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.

refactor(ai): move system prompts from markdown files into new prompt crate (#3911)

Eric Hayesefee988f82c2
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b4826fe2d5..af1161192d 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -140,6 +140,7 @@ dependencies = [
"models_search",
"non_empty",
"notification",
+ "prompt",
"properties",
"rand 0.9.4",
"readonly_pool",
@@ -3383,6 +3384,7 @@ dependencies = [
"models_permissions",
"non_empty",
"notification",
+ "prompt",
"properties",
"readonly_pool",
"redis",
@@ -8915,6 +8917,10 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "prompt"
+version = "0.1.0"
+
[[package]]
name = "properties"
version = "0.1.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 2a16e91730..f2b306c0f9 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -56,7 +56,7 @@ members = [
"user_link_cleanup_handler",
"worker_trigger",
"macro_config"
-]
+, "prompt"]
[workspace.dependencies]
anyhow = "1.0.100"
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 14537b65be..3690da3591 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -50,6 +50,7 @@ models_email = { path = "../models_email" }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions" }
notification = { path = "../notification", features = ["ai_tool"] }
+prompt = { path = "../prompt" }
models_properties = { path = "../models_properties" }
models_search = { path = "../models_search" }
rand.workspace = true
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index e780255460..eb0a404280 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -3,7 +3,6 @@
use ai_toolset::AsyncToolCollection;
use ai_toolset::schema::{CombinedToolSchemas, ToolSchemaGenerator};
mod build_context;
-pub mod prompts;
mod schemas;
pub mod search;
pub mod serde_utils;
@@ -49,7 +48,7 @@ pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
pub struct ToolSetWithPrompt {
pub toolset: Arc<AiToolSet>,
- pub prompt: &'static str,
+ pub prompt: Box<dyn std::fmt::Display + Send + Sync>,
}
impl ToolSchemaGenerator for ToolSetWithPrompt {
@@ -86,9 +85,11 @@ pub fn all_tools() -> ToolSetWithPrompt {
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_toolset())
.add_tool::<Subagent, ToolServiceContext>();
- let prompt = *prompts::TOOLS_PROMPT;
let toolset = Arc::new(toolset);
- ToolSetWithPrompt { toolset, prompt }
+ ToolSetWithPrompt {
+ toolset,
+ prompt: Box::new(&prompt::TOOL_USE_PROMPT),
+ }
}
/// Combined schema with shared, deduplicated `$defs`.
@@ -105,14 +106,16 @@ pub fn mcp_tools() -> ToolSetWithPrompt {
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_mcp_toolset())
.add_tool::<Subagent, ToolServiceContext>();
- let prompt = *prompts::TOOLS_PROMPT;
let toolset = Arc::new(toolset);
- ToolSetWithPrompt { toolset, prompt }
+ ToolSetWithPrompt {
+ toolset,
+ prompt: Box::new(&prompt::TOOL_USE_PROMPT),
+ }
}
pub fn no_tools() -> ToolSetWithPrompt {
ToolSetWithPrompt {
- prompt: prompts::BASE_PROMPT,
+ prompt: Box::new(&prompt::BASE_PROMPT),
toolset: Arc::new(AsyncToolCollection::new()),
}
}
diff --git a/rust/cloud-storage/ai_tools/src/prompts/base.md b/rust/cloud-storage/ai_tools/src/prompts/base.md
deleted file mode 100644
index ca45162af8..0000000000
--- a/rust/cloud-storage/ai_tools/src/prompts/base.md
+++ /dev/null
@@ -1,120 +0,0 @@
-# Tone and Style
-
-- Be correctness-obsessed, precise, and confident.
-- Use a casual, natural tone, but avoid hedging (no “maybe”, “perhaps”).
-- Do not be whiny. Do not use the word “however.”
-- Always use Markdown for formatting.
-
----
-
-# Math Rendering Rules
-
-- Render **all mathematical expressions** (even simple arithmetic) in LaTeX enclosed with double dollar signs `$$ ... $$`.
-- Examples:
- - Simple: $$ 2 + 2 = 4 $$
- - Fractions: $$ \frac{1}{2} $$
- - Quadratic formula: $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
- - Multi-line:
- $$
- \begin{aligned}
- f(x) &= x^2 + 3x + 2 \\
- &= (x+1)(x+2)
- \end{aligned}
- $$
-
----
-
-# Citation Rules
-
-There are two systems: `[[...]]` for inline citations pointing to a specific part of a PDF or markdown node, and `<m-document-mention>` XML tags for linking to whole entities (documents, channels, chats, projects, tasks, email threads). Never mix them.
-
-General citation rules:
-
-- You must include citations from the provided source text when answering.
-- Never fabricate citations.
-- You may cite links by using a standard markdown link: [text](url)
-- To cite documents use the following citation formats. If no id's are present in your converstation chain do not
- cite documents.
-
-Citing Pdfs:
-You can cite a specific part of a pdf by using the ID's that are included in the PDF context.They
-appear in the pdf context as 36-character UUIDs enclosed in double quare brackets `[[uuid]]`
-
-- Include a citation at most once in your final response.
-- Example:
- - Source: “… establish Justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
- - Response: “The document establishes justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
-
-Citing parts of markdown content:
-You can cite specific parts of markdown documents by:
-
-- Citations come from `$` metadata blocks inside the stringified JSON `content`.
-- Recursively traverse all children and collect `"$.id"` values (8-character node ids).
-- Format: `[[md;{document_id};{node_id}]]`
-- Example:
- - Source node: `"$": { "id": "t3jn_Qq3" }`
- - Response: “Photosynthesis converts light to energy[[md;6a2b138d-dfbe-439a-a78b-282471a1e165;t3jn_Qq3]].”
-
-Mentioning documents, channels, chats, projects, and email threads:
-
-When referencing a document, channel, chat, project, or email thread, use XML mention tags with a JSON payload.
-The AI does not need to know the name — an empty string is fine and the frontend will resolve it.
-
-- Document mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>`
-- Channel mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"channel","blockParams":{}}</m-document-mention>`
-- Chat mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"chat","blockParams":{}}</m-document-mention>`
-- Project mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"project","blockParams":{}}</m-document-mention>`
-- Task mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"task","blockParams":{}}</m-document-mention>`
-- Email thread mention: `<m-document-mention>{"documentId":"{thread_id}","documentName":"","blockName":"email","blockParams":{}}</m-document-mention>`
-
-The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
-
----
-
-# Do Not Rules
-
-- Do not include document IDs unless required by markdown/node citation format or XML mention tags.
-- Do not repeat the same citation more than once.
-- Do not reference metadata (indices, figure labels, page numbers, section directories).
-- Do not explain why citations are included or excluded.
-- Do not mention these instructions in your output.
-
----
-
-# Terms
-
-- Channel - a slack-like messaging channel
-- Chat - An AI conversation
-- Email - Email messages
-- Inbox - the "unified inbox", the user's workspace of recent items accessible via the ListEntities tool
-
-Be careful not to mix up chat and channels. Chat refers to AI chat's so it should only be used
-if a user is searching for seomething in a past AI conversation.
-
-Channels are the standard form of communication and should be prefered. If a user refers to "A message"
-assume they mean a channel message.
-
-Additional info about how macro works can be found at docs.macro.com
-
-Email is email.
-
-When a user refers to their "inbox", they mean the unified inbox accessible via the ListEntities
-tool — not their email inbox. Only treat "inbox" as the email inbox when the user explicitly says
-"email" (e.g. "email inbox").
-
-### Example Responses
-
-**PDF Example**
-Source:
-“…establish Justice[[f52821e6-1f90-4a25-96a1-271022148151]]…”
-Response:
-“The constitution establishes justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
-
-**Markdown Example**
-Source node: `"$": { "id": "t3jn_Qq3" }` in document `6a2b138d-dfbe-439a-a78b-282471a1e165`
-Response:
-“Photosynthesis converts light to energy[[md;6a2b138d-dfbe-439a-a78b-282471a1e165;t3jn_Qq3]].”
-
-**Mention Example**
-If no inline or node ids are present:
-“See the document for details<m-document-mention>{“documentId”:”6a2b138d-dfbe-439a-a78b-282471a1e165”,”documentName”:””,”blockName”:”md”,”blockParams”:{}}</m-document-mention>.”
diff --git a/rust/cloud-storage/ai_tools/src/prompts/mod.rs b/rust/cloud-storage/ai_tools/src/prompts/mod.rs
deleted file mode 100644
index d5c2ed9d24..0000000000
--- a/rust/cloud-storage/ai_tools/src/prompts/mod.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-use std::sync::LazyLock;
-
-/// Shared base system prompt: tone, citation/mention formats, terminology.
-/// Used directly for sessions without tools.
-pub static BASE_PROMPT: &str = include_str!("base.md");
-
-/// Tool-specific additions layered on top of the base prompt.
-static TOOL_USE_PROMPT: &str = include_str!("tool_use.md");
-
-/// Full system prompt for tool-enabled sessions: [`BASE_PROMPT`] plus tool-use additions.
-pub static TOOLS_PROMPT: LazyLock<&'static str> = LazyLock::new(|| {
- Box::leak(format!("{BASE_PROMPT}\n\n---\n\n{TOOL_USE_PROMPT}").into_boxed_str())
-});
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 1a1a69490a..85463ed94f 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -86,6 +86,7 @@ models_dcs = { path = "../models_dcs" }
models_opensearch = { path = "../models_opensearch" }
models_permissions = { path = "../models_permissions" }
notification = { path = "../notification" }
+prompt = { path = "../prompt" }
properties = { path = "../properties", features = ["ai_tools"] }
readonly_pool = { path = "../readonly_pool" }
redis = { workspace = true, features = [
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index c1910d147a..d7b2cef35b 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -86,7 +86,7 @@ pub struct ApiContext {
pub call_tool_context: ToolCallToolContext,
pub tool_service_context: ToolServiceContext,
pub all_tools: Arc<AiToolSet>,
- pub all_tools_prompt: &'static str,
+ pub all_tools_prompt: Arc<dyn std::fmt::Display + Send + Sync>,
pub entity_access_service: Arc<DcsEntityAccessService>,
pub message_service: Arc<DcsMessageService>,
pub ai_stream_registry: AiStreamRegistry,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index bfde55f425..bae5de0480 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -331,7 +331,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
- let all_tools_prompt = all_tools.prompt;
+ let all_tools_prompt: Arc<dyn std::fmt::Display + Send + Sync> =
+ Arc::new(all_tools.prompt.to_string());
let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
index d109dfa2cf..eca85e96df 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -290,7 +290,7 @@ async fn send_chat_message_inner(
.flatten();
// Build the chat messages
- let tools_prompt = choose_tools_prompt(&payload, ctx.all_tools_prompt);
+ let tools_prompt = choose_tools_prompt(&payload, &*ctx.all_tools_prompt);
let ai_request = build_chat_messages(&chat, &payload, all_resolved_parts).map_err(|err| {
tracing::error!(error=?err, "failed to build chat messages");
ChatMessageError {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
index e9bdf535dc..dc80289aee 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
@@ -3,12 +3,12 @@ use crate::model::stream::ToolSet;
use crate::model::stream::SendChatMessagePayload;
/// Returns the appropriate system prompt for the requested toolset.
-pub fn choose_tools_prompt(
+pub fn choose_tools_prompt<'a>(
request: &SendChatMessagePayload,
- all_tools_prompt: &'static str,
-) -> &'static str {
+ all_tools_prompt: &'a (dyn std::fmt::Display + Sync),
+) -> &'a (dyn std::fmt::Display + Sync) {
match request.toolset {
ToolSet::All => all_tools_prompt,
- ToolSet::None => ai_tools::prompts::BASE_PROMPT,
+ ToolSet::None => &prompt::BASE_PROMPT,
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
index 801ca168f3..f0997125ec 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
@@ -80,9 +80,9 @@ pub async fn structured_completion(
}
})?;
- let tools_prompt = match request.toolset {
- ToolSet::All => ctx.all_tools_prompt,
- ToolSet::None => ai_tools::prompts::BASE_PROMPT,
+ let tools_prompt: &(dyn std::fmt::Display + Sync) = match request.toolset {
+ ToolSet::All => &ctx.all_tools_prompt,
+ ToolSet::None => &prompt::BASE_PROMPT,
};
let system_prompt = match &request.additional_instructions {
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index b3911cff99..ce2eabeaba 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -388,7 +388,8 @@ async fn main() -> anyhow::Result<()> {
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
- let all_tools_prompt = all_tools.prompt;
+ let all_tools_prompt: Arc<dyn std::fmt::Display + Send + Sync> =
+ Arc::new(all_tools.prompt.to_string());
// Build memory service
let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(db.clone());
diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rs
index 6efffd3b21..fac4a1cf2b 100644
--- a/rust/cloud-storage/memory/src/domain/service.rs
+++ b/rust/cloud-storage/memory/src/domain/service.rs
@@ -118,7 +118,8 @@ where
let pool = self.db.clone();
let tool_context = self.tool_context.clone();
let toolset = self.tools.toolset.clone();
- let prompt = self.tools.prompt;
+ let prompt: Box<dyn std::fmt::Display + Send + Sync> =
+ Box::new(self.tools.prompt.to_string());
tokio::spawn(async move {
let repo = crate::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
let tools = ToolSetWithPrompt { toolset, prompt };
@@ -149,7 +150,7 @@ where
) -> super::Result<Memory> {
// append user data + datetime to prompt
let system_prompt = build_generation_system_prompt(
- self.tools.prompt,
+ &self.tools.prompt,
&user,
&Utc::now().to_rfc2822(),
previous_memory.as_deref(),
@@ -200,7 +201,7 @@ where
}
fn build_generation_system_prompt(
- base_prompt: &str,
+ base_prompt: impl std::fmt::Display,
user: &macro_user_id::user_id::MacroUserIdStr<'_>,
datetime: &str,
previous_memory: Option<&str>,
diff --git a/rust/cloud-storage/prompt/Cargo.toml b/rust/cloud-storage/prompt/Cargo.toml
new file mode 100644
index 0000000000..30a21c5cd9
--- /dev/null
+++ b/rust/cloud-storage/prompt/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "prompt"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
diff --git a/rust/cloud-storage/prompt/src/about_macro.rs b/rust/cloud-storage/prompt/src/about_macro.rs
new file mode 100644
index 0000000000..40ef7a7063
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/about_macro.rs
@@ -0,0 +1,32 @@
+//! Macro-specific terminology and product context.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Terms";
+
+static INSTRUCTIONS: &str = r##"- Channel - a slack-like messaging channel
+- Chat - An AI conversation
+- Email - Email messages
+- Inbox - the "unified inbox", the user's workspace of recent items accessible via the ListEntities tool
+
+Be careful not to mix up chat and channels. Chat refers to AI chat's so it should only be used
+if a user is searching for seomething in a past AI conversation.
+
+Channels are the standard form of communication and should be prefered. If a user refers to "A message"
+assume they mean a channel message.
+
+Additional info about how macro works can be found at docs.macro.com
+
+Email is email.
+
+When a user refers to their "inbox", they mean the unified inbox accessible via the ListEntities
+tool — not their email inbox. Only treat "inbox" as the email inbox when the user explicitly says
+"email" (e.g. "email inbox").
+"##;
+
+static INTENT: &str = "The model uses Macro terminology correctly: channels for messaging, \
+chats only for past AI conversations, and \"inbox\" as the unified inbox unless the user \
+explicitly says email.";
+
+/// about macro promp
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/citations.rs b/rust/cloud-storage/prompt/src/citations.rs
new file mode 100644
index 0000000000..1d9fdfe3e0
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/citations.rs
@@ -0,0 +1,55 @@
+//! Rules for citing source material inline.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Citation Rules";
+
+static INSTRUCTIONS: &str = r##"There are two systems: `[[...]]` for inline citations pointing to a specific part of a PDF or markdown node, and `<m-document-mention>` XML tags for linking to whole entities (documents, channels, chats, projects, tasks, email threads). Never mix them.
+
+General citation rules:
+
+- You must include citations from the provided source text when answering.
+- Never fabricate citations.
+- You may cite links by using a standard markdown link: [text](url)
+- To cite documents use the following citation formats. If no id's are present in your converstation chain do not
+ cite documents.
+
+Citing Pdfs:
+You can cite a specific part of a pdf by using the ID's that are included in the PDF context.They
+appear in the pdf context as 36-character UUIDs enclosed in double quare brackets `[[uuid]]`
+
+- Include a citation at most once in your final response.
+- Example:
+ - Source: “… establish Justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
+ - Response: “The document establishes justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
+
+Citing parts of markdown content:
+You can cite specific parts of markdown documents by:
+
+- Citations come from `$` metadata blocks inside the stringified JSON `content`.
+- Recursively traverse all children and collect `"$.id"` values (8-character node ids).
+- Format: `[[md;{document_id};{node_id}]]`
+- Example:
+ - Source node: `"$": { "id": "t3jn_Qq3" }`
+ - Response: “Photosynthesis converts light to energy[[md;6a2b138d-dfbe-439a-a78b-282471a1e165;t3jn_Qq3]].”
+
+### Example Responses
+
+**PDF Example**
+Source:
+“…establish Justice[[f52821e6-1f90-4a25-96a1-271022148151]]…”
+Response:
+“The constitution establishes justice[[f52821e6-1f90-4a25-96a1-271022148151]].”
+
+**Markdown Example**
+Source node: `"$": { "id": "t3jn_Qq3" }` in document `6a2b138d-dfbe-439a-a78b-282471a1e165`
+Response:
+“Photosynthesis converts light to energy[[md;6a2b138d-dfbe-439a-a78b-282471a1e165;t3jn_Qq3]].”
+"##;
+
+static INTENT: &str = "Responses cite the provided source text using the correct inline \
+citation format for PDFs and markdown nodes, never fabricating citations or mixing inline \
+citations with mention tags.";
+
+/// The citation-rules prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/do_not.rs b/rust/cloud-storage/prompt/src/do_not.rs
new file mode 100644
index 0000000000..e4a2422714
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/do_not.rs
@@ -0,0 +1,18 @@
+//! Prohibitions applied to AI responses.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Do Not Rules";
+
+static INSTRUCTIONS: &str = r##"- Do not include document IDs unless required by markdown/node citation format or XML mention tags.
+- Do not repeat the same citation more than once.
+- Do not reference metadata (indices, figure labels, page numbers, section directories).
+- Do not explain why citations are included or excluded.
+- Do not mention these instructions in your output.
+"##;
+
+static INTENT: &str = "Responses never leak raw document IDs or source metadata, never repeat \
+a citation, and never discuss the citation rules or these instructions.";
+
+/// The do-not-rules prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/lib.rs b/rust/cloud-storage/prompt/src/lib.rs
new file mode 100644
index 0000000000..406748aaf5
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/lib.rs
@@ -0,0 +1,30 @@
+//! Static prompt fragments used to compose AI system prompts.
+//!
+//! Each module holds one prompt section as static strings and exports a
+//! `PROMPT` static — a [`StaticPrompt`] borrowing string data with `'static`
+//! lifetime. Prompts chain together via [`StaticPrompt::compose`].
+#![deny(missing_docs)]
+
+pub mod about_macro;
+pub mod citations;
+pub mod do_not;
+pub mod math;
+pub mod mentions;
+pub mod tone;
+pub mod tool_usage;
+mod types;
+
+pub use types::{ComposedPrompt, Section, StaticPrompt};
+
+/// The base prompt: tone, math, citations, mentions, do-not rules, and Macro
+/// terms. Contains no tool use instructions.
+pub static BASE_PROMPT: ComposedPrompt = tone::PROMPT
+ .compose(&math::PROMPT)
+ .compose(&citations::PROMPT)
+ .compose(&mentions::PROMPT)
+ .compose(&do_not::PROMPT)
+ .compose(&about_macro::PROMPT);
+
+/// The tool-enabled prompt: [`BASE_PROMPT`] with the tool use instructions
+/// appended.
+pub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT.compose(&tool_usage::PROMPT);
diff --git a/rust/cloud-storage/prompt/src/math.rs b/rust/cloud-storage/prompt/src/math.rs
new file mode 100644
index 0000000000..99cef8f6bb
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/math.rs
@@ -0,0 +1,25 @@
+//! Rules for rendering mathematical expressions.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Math Rendering Rules";
+
+static INSTRUCTIONS: &str = r##"- Render **all mathematical expressions** (even simple arithmetic) in LaTeX enclosed with double dollar signs `$$ ... $$`.
+- Examples:
+ - Simple: $$ 2 + 2 = 4 $$
+ - Fractions: $$ \frac{1}{2} $$
+ - Quadratic formula: $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
+ - Multi-line:
+ $$
+ \begin{aligned}
+ f(x) &= x^2 + 3x + 2 \\
+ &= (x+1)(x+2)
+ \end{aligned}
+ $$
+"##;
+
+static INTENT: &str = "All mathematical expressions, including simple arithmetic, are rendered \
+as LaTeX enclosed in double dollar signs.";
+
+/// The math-rendering prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/mentions.rs b/rust/cloud-storage/prompt/src/mentions.rs
new file mode 100644
index 0000000000..14b813e937
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/mentions.rs
@@ -0,0 +1,30 @@
+//! Rules for mentioning whole entities with XML mention tags.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Mentioning documents, channels, chats, projects, and email threads";
+
+static INSTRUCTIONS: &str = r##"When referencing a document, channel, chat, project, or email thread, use XML mention tags with a JSON payload.
+The AI does not need to know the name — an empty string is fine and the frontend will resolve it.
+
+- Document mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>`
+- Channel mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"channel","blockParams":{}}</m-document-mention>`
+- Chat mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"chat","blockParams":{}}</m-document-mention>`
+- Project mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"project","blockParams":{}}</m-document-mention>`
+- Task mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"task","blockParams":{}}</m-document-mention>`
+- Email thread mention: `<m-document-mention>{"documentId":"{thread_id}","documentName":"","blockName":"email","blockParams":{}}</m-document-mention>`
+
+The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
+
+### Example Response
+
+If no inline or node ids are present:
+“See the document for details<m-document-mention>{“documentId”:”6a2b138d-dfbe-439a-a78b-282471a1e165”,”documentName”:””,”blockName”:”md”,”blockParams”:{}}</m-document-mention>.”
+"##;
+
+static INTENT: &str = "Whole entities are referenced with correctly formatted \
+<m-document-mention> XML tags using the right blockName for each entity type, including \
+exactly \"email\" for email threads.";
+
+/// The entity-mention prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/tone.rs b/rust/cloud-storage/prompt/src/tone.rs
new file mode 100644
index 0000000000..147e37306a
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/tone.rs
@@ -0,0 +1,17 @@
+//! Tone and style rules for AI responses.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Tone and Style";
+
+static INSTRUCTIONS: &str = r##"- Be correctness-obsessed, precise, and confident.
+- Use a casual, natural tone, but avoid hedging (no “maybe”, “perhaps”).
+- Do not be whiny. Do not use the word “however.”
+- Always use Markdown for formatting.
+"##;
+
+static INTENT: &str = "Responses are confident, precise, and casual, formatted in Markdown, \
+without hedging language or the word \"however\".";
+
+/// The tone-and-style prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/ai_tools/src/prompts/tool_use.md b/rust/cloud-storage/prompt/src/tool_usage.rs
similarity index 76%
rename from rust/cloud-storage/ai_tools/src/prompts/tool_use.md
rename to rust/cloud-storage/prompt/src/tool_usage.rs
index 4c20631c61..9340f88171 100644
--- a/rust/cloud-storage/ai_tools/src/prompts/tool_use.md
+++ b/rust/cloud-storage/prompt/src/tool_usage.rs
@@ -1,17 +1,21 @@
-# Tone and Style Additions
+//! Tool-use behavior, plus tone additions for tool-driven conversations.
+
+use crate::types::StaticPrompt;
+
+static TITLE: &str = "Tool Use";
+
+static INSTRUCTIONS: &str = r##"## Tone and Style Additions
- Write casual, text-message style prose
- Avoid using formal formatting like bullet points, tables, and headings
- Use short paragraphs
- Use citations often
----
+## Tool Use
-# Tool Use
-
-- User tools are tools that must be executed by a user on the frontend.
- A user tool will return "PendingUserExecution" until a user chooses to
- accept / reject the tool.
+- User tools are tools that must be executed by a user on the frontend.
+ A user tool will return "PendingUserExecution" until a user chooses to
+ accept / reject the tool.
- Use tools often and specifically.
- Prefer precise filters (domain names, IDs) over generic queries.
@@ -23,8 +27,8 @@
using XML mention tags (e.g. `<m-document-mention>`). Always use a mention if the tool
returns anything relavent. IMPORTANT
-- IMPORTANT: The code execution tools (`bash_code_execution`, and `text_editor_code_execution`) should only be used
-when the user explicitely asks you to _execute_ code.
+- IMPORTANT: The code execution tools (`bash_code_execution`, and `text_editor_code_execution`) should only be used
+when the user explicitely asks you to _execute_ code.
- DO NOT confuse `text_editor_code_execution` tool
(which creates a file for the code execution environment) for the `CreateDocument` tool which creates a document in the
@@ -42,3 +46,11 @@ users workspace. If the user asks you to create a document, write a code file, o
asking for something specifi like "someone mentioned ..." prefer search
if they are asking for summaries of messages or emails prefer listing.
After collecting information read the appropriate resource using the read tool.
+"##;
+
+static INTENT: &str = "The model proactively uses tools with precise filters instead of \
+claiming it lacks context, cites relevant tool results with mention tags, reserves code \
+execution for explicit requests, and uses CreateDocument for files in the user's workspace.";
+
+/// The tool-use prompt.
+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/rust/cloud-storage/prompt/src/types.rs b/rust/cloud-storage/prompt/src/types.rs
new file mode 100644
index 0000000000..793417954e
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/types.rs
@@ -0,0 +1,71 @@
+use std::borrow::Cow;
+use std::fmt::Display;
+
+/// A prompt passed to AI
+pub struct StaticPrompt<'a> {
+ /// Instructions passed to model in request
+ pub instructions: Cow<'a, str>,
+ /// Intent of the request used for testing
+ pub intent: Cow<'a, str>,
+ /// A title to deliminate the prompt in composition
+ pub title: Cow<'a, str>,
+}
+
+impl<'a> StaticPrompt<'a> {
+ /// Build a prompt from borrowed strings. `const` so modules can declare
+ /// a `pub static` `StaticPrompt<'static>` built entirely at compile time.
+ pub const fn borrowed(title: &'a str, instructions: &'a str, intent: &'a str) -> Self {
+ Self {
+ instructions: Cow::Borrowed(instructions),
+ intent: Cow::Borrowed(intent),
+ title: Cow::Borrowed(title),
+ }
+ }
+}
+
+impl StaticPrompt<'static> {
+ /// Chain another section after this prompt, starting a [`ComposedPrompt`].
+ pub const fn compose(&'static self, next: Section) -> ComposedPrompt {
+ ComposedPrompt {
+ left: self,
+ right: next,
+ }
+ }
+}
+
+impl<'a> Display for StaticPrompt<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ writeln!(f, "# {}\n{}", self.title, self.instructions)
+ }
+}
+
+/// A prompt section that can take part in a composition: any `'static`
+/// renderable value, e.g. a `StaticPrompt` or another [`ComposedPrompt`].
+pub type Section = &'static (dyn Display + Sync);
+
+/// Prompt sections chained together, rendered in composition order via
+/// [`Display`]. Built by calling `compose` on a [`StaticPrompt`] and chaining
+/// further `compose` calls; inside a `static` initializer the intermediate
+/// compositions get `'static` lifetime, so the whole chain is built at
+/// compile time.
+pub struct ComposedPrompt {
+ left: Section,
+ right: Section,
+}
+
+impl ComposedPrompt {
+ /// Chain another section after this composition.
+ pub const fn compose(&'static self, next: Section) -> ComposedPrompt {
+ ComposedPrompt {
+ left: self,
+ right: next,
+ }
+ }
+}
+
+impl Display for ComposedPrompt {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ Display::fmt(self.left, f)?;
+ Display::fmt(self.right, f)
+ }
+}
diff --git a/rust/cloud-storage/prompt/tests/compose.rs b/rust/cloud-storage/prompt/tests/compose.rs
new file mode 100644
index 0000000000..e7cc9cfd87
--- /dev/null
+++ b/rust/cloud-storage/prompt/tests/compose.rs
@@ -0,0 +1,37 @@
+//! Rendering tests for the composed prompts exported from the crate root.
+
+use prompt::{BASE_PROMPT, TOOL_USE_PROMPT};
+
+const BASE_TITLES: [&str; 6] = [
+ "# Tone and Style",
+ "# Math Rendering Rules",
+ "# Citation Rules",
+ "# Mentioning documents, channels, chats, projects, and email threads",
+ "# Do Not Rules",
+ "# Terms",
+];
+
+#[test]
+fn base_prompt_renders_all_sections_in_order() {
+ let rendered = BASE_PROMPT.to_string();
+ let mut last = 0;
+ for title in BASE_TITLES {
+ let position = rendered[last..]
+ .find(title)
+ .unwrap_or_else(|| panic!("missing or out-of-order section: {title}"));
+ last += position + title.len();
+ }
+ assert!(!rendered.contains("# Tool Use"));
+}
+
+#[test]
+fn tool_use_prompt_appends_tool_section_to_base() {
+ let rendered = TOOL_USE_PROMPT.to_string();
+ assert!(rendered.starts_with(&BASE_PROMPT.to_string()));
+ assert!(
+ rendered
+ .trim_end()
+ .ends_with("read the appropriate resource using the read tool.")
+ );
+ assert!(rendered.contains("# Tool Use"));
+}