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
chore: remove jwt from RequestContext (#2118)
Eric Hayes20780943803e
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex d893fc7ac4..f7e8f40de4 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6091,8 +6091,6 @@ dependencies = ["axum","chrono","comms",- "comms_service_client",- "document_cognition_service_client","document_storage_service_client","documents","email",@@ -8683,21 +8681,23 @@ dependencies = ["anyhow","base64 0.22.1","bytes",+ "chat","chrono","comms_db_client",- "comms_service_client","derive_builder",- "document_cognition_service_client","document_storage_service_client","doppleganger","email_service_client","futures","lexical_client","macro_client_errors",+ "macro_db_client",+ "macro_user_id","model","models_comms","models_dcs","models_email",+ "models_permissions","models_properties","models_sfs","properties_db_client",diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rsindex cabb66b05d..0f1def59dd 100644--- a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs+++ b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs@@ -26,7 +26,6 @@//! Model::Claude35Sonnet,//! || RequestContext {//! user_id: Arc::new(MacroUserIdStr::try_from_email("[email protected]").unwrap()),-//! jwt: Arc::new(String::new()),//! },//! );//! cli.run().await;@@ -76,10 +75,8 @@ impl Default for Cli<(), fn() -> RequestContext> {service_context: (),system_prompt: CLI_PROMPT.to_string(),model: Model::Claude45Opus,- #[allow(deprecated)]request_context_fn: || RequestContext {user_id: MacroUserIdStr::try_from_email("cli@localhost").expect("valid email"),- jwt: Arc::new(String::new()),},}}diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rsindex 4beda4c328..b1f381d80e 100644--- a/rust/cloud-storage/ai_tools/src/read.rs+++ b/rust/cloud-storage/ai_tools/src/read.rs@@ -144,14 +144,12 @@ impl AsyncTool<Arc<ToolScribe>> for ReadThread {}let content = match self.content_type {- ContentType::Channel => self.read_channel(&scribe, &request_context).await?,- ContentType::ChannelMessage => {- self.read_channel_message(&scribe, &request_context).await?- }- ContentType::ChatThread => self.read_chat_thread(&scribe, &request_context).await?,- ContentType::ChatMessage => self.read_chat_messages(&scribe, &request_context).await?,- ContentType::EmailThread => self.read_email_thread(&scribe, &request_context).await?,- ContentType::EmailMessage => self.read_email_message(&scribe, &request_context).await?,+ ContentType::Channel => self.read_channel(&scribe).await?,+ ContentType::ChannelMessage => self.read_channel_message(&scribe).await?,+ ContentType::ChatThread => self.read_chat_thread(&scribe).await?,+ ContentType::ChatMessage => self.read_chat_messages(&scribe).await?,+ ContentType::EmailThread => self.read_email_thread(&scribe).await?,+ ContentType::EmailMessage => self.read_email_message(&scribe).await?,ContentType::Project => self.read_project(&scribe, &request_context).await?,};@@ -177,7 +175,6 @@ impl ReadThread {Ok(self.ids[0].clone())}- #[allow(deprecated)]async fn read_project(&self,scribe: &ToolScribe,@@ -188,26 +185,20 @@ impl ReadThread {internal_error: anyhow!("Bad tool args"),})?;- scribe- .document- .fetch_project(id.to_owned(), (*request_context.jwt).clone())- .content()+ let fetcher = scribe.document.fetch_project(id.to_owned());+ fetcher+ .content(scribe.document.db(), request_context.user_id.clone()).await.map_err(|err| ToolCallError {description: "failed to fetch project".into(),internal_error: err,})- .map(|s| ReadContent::ItemPreviews {- formatted_preview: s.to_string(),+ .map(|f| ReadContent::ItemPreviews {+ formatted_preview: f.to_string(),})}- #[allow(deprecated)]- async fn read_channel(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- ) -> Result<ReadContent, ToolCallError> {+ async fn read_channel(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {let id = self.provide_single_id()?;let since = self@@ -216,7 +207,7 @@ impl ReadThread {// Get channel metadatalet metadata = scribe.channel- .get_channel_metadata(id.as_str(), Some(&*request_context.jwt))+ .get_channel_metadata(id.as_str()).await.map_err(|e| ToolCallError {description: format!("failed to fetch channel metadata: {}", e),@@ -226,12 +217,7 @@ impl ReadThread {// Get channel transcriptlet transcript = scribe.channel- .get_channel_transcript(- id.as_str(),- Some(&*request_context.jwt),- Some(since),- Some(MAX_MESSAGES),- )+ .get_channel_transcript(id.as_str(), Some(since), Some(MAX_MESSAGES)).await.map_err(|e| ToolCallError {description: format!("failed to fetch channel transcript: {}", e),@@ -245,11 +231,9 @@ impl ReadThread {})}- #[allow(deprecated)]async fn read_channel_message(&self,scribe: &ToolScribe,- request_context: &RequestContext,) -> Result<ReadContent, ToolCallError> {let mut transcripts = Vec::new();let mut channel_id = String::new();@@ -258,7 +242,7 @@ impl ReadThread {// Get messages with contextlet transcript = match scribe.channel- .get_message_with_context(id.as_str(), 0, 0, &request_context.jwt)+ .get_message_with_context(id.as_str(), 0, 0).await{Ok(t) => t,@@ -300,16 +284,11 @@ impl ReadThread {})}- #[allow(deprecated)]- async fn read_chat_thread(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- ) -> Result<ReadContent, ToolCallError> {+ async fn read_chat_thread(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {let id = self.provide_single_id()?;let history = scribe.chat- .get_chat_history(&id, &request_context.jwt)+ .get_chat_history(&id).await.map_err(|e| ToolCallError {description: format!("failed to fetch chat thread: {}", e),@@ -319,17 +298,12 @@ impl ReadThread {Ok(ReadContent::Chat { history })}- #[allow(deprecated)]- async fn read_chat_messages(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- ) -> Result<ReadContent, ToolCallError> {+ async fn read_chat_messages(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {let message_ids = &self.ids;let history = scribe.chat- .get_chat_history_for_messages(message_ids, &request_context.jwt)+ .get_chat_history_for_messages(message_ids).await.map_err(|e| ToolCallError {description: format!("failed to fetch chat messages: {}", e),@@ -339,16 +313,11 @@ impl ReadThread {Ok(ReadContent::Chat { history })}- #[allow(deprecated)]- async fn read_email_thread(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- ) -> Result<ReadContent, ToolCallError> {+ async fn read_email_thread(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {let id = self.provide_single_id()?;let messages = scribe- .get_email_messages_by_thread_id(&id, 0, 100, Some(&*request_context.jwt))+ .get_email_messages_by_thread_id(&id, 0, 100).await.map_err(|e| ToolCallError {description: format!("failed to fetch email thread messages: {}", e),@@ -365,22 +334,13 @@ impl ReadThread {})}- #[allow(deprecated)]- async fn read_email_message(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- ) -> Result<ReadContent, ToolCallError> {+ async fn read_email_message(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {let mut email_messages = Vec::new();let mut subject = None;let mut thread_id = String::new();for id in &self.ids {- let parsed_message = match scribe- .get_email_message_by_id(id, Some(&*request_context.jwt))- .await- {+ let parsed_message = match scribe.email.get_email_message_by_id(id).await {Ok(msg) => msg,Err(e) => {tracing::warn!("failed to fetch email message {}: {}", id, e);diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rsindex cbbe60610b..0d7e15881f 100644--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs@@ -31,7 +31,6 @@ pub struct MarkdownRewrite {impl AsyncTool<Arc<ToolScribe>> for MarkdownRewrite {type Output = AIDiffResponse;- #[allow(deprecated)]#[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]async fn call(&self,@@ -40,29 +39,22 @@ impl AsyncTool<Arc<ToolScribe>> for MarkdownRewrite {) -> ToolResult<Self::Output> {tracing::info!(markdown_file_id=?self.markdown_file_id, "Rewrite params");- rewrite_markdown(- self.clone(),- &scribe,- (*request_context.user_id).as_ref(),- (*request_context.jwt).clone(),- )- .await- .map_err(|err| ToolCallError {- description: "An internal error occured rewriting generating rewrite".into(),- internal_error: err,- })+ rewrite_markdown(self.clone(), &scribe)+ .await+ .map_err(|err| ToolCallError {+ description: "An internal error occured rewriting generating rewrite".into(),+ internal_error: err,+ })}}pub async fn rewrite_markdown(request: MarkdownRewrite,scribe: &ToolScribe,- _user_id: &str,- jwt: String,) -> Result<AIDiffResponse, Error> {let document = scribe.document- .fetch_with_auth(request.markdown_file_id.clone(), jwt)+ .fetch(request.markdown_file_id.clone()).document_content().await?;if document.file_type() != FileType::Md {diff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rsindex a67cf82785..19c98bcf8b 100644--- a/rust/cloud-storage/ai_toolset/src/context.rs+++ b/rust/cloud-storage/ai_toolset/src/context.rs@@ -1,6 +1,5 @@use macro_user_id::user_id::MacroUserIdStr;use std::ops::{Deref, DerefMut};-use std::sync::Arc;/// Service context wrapper for shared state passed to tools.///@@ -28,7 +27,4 @@ impl<S> DerefMut for ServiceContext<S> {pub struct RequestContext {/// The ID of the user making the request.pub user_id: MacroUserIdStr<'static>,- /// The JWT token for the request.- #[deprecated(note = "Do not add new dependencies on this field")]- pub jwt: Arc<String>,}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/mod.rsindex d3ee1cff7c..41372d59fa 100644--- a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs+++ b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs@@ -31,6 +31,7 @@ fn to_chat_err(e: anyhow::Error) -> ChatErr {}/// Postgres adapter for chat repository operations.+#[derive(Clone)]pub struct PgChatRepo {pool: PgPool,}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rsindex d0663adf2b..ce30190935 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs@@ -30,8 +30,6 @@ use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractuse model::user::axum_extractor::MacroUserExtractor;use serde::{Deserialize, Serialize};use serde_json::Value;-use std::sync::Arc;-#[derive(Debug, Serialize, Deserialize)]#[serde(tag = "action", rename_all = "lowercase")]pub enum ToolPostRequest {@@ -165,10 +163,8 @@ pub async fn handler(properties_tool_context: state.properties_tool_context.clone(),};- #[expect(deprecated)]let request_context = RequestContext {user_id: user.macro_user_id,- jwt: Arc::new(String::new()),};let tool_result = toolsetdiff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 466f3bdf06..1ccdbea73f 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@@ -177,8 +177,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar.with_macro_db(pool.clone()).build(),)- .with_channel_client_and_db(comms_service_client.clone(), pool.clone())- .with_dcs_client(document_cognition_service_client)+ .with_channel_client(pool.clone())+ .with_dcs_client(pool.clone()).with_email_client(email_service_client).with_static_file_client(static_file_service_client.clone());diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex 4a0e910ef9..ae50af9134 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -246,6 +246,7 @@ pub async fn send_chat_message(toolset.prompt,&jwt_token,user_memory.as_deref(),+ (*user_id).clone(),).await.map_err(|err| {@@ -366,10 +367,8 @@ fn stream_and_save_message(properties_tool_context: ctx.properties_tool_context.clone(),};- #[expect(deprecated)]let request_context = RequestContext {user_id: user_id.clone(),- jwt: Arc::new(jwt_token),};let ctx_outer = ctx.clone();diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rsindex 9fd4a9243e..3301e0e73e 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs@@ -7,6 +7,7 @@ use crate::model::chats::ChatResponse;use ai::types::{ChatCompletionRequest, MessageBuilder, RequestBuilder};use anyhow::{Context, Result};+use macro_user_id::user_id::MacroUserIdStr;use std::sync::Arc;// fetch documents then build request@@ -18,11 +19,13 @@ pub async fn build_chat_completion_request(static_system_prompt: &str,jwt: &str,user_memory: Option<&str>,+ user_id: MacroUserIdStr<'static>,) -> Result<ChatCompletionRequest> {let attachments = fetch::fetchium(ctx.scribe.clone(),incoming_message.attachments.clone().unwrap_or_default(),jwt,+ user_id,).await.context("failed to fetch attachment content")?;diff --git a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rsindex 8921d5f126..b1b6661e7f 100644--- a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs+++ b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs@@ -15,7 +15,6 @@ use dashmap::DashMap;use document_cognition_service::mcp_oauth::{mcp_router, state::OAuthState, tool_service::AuthenticatedToolService,};-use document_cognition_service_client::DocumentCognitionServiceClient;use document_storage_service_client::DocumentStorageServiceClient;use documents::{domain::{models::CloudFrontConfig, service::DocumentServiceImpl},@@ -121,8 +120,6 @@ async fn main() -> anyhow::Result<()> {let document_storage_client =DocumentStorageServiceClient::new(internal_auth_key.as_ref().to_string(), dss_url.clone());- let comms_service_client = comms_service_client::CommsServiceClient::new(dss_url.clone());-let sync_service_auth_key = if is_local() {env_vars.sync_service_auth_key.as_ref().to_owned()} else {@@ -146,14 +143,6 @@ async fn main() -> anyhow::Result<()> {env_vars.email_service_url.as_ref().to_owned(),));- // DCS URL for scribe loopback — just use localhost on port 8080- let dcs_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")- .unwrap_or_else(|_| "http://127.0.0.1:8080".to_string());- let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(- internal_auth_key.as_ref().to_string(),- dcs_url,- ));-let static_file_service_client =Arc::new(static_file_service_client::StaticFileServiceClient::new(internal_auth_key.as_ref().to_string(),@@ -264,8 +253,8 @@ async fn main() -> anyhow::Result<()> {.with_macro_db(db.clone()).build(),)- .with_channel_client_and_db(comms_service_client, db.clone())- .with_dcs_client(document_cognition_service_client)+ .with_channel_client(db.clone())+ .with_dcs_client(db.clone()).with_email_client(email_service_client).with_static_file_client(static_file_service_client),),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 9d98e2b08d..0080b51d08 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -7,7 +7,6 @@ use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms::outbound::postgres::user_repo::PgUserRepo;use comms_service_client::CommsServiceClient;use config::{Config, EnvVars, Environment};-use document_cognition_service_client::DocumentCognitionServiceClient;use document_storage_service_client::DocumentStorageServiceClient;use documents::{domain::{models::CloudFrontConfig, service::DocumentServiceImpl},@@ -136,11 +135,6 @@ async fn main() -> anyhow::Result<()> {config.email_service_url.clone(),));- let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(- internal_auth_key.as_ref().to_string(),- config.document_cognition_service_url.clone(),- ));-let static_file_service_client = Arc::new(StaticFileServiceClient::new(internal_auth_key.as_ref().to_string(),config.static_file_service_url.clone(),@@ -262,8 +256,8 @@ async fn main() -> anyhow::Result<()> {.with_macro_db(db.clone()).build(),)- .with_channel_client_and_db(comms_service_client.clone(), db.clone())- .with_dcs_client(document_cognition_service_client)+ .with_channel_client(db.clone())+ .with_dcs_client(db.clone()).with_email_client(email_service_client).with_static_file_client(static_file_service_client.clone()),);diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rsindex a35fef8d56..fe4cf575af 100644--- a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs@@ -90,11 +90,7 @@ wherelet user_id = MacroUserIdStr::try_from(identity.user_id.clone()).map_err(|e| rmcp::ErrorData::internal_error(format!("invalid user id: {e}"), None))?;- #[allow(deprecated)]- let request_context = RequestContext {- jwt: Arc::new(identity.jwt.clone()),- user_id,- };+ let request_context = RequestContext { user_id };let arguments = request.argumentsdiff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rsindex a0031b5e15..addae2269f 100644--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs@@ -3,6 +3,7 @@ use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;use ai::types::{Attachment, ImageData};use ai_format::document::Document;use ai_tools::read::EmailMessage;+use macro_user_id::user_id::MacroUserIdStr;use model::{chat::{AttachmentType, ChatAttachmentWithName},document::FileTypeExt,@@ -16,6 +17,7 @@ pub async fn fetchium(scribe: Arc<DcsScribe>,attachments: Vec<ChatAttachmentWithName>,jwt: &str,+ user_id: MacroUserIdStr<'static>,) -> Result<Vec<Attachment>, anyhow::Error> {// --- closure to fetch single attachment ---#[tracing::instrument(err, skip(scribe))]@@ -23,14 +25,15 @@ pub async fn fetchium(attachment: ChatAttachmentWithName,scribe: Arc<DcsScribe>,jwt: &str,+ user_id: MacroUserIdStr<'static>,) -> Result<Attachment, anyhow::Error> {match attachment.attachment_type {AttachmentType::Project => {// fetch id's of stuff in folderlet project_items = scribe.document- .fetch_project(attachment.attachment_id.clone(), jwt.to_owned())- .content()+ .fetch_project(attachment.attachment_id.clone())+ .content(scribe.document.db(), user_id).await?.to_string();Ok(Attachment::Text(@@ -60,7 +63,6 @@ pub async fn fetchium(.get_channel_transcript(attachment.attachment_id.as_str(),None,- None,Some(CHANNEL_TRANSCRIPT_MAX_MESSAGES),).await?;@@ -98,7 +100,6 @@ pub async fn fetchium(&attachment.attachment_id,0,EMAIL_THREAD_MESSAGE_LIMIT,- None,).await?;@@ -137,7 +138,7 @@ pub async fn fetchium(let futures = attachments.into_iter()- .map(|attachment| fetchington(attachment, scribe.clone(), jwt));+ .map(|attachment| fetchington(attachment, scribe.clone(), jwt, user_id.clone()));let results = futures::future::try_join_all(futures).await.inspect_err(|err| tracing::error!(error=?err, "failed to fetch one or more attachments"),diff --git a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rsindex 5f7a668422..da078dad70 100644--- a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs@@ -59,7 +59,7 @@ pub async fn get_chat(AttachmentType::Channel => ctx.scribe.channel- .get_channel_metadata(attachment.attachment_id.as_str(), None)+ .get_channel_metadata(attachment.attachment_id.as_str()).await.map(|channel_metadata| AttachmentMetadata::Channel {channel_name: channel_metadata.name,@@ -70,7 +70,7 @@ pub async fn get_chat(let thread = ctx.scribe- .get_email_messages_by_thread_id(&attachment.attachment_id, 0, 1, None)+ .get_email_messages_by_thread_id(&attachment.attachment_id, 0, 1).await;threaddiff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rsindex 30367ecaeb..ffec378d01 100644--- a/rust/cloud-storage/documents/examples/documents_toolset.rs+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs@@ -34,7 +34,6 @@ use entity_access::outbound::PgAccessRepository;use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;use sqlx::PgPool;-use std::sync::Arc;use sync_service_client::SyncServiceClient;/// No-op connection service@@ -146,12 +145,7 @@ async fn main() {let toolset = document_toolset();- let context = RequestContext {- user_id,- // Remove this later- #[allow(deprecated)]- jwt: Arc::new(String::new()),- };+ let context = RequestContext { user_id };// Create the CLIlet cli = Cli::new(diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rsindex adcf599e7b..57973f1d99 100644--- a/rust/cloud-storage/email/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs@@ -97,10 +97,7 @@ async fn main() {let toolset = email_toolset();#[expect(deprecated)]- let context = RequestContext {- user_id,- jwt: Arc::new(String::new()),- };+ let context = RequestContext { user_id };let cli = Cli::new(toolset,diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex 4fc483b8b4..86ce83fb0f 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -36,8 +36,6 @@ scribe = { path = "../scribe" }search_service_client = { path = "../search_service_client" }email_service_client = { path = "../email_service_client" }document_storage_service_client = { path = "../document_storage_service_client" }-comms_service_client = { path = "../comms_service_client" }-document_cognition_service_client = { path = "../document_cognition_service_client" }static_file_service_client = { path = "../static_file_service_client" }sync_service_client = { path = "../sync_service_client" }soup = { path = "../soup", features = ["all"] }diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex 3348dd68cd..b374181ac9 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -4,7 +4,6 @@ use ai_tools::{use comms::domain::service::ChannelServiceImpl;use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms::outbound::postgres::user_repo::PgUserRepo;-use document_cognition_service_client::DocumentCognitionServiceClient;use document_storage_service_client::DocumentStorageServiceClient;use documents::domain::models::CloudFrontConfig;use documents::inbound::toolset::DocumentToolContext;@@ -44,10 +43,7 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<Tolet search_url = std::env::var("SEARCH_SERVICE_URL")?;let email_url = std::env::var("EMAIL_SERVICE_URL")?;let sync_url = std::env::var("SYNC_SERVICE_URL")?;- let dcs_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")?;let sfs_url = std::env::var("STATIC_FILE_SERVICE_URL")?;- let comms_url =- std::env::var("COMMS_SERVICE_URL").unwrap_or_else(|_| "http://localhost:8080".into());let lexical_url =std::env::var("LEXICAL_SERVICE_URL").unwrap_or_else(|_| "http://localhost:8096".into());let doc_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")?;@@ -62,7 +58,6 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<Tointernal_auth_key.clone(),dss_url,));- let comms_client = Arc::new(comms_service_client::CommsServiceClient::new(comms_url));let search_client = Arc::new(SearchServiceClient::new(internal_auth_key.clone(),search_url,@@ -72,10 +67,6 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<Tointernal_auth_key.clone(),email_url.clone(),));- let dcs_client = Arc::new(DocumentCognitionServiceClient::new(- internal_auth_key.clone(),- dcs_url,- ));let sfs_client = Arc::new(StaticFileServiceClient::new(internal_auth_key.clone(),sfs_url,@@ -94,8 +85,8 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<To.with_macro_db(pool.clone()).build(),)- .with_channel_client_and_db(comms_client, pool.clone())- .with_dcs_client(dcs_client)+ .with_channel_client(pool.clone())+ .with_dcs_client(pool.clone()).with_email_client(email_client).with_static_file_client(sfs_client),);diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rsindex 97e52b6aaf..5ab4cb42a4 100644--- a/rust/cloud-storage/memory/src/domain/service.rs+++ b/rust/cloud-storage/memory/src/domain/service.rs@@ -7,7 +7,6 @@ use ai_toolset::RequestContext;use chrono::Utc;use futures::stream::StreamExt;use serde::Deserialize;-use std::sync::Arc;static GENERATION_MODEL: Model = Model::Claude46Opus;static JUDGE_MODEL: Model = Model::Claude46Sonnet;@@ -158,8 +157,6 @@ wherelet request_context = RequestContext {user_id: user.clone(),- #[allow(deprecated)]- jwt: Arc::new("fake_jwt".into()),};{diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.tomlindex e5852c1917..d21a3d597c 100644--- a/rust/cloud-storage/scribe/Cargo.toml+++ b/rust/cloud-storage/scribe/Cargo.toml@@ -7,8 +7,8 @@ version = "0.1.0"[features]all = ["channel", "dcs", "document", "email", "static_file"]-channel = ["comms_service_client", "comms_db_client", "models_comms", "dep:sqlx"]-dcs = ["document_cognition_service_client"]+channel = ["comms_db_client", "models_comms", "dep:sqlx"]+dcs = ["dep:chat", "macro_db_client", "dep:sqlx"]default = []document = ["document_storage_service_client",@@ -16,6 +16,9 @@ document = ["sync_service_client","properties_db_client","models_properties",+ "macro_db_client",+ "macro_user_id",+ "models_permissions","dep:sqlx",# TODO# "static_file_service_client??",@@ -54,11 +57,13 @@ document_storage_service_client = { path = "../document_storage_service_client",lexical_client = { path = "../lexical_client", optional = true }sync_service_client = { path = "../sync_service_client", optional = true }+chat = { path = "../chat", optional = true, default-features = false, features = ["outbound"] }comms_db_client = { path = "../comms_db_client", optional = true }-comms_service_client = { path = "../comms_service_client", optional = true }-document_cognition_service_client = { path = "../document_cognition_service_client", optional = true }+macro_db_client = { path = "../macro_db_client", optional = true }email_service_client = { path = "../email_service_client", optional = true }+macro_user_id = { path = "../macro_user_id", optional = true }models_comms = { path = "../models_comms", optional = true }+models_permissions = { path = "../models_permissions", optional = true }models_email = { path = "../models_email", optional = true }models_properties = { path = "../models_properties", optional = true }models_sfs = { path = "../models_sfs", optional = true }diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rsindex af6516acdb..af5078f662 100644--- a/rust/cloud-storage/scribe/src/channel/client.rs+++ b/rust/cloud-storage/scribe/src/channel/client.rs@@ -1,69 +1,37 @@use ai_format::insight_context_log::InsightContextLog;use ai_format::util::Indent;use anyhow::Error;-use comms_service_client::CommsServiceClient;-use comms_service_client::channels::{ApiChannelWithLatest, ChannelMetadataResponse};use models_comms::channel::ChannelMetadata;use sqlx::{Pool, Postgres};use std::fmt::Debug;-use std::sync::Arc;use uuid::Uuid;#[derive(Clone)]pub struct ChannelClient {- inner: Arc<CommsServiceClient>,db: Pool<Postgres>,}impl ChannelClient {- /// Create a new ChannelClient with a database pool for internal (non-JWT) operations- pub fn new_with_db(client: Arc<CommsServiceClient>, db: Pool<Postgres>) -> Self {- Self { inner: client, db }- }-- /// List all channels the user has access to- #[tracing::instrument(skip(self, jwt_token), err)]- pub async fn list_channels(&self, jwt_token: &str) -> Result<Vec<ApiChannelWithLatest>, Error> {- let channels = self- .inner- .get_channels_external(jwt_token)- .await- .map_err(Error::from)?;- Ok(channels)+ /// Create a new ChannelClient with a database pool for direct DB operations+ pub fn new(db: Pool<Postgres>) -> Self {+ Self { db }}/// Get channel metadata (name and type) by channel ID- /// Uses external authenticated endpoint if jwt_token is provided, otherwise uses direct DB access- #[tracing::instrument(skip(self, jwt_token), err)]+ #[tracing::instrument(skip(self), err)]pub async fn get_channel_metadata(&self,channel_id: impl TryInto<Uuid> + Debug,- jwt_token: Option<&str>,) -> Result<ChannelMetadata, Error> {let channel_id = channel_id.try_into().map_err(|_| anyhow::anyhow!("invalid uuid"))?;- let channel = match jwt_token {- Some(token) => self- .inner- .get_channel_metadata_external(&channel_id, token)- .await- .map_err(Error::from)?,- None => {- let channel =- comms_db_client::channels::get_channel::get_channel(&self.db, &channel_id)- .await?;-- ChannelMetadataResponse {- channel_name: channel.name.unwrap_or_default(),- channel_type: channel.channel_type,- }- }- };+ let channel =+ comms_db_client::channels::get_channel::get_channel(&self.db, &channel_id).await?;Ok(ChannelMetadata {- name: channel.channel_name,+ name: channel.name.unwrap_or_default(),channel_type: match channel.channel_type {model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,model::comms::ChannelType::Organization => {@@ -79,12 +47,10 @@ impl ChannelClient {}/// Get channel transcript (message history) by channel ID- /// Uses external authenticated endpoint if jwt_token is provided, otherwise uses direct DB access- #[tracing::instrument(skip(self, jwt_token), err)]+ #[tracing::instrument(skip(self), err)]pub async fn get_channel_transcript(&self,channel_id: impl TryInto<Uuid> + Debug,- jwt_token: Option<&str>,since: Option<chrono::DateTime<chrono::Utc>>,limit: Option<i64>,) -> Result<String, Error> {@@ -92,47 +58,34 @@ impl ChannelClient {.try_into().map_err(|_| anyhow::anyhow!("invalid uuid"))?;- match jwt_token {- Some(token) => {- let response = self- .inner- .get_channel_transcript_external(&channel_id, token, since, limit)- .await- .map_err(Error::from)?;- Ok(response.transcript)- }- None => {- // Use direct DB access for internal calls- let transcript =- format_channel_transcript(&self.db, &channel_id, since, limit).await?;- Ok(transcript)- }- }+ let transcript = format_channel_transcript(&self.db, &channel_id, since, limit).await?;+ Ok(transcript)}/// Get messages with context around a specific message/// Returns formatted conversation with messages before and after the target message- #[tracing::instrument(skip(self, jwt_token), err)]+ #[tracing::instrument(skip(self), err)]pub async fn get_message_with_context(&self,message_id: impl TryInto<Uuid> + Debug,before: i64,after: i64,- jwt_token: &str,) -> Result<String, Error> {let message_id = message_id.try_into().map_err(|_| anyhow::anyhow!("invalid uuid"))?;- let response = self- .inner- .get_message_with_context(&message_id, before, after, jwt_token)- .await- .map_err(Error::from)?;+ let db_messages =+ comms_db_client::messages::read_message_with_context::get_messages_with_context(+ &self.db,+ &message_id,+ before,+ after,+ )+ .await?;// Format messages using InsightContextLog- let formatted_messages = response- .messages+ let formatted_messages = db_messages.iter().map(|msg| {InsightContextLog {diff --git a/rust/cloud-storage/scribe/src/channel/mod.rs b/rust/cloud-storage/scribe/src/channel/mod.rsindex 796bfa35af..4b7eb74623 100644--- a/rust/cloud-storage/scribe/src/channel/mod.rs+++ b/rust/cloud-storage/scribe/src/channel/mod.rs@@ -1,19 +1,16 @@mod client;pub use client::ChannelClient;-use comms_service_client::CommsServiceClient;use sqlx::{Pool, Postgres};use crate::client::ScribeClient;-use std::sync::Arc;impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {- /// Configure the channel client with both HTTP client and database pool for internal operations- pub fn with_channel_client_and_db<T: Into<Arc<CommsServiceClient>>>(+ /// Configure the channel client with a database pool for direct DB operations+ pub fn with_channel_client(self,- channel_client: T,db: Pool<Postgres>,) -> ScribeClient<D, ChannelClient, A, E, S> {- let client = ChannelClient::new_with_db(channel_client.into(), db);+ let client = ChannelClient::new(db);ScribeClient {document: self.document,channel: client,diff --git a/rust/cloud-storage/scribe/src/dcs/client.rs b/rust/cloud-storage/scribe/src/dcs/client.rsindex c3da7b3188..d50a2b67d9 100644--- a/rust/cloud-storage/scribe/src/dcs/client.rs+++ b/rust/cloud-storage/scribe/src/dcs/client.rs@@ -1,37 +1,67 @@-use anyhow::{Error, Result};-use document_cognition_service_client::DocumentCognitionServiceClient;+use anyhow::Result;+use chat::domain::ports::ChatRepo;+use chat::outbound::postgres::PgChatRepo;pub use model::chat::ChatHistory;-use std::sync::Arc;+use model::chat::{ConversationRecord, MessageWithAttachments};+use sqlx::{Pool, Postgres};#[derive(Clone)]pub struct DcsClient {- inner: Arc<DocumentCognitionServiceClient>,+ chat_repo: PgChatRepo,+ db: Pool<Postgres>,}impl DcsClient {- pub fn new(inner: Arc<DocumentCognitionServiceClient>) -> Self {- Self { inner }+ pub fn new(db: Pool<Postgres>) -> Self {+ let chat_repo = PgChatRepo::new(db.clone());+ Self { chat_repo, db }}}impl DcsClient {- #[tracing::instrument(skip(self, jwt_token), err)]- pub async fn get_chat_history(&self, chat_id: &str, jwt_token: &str) -> Result<ChatHistory> {- self.inner- .get_chat_history_external(chat_id, jwt_token)+ #[tracing::instrument(skip(self), err)]+ pub async fn get_chat_history(&self, chat_id: &str) -> Result<ChatHistory> {+ let chat = self+ .chat_repo+ .get_chat(chat_id).await- .map_err(Error::from)+ .map_err(|e| anyhow::anyhow!("failed to get chat: {e}"))?;++ let messages = chat+ .messages+ .into_iter()+ .map(|m| {+ let content = match m.content {+ ai::types::ChatMessageContent::Text(s) => s,+ other => serde_json::to_string(&other).unwrap_or_default(),+ };+ MessageWithAttachments {+ content,+ date: chrono::Utc::now(),+ attachment_ids: m+ .attachments+ .iter()+ .map(|a| a.attachment_id.clone())+ .collect(),+ }+ })+ .collect();++ Ok(ChatHistory {+ conversation: vec![ConversationRecord {+ chat_id: chat.id,+ title: chat.name,+ messages,+ }],+ })}- #[tracing::instrument(skip(self, jwt_token), err)]+ /// Get chat history for specific message IDs (may span multiple chats).+ #[tracing::instrument(skip(self), err)]pub async fn get_chat_history_for_messages(&self,message_ids: &[String],- jwt_token: &str,) -> Result<ChatHistory> {- self.inner- .get_chat_history_for_messages_external(message_ids, jwt_token)- .await- .map_err(Error::from)+ macro_db_client::chat_history::get_chat_history_for_messages(&self.db, message_ids).await}}diff --git a/rust/cloud-storage/scribe/src/dcs/mod.rs b/rust/cloud-storage/scribe/src/dcs/mod.rsindex 61daff6a61..0d4afb89c9 100644--- a/rust/cloud-storage/scribe/src/dcs/mod.rs+++ b/rust/cloud-storage/scribe/src/dcs/mod.rs@@ -1,16 +1,12 @@mod client;pub use client::DcsClient;-use document_cognition_service_client::DocumentCognitionServiceClient;-use std::sync::Arc;+use sqlx::{Pool, Postgres};use crate::client::ScribeClient;impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {- pub fn with_dcs_client<T: Into<Arc<DocumentCognitionServiceClient>>>(- self,- chat_client: T,- ) -> ScribeClient<D, C, DcsClient, E, S> {- let dcs_client = DcsClient::new(chat_client.into());+ pub fn with_dcs_client(self, db: Pool<Postgres>) -> ScribeClient<D, C, DcsClient, E, S> {+ let dcs_client = DcsClient::new(db);ScribeClient {channel: self.channel,chat: dcs_client,diff --git a/rust/cloud-storage/scribe/src/document/client.rs b/rust/cloud-storage/scribe/src/document/client.rsindex 0463a28e8c..94fbaffd6d 100644--- a/rust/cloud-storage/scribe/src/document/client.rs+++ b/rust/cloud-storage/scribe/src/document/client.rs@@ -61,8 +61,13 @@ impl DocumentClient {.with_jwt_token(jwt_token)}- pub fn fetch_project(&self, id: String, jwt: String) -> ProjectFetcher<()> {- ProjectFetcher::new(self.dss_client.clone(), id, jwt)+ pub fn fetch_project(&self, id: String) -> ProjectFetcher<()> {+ ProjectFetcher::new(id)+ }++ /// Get the database pool for direct DB access+ pub fn db(&self) -> &Pool<Postgres> {+ &self.macro_db}}diff --git a/rust/cloud-storage/scribe/src/document/project.rs b/rust/cloud-storage/scribe/src/document/project.rsindex 68873d31d2..8d35e6fb1b 100644--- a/rust/cloud-storage/scribe/src/document/project.rs+++ b/rust/cloud-storage/scribe/src/document/project.rs@@ -1,11 +1,11 @@use anyhow::Result;-use document_storage_service_client::DocumentStorageServiceClient;+use macro_user_id::user_id::MacroUserIdStr;use model::item::{Item, ItemWithUserAccessLevel};-use model::project::response::GetProjectContentResponse;-use std::sync::Arc;+use models_permissions::share_permission::access_level::AccessLevel;+use sqlx::{Pool, Postgres};#[derive(Debug, Clone)]-pub struct ScribeProjectPreview(pub GetProjectContentResponse);+pub struct ScribeProjectPreview(pub Vec<ItemWithUserAccessLevel>);pub fn format_item_with_access(item: &ItemWithUserAccessLevel,@@ -39,7 +39,7 @@ pub fn format_item_with_access(impl std::fmt::Display for ScribeProjectPreview {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- for (i, item) in self.0.data.iter().enumerate() {+ for (i, item) in self.0.iter().enumerate() {writeln!(f, "{}.", i)?;format_item_with_access(item, f)?;}@@ -48,34 +48,34 @@ impl std::fmt::Display for ScribeProjectPreview {}pub struct ProjectFetcher<Content> {- inner_dss: Arc<DocumentStorageServiceClient>,pub content: Content,pub id: String,- pub jwt: String,}pub type NoData = ();impl ProjectFetcher<NoData> {- pub fn new(client: Arc<DocumentStorageServiceClient>, id: String, jwt: String) -> Self {- Self {- content: (),- id,- jwt,- inner_dss: client,- }+ pub fn new(id: String) -> Self {+ Self { content: (), id }}- pub async fn content(&mut self) -> Result<ProjectFetcher<ScribeProjectPreview>> {- self.inner_dss- .get_project(&self.id, &self.jwt)- .await- .map(|response| ProjectFetcher {- content: ScribeProjectPreview(response),- id: self.id.clone(),- inner_dss: self.inner_dss.clone(),- jwt: self.jwt.clone(),- })+ pub async fn content(+ &self,+ db: &Pool<Postgres>,+ user_id: MacroUserIdStr<'_>,+ ) -> Result<ProjectFetcher<ScribeProjectPreview>> {+ let items = macro_db_client::projects::get_project::get_project_content_v2(+ db,+ &self.id,+ user_id,+ AccessLevel::View,+ )+ .await?;++ Ok(ProjectFetcher {+ content: ScribeProjectPreview(items),+ id: self.id.clone(),+ })}}diff --git a/rust/cloud-storage/scribe/src/email/client.rs b/rust/cloud-storage/scribe/src/email/client.rsindex 1b53ca5b6a..4b53e12252 100644--- a/rust/cloud-storage/scribe/src/email/client.rs+++ b/rust/cloud-storage/scribe/src/email/client.rs@@ -2,7 +2,6 @@ use email_service_client::EmailServiceClient;use models_email::email::service::message::ParsedMessage;use anyhow::Result;-use email_service_client;use std::sync::Arc;#[derive(Clone)]@@ -18,68 +17,21 @@ impl EmailClient {impl EmailClient {/// Get a single email message by ID- #[tracing::instrument(skip(self, jwt_token), err)]- pub async fn get_email_message_by_id(- &self,- message_id: &str,- jwt_token: Option<&str>,- ) -> Result<ParsedMessage> {- match jwt_token {- Some(token) => {- self.inner- .get_message_by_id_external(message_id, token)- .await- }- None => self.inner.get_message_by_id_internal(message_id).await,- }- }-- /// Get multiple email messages by IDs in batch- #[tracing::instrument(skip(self, jwt_token), err)]- pub async fn get_email_messages_by_id_batch(- &self,- message_ids: &[String],- jwt_token: Option<&str>,- ) -> Result<Vec<ParsedMessage>> {- match jwt_token {- Some(token) => {- self.inner- .get_message_by_id_batch_external(message_ids, token)- .await- }- None => {- self.inner- .get_message_by_id_batch_internal(message_ids)- .await- }- }+ #[tracing::instrument(skip(self), err)]+ pub async fn get_email_message_by_id(&self, message_id: &str) -> Result<ParsedMessage> {+ self.inner.get_message_by_id_internal(message_id).await}/// Get messages by thread ID with pagination- #[tracing::instrument(skip(self, jwt_token), err)]+ #[tracing::instrument(skip(self), err)]pub async fn get_email_messages_by_thread_id(&self,thread_id: &str,message_offset: i64,message_limit: i64,- jwt_token: Option<&str>,) -> Result<Vec<ParsedMessage>> {- match jwt_token {- Some(token) => {- self.inner- .get_messages_by_thread_id_external(- thread_id,- message_offset,- message_limit,- token,- )- .await- }- None => {- self.inner- .get_messages_by_thread_id_internal(thread_id, message_offset, message_limit)- .await- }- }+ self.inner+ .get_messages_by_thread_id_internal(thread_id, message_offset, message_limit)+ .await}}diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rsindex 92b8873d1c..72f535e416 100644--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs@@ -27,8 +27,6 @@ use soup::domain::service::SoupImpl;use soup::inbound::toolset::{SoupToolContext, soup_toolset};use soup::outbound::pg_soup_repo::PgSoupRepo;use sqlx::PgPool;-use std::sync::Arc;-#[tokio::main]async fn main() {// Get database URL from environment@@ -75,10 +73,7 @@ async fn main() {// Create the soup toolsetlet toolset = soup_toolset();- let context = RequestContext {- user_id,- jwt: Arc::new(String::new()),- };+ let context = RequestContext { user_id };// Create the CLIlet cli = Cli::new(