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(ai): AI CLI (#1041)
Eric Hayes3df73e692920
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex c6fe2d204e..100fd318eb 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -58,6 +58,7 @@ dependencies = ["futures","image","lazy_static",+ "macro_user_id","model_file_type","rand 0.9.0","reqwest",diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.tomlindex b91a242423..4dc5cabb17 100644--- a/rust/cloud-storage/ai/Cargo.toml+++ b/rust/cloud-storage/ai/Cargo.toml@@ -4,8 +4,11 @@ name = "ai"publish = falseversion = "0.1.0"+[[bin]]+name = "cli"+path = "src/bin/cli.rs"+[dev-dependencies]-tokio = { workspace = true }[dependencies]anyhow = { workspace = true }@@ -30,6 +33,7 @@ tracing = { workspace = true }utoipa = { workspace = true }anthropic = { path = "../anthropic" }ai_toolset = { path = "../ai_toolset" }+macro_user_id = { path = "../macro_user_id" }base64 = { workspace = true }image = "0.25.9"webp = "0.3.1"diff --git a/rust/cloud-storage/ai/src/bin/cli.rs b/rust/cloud-storage/ai/src/bin/cli.rsnew file mode 100644index 0000000000..369a434484--- /dev/null+++ b/rust/cloud-storage/ai/src/bin/cli.rs@@ -0,0 +1,6 @@+use ai::tool::Cli;++#[tokio::main]+async fn main() {+ Cli::default().run().await;+}diff --git a/rust/cloud-storage/ai/src/lib.rs b/rust/cloud-storage/ai/src/lib.rsindex f9ad9e7d2a..6bfbdd9c6f 100644--- a/rust/cloud-storage/ai/src/lib.rs+++ b/rust/cloud-storage/ai/src/lib.rs@@ -3,6 +3,7 @@ pub mod chat_stream;mod constants;pub mod model_selection;mod openai_toolset;+pub mod prompts;pub mod simple_completion;pub mod structured_output;pub mod structured_output_v2;diff --git a/rust/cloud-storage/ai/src/prompts/base.md b/rust/cloud-storage/ai/src/prompts/base.mdnew file mode 100644index 0000000000..1617a7ee2f--- /dev/null+++ b/rust/cloud-storage/ai/src/prompts/base.md@@ -0,0 +1,105 @@+# 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++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]]."++Citing documents, channels, chats, and projects:++- Use when no inline/node citations are present:+ - Document mention: `[[document-mention;{documentId}]]`+ - Channel mention: `[[channel-mention;{channelId}]]`+ - Chat mention: `[[chat-mention;{chatId}]]`+ - Project mention: `[[project-mention;{projectId}]]`++---++# Do Not Rules++- Do not include document IDs unless required by markdown/node citation format or mention format.+- 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++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.++Email is email.++### 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[[document-mention;6a2b138d-dfbe-439a-a78b-282471a1e165]]."diff --git a/rust/cloud-storage/ai/src/prompts/mod.rs b/rust/cloud-storage/ai/src/prompts/mod.rsnew file mode 100644index 0000000000..d7bf33c503--- /dev/null+++ b/rust/cloud-storage/ai/src/prompts/mod.rs@@ -0,0 +1,4 @@+//! Default prompts for the AI crate.++/// Base prompt for AI interactions.+pub const BASE_PROMPT: &str = include_str!("base.md");diff --git a/rust/cloud-storage/ai/src/tool/mod.rs b/rust/cloud-storage/ai/src/tool/mod.rsindex 473fd6f37a..98de7c50e6 100644--- a/rust/cloud-storage/ai/src/tool/mod.rs+++ b/rust/cloud-storage/ai/src/tool/mod.rs@@ -5,5 +5,6 @@ pub mod types;pub use ai_toolset::generate_tool_input_schema;pub use ai_toolset::generate_tool_output_schema;pub use tool_loop::ai_client::ToolLoop;+pub use tool_loop::cli::Cli;pub use types::tool_object::minimized_output_schema_generator;pub use types::*;diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rsnew file mode 100644index 0000000000..6438c7f5c9--- /dev/null+++ b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs@@ -0,0 +1,285 @@+//! CLI interface for the Chat tool loop.+//!+//! This module provides a simple CLI frontend that consumes the existing+//! `Chat` tool loop, allowing developers to test toolsets interactively+//! from the command line.+//!+//! # Example with custom toolset+//!+//! ```rust,ignore+//! use ai::tool::tool_loop::cli::Cli;+//! use ai::tool::{AsyncToolSet, RequestContext};+//! use ai::types::Model;+//! use macro_user_id::user_id::MacroUserIdStr;+//! use std::sync::Arc;+//!+//! #[tokio::main]+//! async fn main() {+//! let toolset = AsyncToolSet::new()+//! .add_tool::<MyTool>()+//! .expect("failed to add tool");+//!+//! let cli = Cli::new(+//! toolset,+//! MyServiceContext::new(),+//! "You are a helpful assistant.",+//! Model::Claude35Sonnet,+//! || RequestContext {+//! user_id: Arc::new(MacroUserIdStr::try_from_email("[email protected]").unwrap()),+//! jwt: Arc::new(String::new()),+//! },+//! );+//! cli.run().await;+//! }+//! ```+//!+//! # Example with default (no tools)+//!+//! ```rust,ignore+//! use ai::tool::tool_loop::cli::Cli;+//!+//! #[tokio::main]+//! async fn main() {+//! Cli::default().run().await;+//! }+//! ```++use crate::prompts::BASE_PROMPT;+use crate::tool::ToolLoop;+use crate::tool::types::{AsyncToolSet, RequestContext, StreamPart, ToolResponse};+use crate::types::{ChatMessage, MessageBuilder, Model, RequestBuilder, Role};+use futures::stream::StreamExt;+use macro_user_id::user_id::MacroUserIdStr;+use std::io::{self, BufRead, Write};+use std::sync::Arc;++/// CLI interface for the Chat tool loop.+///+/// This struct wraps the tool loop and provides an interactive readline-style+/// interface for multi-turn conversations with tool support.+pub struct Cli<T, F>+where+ T: Clone + Send + Sync + 'static,+ F: Fn() -> RequestContext,+{+ toolset: AsyncToolSet<T>,+ service_context: T,+ system_prompt: String,+ model: Model,+ request_context_fn: F,+}++impl Default for Cli<(), fn() -> RequestContext> {+ fn default() -> Self {+ Self {+ toolset: AsyncToolSet::new(),+ service_context: (),+ system_prompt: BASE_PROMPT.to_string(),+ model: Model::Claude45Opus,+ #[allow(deprecated)]+ request_context_fn: || RequestContext {+ user_id: Arc::new(+ MacroUserIdStr::try_from_email("cli@localhost").expect("valid email"),+ ),+ jwt: Arc::new(String::new()),+ },+ }+ }+}++impl<T, F> Cli<T, F>+where+ T: Clone + Send + Sync + 'static,+ F: Fn() -> RequestContext,+{+ /// Create a new CLI with the given configuration.+ ///+ /// # Arguments+ ///+ /// * `toolset` - The async toolset to use for tool calls+ /// * `service_context` - The service context passed to tools+ /// * `system_prompt` - The system prompt for the AI+ /// * `model` - The model to use for completions+ /// * `request_context_fn` - A function that creates a request context for each message+ pub fn new(+ toolset: AsyncToolSet<T>,+ service_context: T,+ system_prompt: impl Into<String>,+ model: Model,+ request_context_fn: F,+ ) -> Self {+ Self {+ toolset,+ service_context,+ system_prompt: system_prompt.into(),+ model,+ request_context_fn,+ }+ }++ /// Run the interactive CLI session.+ ///+ /// This provides a readline-style interface that:+ /// - Reads user input from stdin+ /// - Sends messages through the Chat tool loop+ /// - Streams responses to stdout+ /// - Displays tool calls and responses+ /// - Maintains conversation history across turns+ ///+ /// The session ends when the user types "exit" or "quit", or when stdin closes.+ pub async fn run(self) {+ // Print startup info+ println!("Model: {}", self.model);+ let tool_names: Vec<&String> = self.toolset.tools.keys().collect();+ if tool_names.is_empty() {+ println!("Tools: (none)");+ } else {+ println!(+ "Tools: {}",+ tool_names+ .into_iter()+ .cloned()+ .collect::<Vec<_>>()+ .join(", ")+ );+ }+ println!("---");++ let tool_loop = ToolLoop::new(self.toolset, self.service_context);++ let stdin = io::stdin();+ let mut stdout = io::stdout();+ let mut messages: Vec<ChatMessage> = Vec::new();++ println!("Type 'exit' or 'quit' to end.");+ println!("---");++ loop {+ print!("> ");+ if stdout.flush().is_err() {+ break;+ }++ let input = {+ let handle = stdin.lock();+ match handle.lines().next() {+ Some(Ok(line)) => line,+ Some(Err(_)) | None => break,+ }+ };++ let input = input.trim();++ if input.eq_ignore_ascii_case("exit") || input.eq_ignore_ascii_case("quit") {+ println!("Goodbye!");+ break;+ }++ if input.is_empty() {+ continue;+ }++ messages.push(+ MessageBuilder::new()+ .content(input)+ .role(Role::User)+ .build(),+ );++ let request = RequestBuilder::new()+ .system_prompt(&self.system_prompt)+ .messages(messages.clone())+ .model(self.model)+ .build();++ let mut chat = tool_loop.chat();+ let request_context = (self.request_context_fn)();++ // Process stream in a scope so it's dropped before accessing chat+ let stream_error = {+ let stream_result = chat+ .send_message(request, request_context, "cli-user".to_string())+ .await;++ let mut stream = match stream_result {+ Ok(s) => s,+ Err(e) => {+ eprintln!("\nError: {}", e);+ messages.pop();+ continue;+ }+ };++ let mut has_content = false;+ let mut error_occurred = false;++ while let Some(result) = stream.next().await {+ match result {+ Ok(part) => match part {+ StreamPart::Content(content) => {+ print!("{}", content);+ let _ = stdout.flush();+ has_content = true;+ }+ StreamPart::ToolCall(call) => {+ if has_content {+ println!();+ }+ println!("\n[Tool Call: {}]", call.name);+ if let Ok(pretty) = serde_json::to_string_pretty(&call.json) {+ println!("{}", pretty);+ }+ has_content = false;+ }+ StreamPart::ToolResponse(response) => {+ match &response {+ ToolResponse::Json { name, json, .. } => {+ println!("\n[Tool Response: {}]", name);+ if let Ok(pretty) = serde_json::to_string_pretty(json) {+ let display = if pretty.len() > 500 {+ format!("{}...(truncated)", &pretty[..500])+ } else {+ pretty+ };+ println!("{}", display);+ }+ }+ ToolResponse::Err {+ name, description, ..+ } => {+ println!("\n[Tool Error: {}]", name);+ println!("{}", description);+ }+ }+ println!();+ }+ StreamPart::Usage(usage) => {+ tracing::debug!(usage=?usage, "token usage");+ }+ },+ Err(e) => {+ eprintln!("\nStream error: {}", e);+ error_occurred = true;+ break;+ }+ }+ }++ if has_content {+ println!();+ }+ println!("---");++ error_occurred+ };++ if stream_error {+ messages.pop();+ continue;+ }++ let new_messages = chat.get_new_conversation_messages();+ messages.extend(new_messages);+ }+ }+}diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs b/rust/cloud-storage/ai/src/tool/tool_loop/mod.rsindex 34be565164..7191e6d79c 100644--- a/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs+++ b/rust/cloud-storage/ai/src/tool/tool_loop/mod.rs@@ -1,4 +1,5 @@pub mod ai_client;pub mod chained;pub mod chat;+pub mod cli;pub mod constant;