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
Integrate properties for tasks (#859)
Eric Hayes9d96662a646e
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex d28fd9ea61..7eb5be1dce 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -26,7 +26,7 @@ export const Read = z.object({ "contentType": z.enum(["document","channel","chanexport const ReadResponse = z.object({ "content": z.any().superRefine((x, ctx) => {- const schemas = [z.object({ "documents": z.array(z.object({ "content": z.string(), "documentId": z.string(), "metadata": z.object({ "deleted": z.boolean(), "documentName": z.string(), "fileType": z.union([z.string(), z.null()]).optional(), "owner": z.string(), "projectId": z.union([z.string(), z.null()]).optional() }) })), "type": z.literal("documents") }), z.object({ "channel_id": z.string(), "channel_name": z.union([z.string(), z.null()]).optional(), "transcript": z.string(), "type": z.literal("channel") }), z.object({ "conversation": z.array(z.object({ "chat_id": z.string(), "messages": z.array(z.object({ "attachment_summaries": z.array(z.any().superRefine((x, ctx) => {+ const schemas = [z.object({ "documents": z.array(z.object({ "formattedDocument": z.string() })), "type": z.literal("documents") }), z.object({ "channel_id": z.string(), "channel_name": z.union([z.string(), z.null()]).optional(), "transcript": z.string(), "type": z.literal("channel") }), z.object({ "conversation": z.array(z.object({ "chat_id": z.string(), "messages": z.array(z.object({ "attachment_summaries": z.array(z.any().superRefine((x, ctx) => {const schemas = [z.object({ "Summary": z.object({ "created_at": z.union([z.string().datetime({ offset: true }), z.null()]).optional(), "document_id": z.string(), "id": z.union([z.string(), z.null()]).optional(), "summary": z.string(), "version_id": z.string() }) }).strict(), z.object({ "NoSummary": z.object({ "document_id": z.string() }) }).strict()];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 29fcddaf8c..53844c7887 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -303,15 +303,7 @@ export interface ReadResponse {content:| {documents: {- content: string;- documentId: string;- metadata: {- deleted: boolean;- documentName: string;- fileType?: string | null;- owner: string;- projectId?: string | null;- };+ formattedDocument: string;}[];type: 'documents';}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 3f082c6d36..fb35c0b2c6 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -45,6 +45,7 @@ dependencies = [name = "ai"version = "0.1.0"dependencies = [+ "ai_format","anthropic","anyhow","async-openai",@@ -76,8 +77,8 @@ dependencies = [name = "ai_format"version = "0.1.0"dependencies = [- "ai","chrono",+ "models_properties",][[package]]@@ -7617,11 +7618,14 @@ dependencies = ["models_comms","models_dcs","models_email",+ "models_properties","models_sfs",+ "properties_db_client","reqwest","s3_client","serde","serde_json",+ "sqlx","static_file_service_client","sync_service_client","thiserror 2.0.17",diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.tomlindex a66d9128e8..e590874b58 100644--- a/rust/cloud-storage/ai/Cargo.toml+++ b/rust/cloud-storage/ai/Cargo.toml@@ -33,3 +33,4 @@ base64 = { workspace = true }image = "0.25.9"webp = "0.3.1"model_file_type = { path = "../model_file_type"}+ai_format = {path = "../ai_format"}diff --git a/rust/cloud-storage/ai/src/traits.rs b/rust/cloud-storage/ai/src/traits.rsindex 38d25f9637..258a1b4ac4 100644--- a/rust/cloud-storage/ai/src/traits.rs+++ b/rust/cloud-storage/ai/src/traits.rs@@ -1,10 +1,8 @@+pub use ai_format::traits::TextAttachment;+use serde::Deserialize;pub trait Metadata: for<'de> Deserialize<'de> {fn name() -> String;fn description() -> Option<String>;}--pub trait TextAttachment: std::fmt::Display + std::fmt::Debug + Send + Sync {}--impl TextAttachment for Box<dyn TextAttachment> {}diff --git a/rust/cloud-storage/ai_format/Cargo.toml b/rust/cloud-storage/ai_format/Cargo.tomlindex 1d41b9f1a5..7676ca2081 100644--- a/rust/cloud-storage/ai_format/Cargo.toml+++ b/rust/cloud-storage/ai_format/Cargo.toml@@ -6,4 +6,4 @@ version = "0.1.0"[dependencies]chrono = { workspace = true }-ai = { path = "../ai" }+models_properties = { path = "../models_properties"}diff --git a/rust/cloud-storage/ai_format/src/document.rs b/rust/cloud-storage/ai_format/src/document.rsindex 0200d9abed..9cc0c058e8 100644--- a/rust/cloud-storage/ai_format/src/document.rs+++ b/rust/cloud-storage/ai_format/src/document.rs@@ -1,10 +1,13 @@-use ai::traits::TextAttachment;+use super::util::Indent;+use crate::properties::Properties;+use crate::traits::TextAttachment;pub struct Document {pub content: String,pub file_type: String,pub id: String,pub name: String,+ pub properties: Option<Properties>,}impl std::fmt::Debug for Document {@@ -17,21 +20,29 @@ impl std::fmt::Debug for Document {.field("file_type", &self.file_type).field("id", &self.id).field("name", &self.name)+ .field("properties", &self.properties).finish()}}impl std::fmt::Display for Document {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(+ writeln!(f,- r#"<document id="{}" file_type="{}" name="{}">- <content>- {}- </content>-</document>"#,- self.id, self.file_type, self.name, self.content- )+ r#"<document id="{}" file_type="{}" name="{}">"#,+ self.id, self.file_type, self.name+ )?;++ // Include properties before content if present+ if let Some(props) = &self.properties+ && !props.is_empty()+ {+ writeln!(f, "{}", Indent(4, props))?;+ }+ writeln!(f, "{}", Indent(4, "<content>"))?;+ writeln!(f, "{}", Indent(8, &self.content))?;+ writeln!(f, "{}", Indent(4, "</content>"))?;+ write!(f, "</document>")}}diff --git a/rust/cloud-storage/ai_format/src/lib.rs b/rust/cloud-storage/ai_format/src/lib.rsindex 556cfce998..2b8d73d3d5 100644--- a/rust/cloud-storage/ai_format/src/lib.rs+++ b/rust/cloud-storage/ai_format/src/lib.rs@@ -1,3 +1,5 @@pub mod document;pub mod insight_context_log;+pub mod properties;+pub mod traits;pub mod util;diff --git a/rust/cloud-storage/ai_format/src/properties.rs b/rust/cloud-storage/ai_format/src/properties.rsnew file mode 100644index 0000000000..e17bfaa877--- /dev/null+++ b/rust/cloud-storage/ai_format/src/properties.rs@@ -0,0 +1,141 @@+//! AI formatting for entity properties.+//!+//! Provides XML-like formatting for key-value properties to be included+//! in AI document context.++use crate::util::{Date, Indent};++use models_properties::EntityType;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_value::PropertyValue;+use std::fmt;++/// A single property key-value pair.+#[derive(Debug, Clone)]+pub struct Property {+ pub(crate) key: String,+ pub(crate) value: String,+}++impl Property {+ pub fn from_property(property: EntityPropertyWithDefinition) -> Self {+ property+ .value+ .as_ref()+ .and_then(|v| format_property_value(v, &property.options))+ .map(|s| Self {+ key: property.definition.display_name.clone(),+ value: s,+ })+ .unwrap_or_else(|| Self {+ key: property.definition.display_name,+ value: "null".into(),+ })+ }+}++impl fmt::Display for Property {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ f,+ "<property key=\"{}\">{}</property>",+ self.key, self.value+ )+ }+}++/// A collection of properties for an entity.+#[derive(Debug, Clone, Default)]+pub struct Properties {+ pub(crate) kind: String,+ pub(crate) items: Vec<Property>,+}++impl Properties {+ pub fn from_properties(+ kind: EntityType,+ properties: Vec<EntityPropertyWithDefinition>,+ ) -> Self {+ Self {+ kind: kind.to_string(),+ items: properties+ .into_iter()+ .map(Property::from_property)+ .collect(),+ }+ }++ pub fn is_empty(&self) -> bool {+ self.items.is_empty()+ }+}++impl fmt::Display for Properties {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ if self.items.is_empty() {+ return Ok(());+ }++ writeln!(f, "<properties entity_kind=\"{}\">", self.kind)?;+ for prop in &self.items {+ writeln!(f, "{}", Indent(4, prop))?;+ }+ write!(f, "</properties>")+ }+}++/// Format a property value as a human-readable string.+fn format_property_value(+ value: &PropertyValue,+ options: &Option<Vec<models_properties::service::property_option::PropertyOption>>,+) -> Option<String> {+ match value {+ PropertyValue::Bool(b) => Some(if *b { "Yes" } else { "No" }.to_string()),+ PropertyValue::Num(n) => Some(n.to_string()),+ PropertyValue::Str(s) => Some(s.clone()),+ PropertyValue::Date(d) => Some(Date(d.to_owned()).to_string()),+ PropertyValue::SelectOption(ids) => {+ // Look up option display values+ let opts = options.as_ref()?;+ let values: Vec<String> = ids+ .iter()+ .filter_map(|id| {+ opts.iter().find(|o| &o.id == id).map(|o| {+ match &o.value {+ models_properties::service::property_option::PropertyOptionValue::String(+ s,+ ) => s.clone(),+ models_properties::service::property_option::PropertyOptionValue::Number(+ n,+ ) => n.to_string(),+ }+ })+ })+ .collect();++ if values.is_empty() {+ None+ } else {+ Some(values.join(", "))+ }+ }+ PropertyValue::EntityRef(refs) => {+ if refs.is_empty() {+ None+ } else {+ let ids: Vec<String> = refs+ .iter()+ .map(|r| format!("{}:{}", r.entity_type, r.entity_id))+ .collect();+ Some(ids.join(", "))+ }+ }+ PropertyValue::Link(urls) => {+ if urls.is_empty() {+ None+ } else {+ Some(urls.join(", "))+ }+ }+ }+}diff --git a/rust/cloud-storage/ai_format/src/traits.rs b/rust/cloud-storage/ai_format/src/traits.rsnew file mode 100644index 0000000000..a932c00868--- /dev/null+++ b/rust/cloud-storage/ai_format/src/traits.rs@@ -0,0 +1,3 @@+pub trait TextAttachment: std::fmt::Display + std::fmt::Debug + Send + Sync {}++impl TextAttachment for Box<dyn TextAttachment> {}diff --git a/rust/cloud-storage/ai_format/src/util.rs b/rust/cloud-storage/ai_format/src/util.rsindex 18b37a62d9..2809e5bc57 100644--- a/rust/cloud-storage/ai_format/src/util.rs+++ b/rust/cloud-storage/ai_format/src/util.rs@@ -1,10 +1,6 @@use chrono::{DateTime, Utc};use std::fmt::Display;-pub fn format_date(date: DateTime<Utc>) -> String {- date.format("%Y-%m-%d").to_string()-}-pub fn truncate<T: Display>(v: T, limit: usize) -> String {let content = v.to_string();content@@ -14,21 +10,28 @@ pub fn truncate<T: Display>(v: T, limit: usize) -> String {.unwrap_or(content)}-pub struct Indent<T: Sized>(pub T, pub usize);-pub struct Truncate<T: Sized>(pub T, pub usize);+pub struct Date(pub DateTime<Utc>);+pub struct Indent<T: Sized>(pub usize, pub T);+pub struct Truncate<T: Sized>(pub usize, pub T);++impl Display for Date {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.0.to_rfc2822())+ }+}impl<T> Display for Indent<T>whereT: Display + Sized,{fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let text = self.0.to_string();+ let text = self.1.to_string();let mut iter = text.lines().peekable();while let Some(line) = iter.next() {if iter.peek().is_some() {- writeln!(f, "{:indent$}{}", "", line, indent = self.1)?;+ writeln!(f, "{:indent$}{}", "", line, indent = self.0)?;} else {- write!(f, "{:indent$}{}", "", line, indent = self.1)?;+ write!(f, "{:indent$}{}", "", line, indent = self.0)?;}}Ok(())@@ -40,7 +43,7 @@ whereT: Display + Sized,{fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "{}", truncate(&self.0, self.1))+ write!(f, "{}", truncate(&self.1, self.0))}}@@ -51,10 +54,10 @@ mod test {#[test]fn test_truncate() {- let truncated = Truncate("123456789", 3).to_string();+ let truncated = Truncate(3, "123456789").to_string();assert_eq!(truncated.as_str(), "123...");assert_eq!(- Truncate("hello world", 5).to_string(),+ Truncate(5, "hello world").to_string(),"hello...".to_string());}@@ -62,7 +65,7 @@ mod test {#[test]fn test_indent() {let text = "this is text";- assert_eq!(" this is text".to_string(), Indent(text, 4).to_string());+ assert_eq!(" this is text".to_string(), Indent(4, text).to_string());let text = r#"multilinetext@@ -73,7 +76,7 @@ texttexthere"#.to_string(),- Indent(text, 4).to_string()+ Indent(4, text).to_string());}@@ -95,7 +98,7 @@ content);let log = InsightContextLog {- content: Truncate("content that is too long to be useful to ai", 7),+ content: Truncate(7, "content that is too long to be useful to ai"),metadata: vec![],name: "long test".to_string(),};@@ -109,7 +112,7 @@ content...);let nested_log = InsightContextLog {- content: Indent(log, 4),+ content: Indent(4, log),metadata: vec![("swag".to_string(), "true".to_string())],name: "nested test".to_string(),};diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rsindex 8112d15464..8e4a82c1e8 100644--- a/rust/cloud-storage/ai_tools/src/read.rs+++ b/rust/cloud-storage/ai_tools/src/read.rs@@ -58,9 +58,7 @@ pub struct DocumentMetadata {#[derive(Debug, JsonSchema, Serialize)]#[serde(rename_all = "camelCase")]pub struct DocumentItem {- pub document_id: String,- pub content: String,- pub metadata: DocumentMetadata,+ pub formatted_document: String,}#[derive(Debug, JsonSchema, Serialize)]@@ -236,26 +234,13 @@ impl Read {}};- let metadata = document_with_content.metadata().clone();- let content_str = match document_with_content.content.text_content() {- Ok(content) => content,- Err(e) => {- tracing::warn!("failed to extract text content for document {}: {}", id, e);- continue;- }- };-- documents.push(DocumentItem {- document_id: id.clone(),- content: content_str,- metadata: DocumentMetadata {- document_name: metadata.document_name,- owner: metadata.owner.to_string(),- file_type: metadata.file_type,- project_id: metadata.project_id,- deleted: metadata.deleted_at.is_some(),- },- });+ if let Some(doc) = document_with_content.text_attachment() {+ documents.push(DocumentItem {+ formatted_document: doc.to_string(),+ });+ } else {+ tracing::warn!("Unexpected document type for fetch");+ }}if documents.is_empty() {diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rsindex 7d3f877d8e..af7cebb120 100644--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs@@ -87,6 +87,7 @@ pub async fn generate_patches(file_type: "md".into(),id: request.markdown_file_id,name: file_name,+ properties: None,}.boxed(),)diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rsindex 6327b61a89..0e3896027a 100644--- a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs@@ -55,7 +55,7 @@ pub async fn get_channel_transcript(let formatted_text = InsightContextLog {name: "conversation".to_string(),metadata: vec![],- content: Indent(formatted_messages, 4),+ content: Indent(4, formatted_messages),}.to_string();diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rsindex cac66e4436..c62a064640 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs@@ -99,6 +99,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar.with_dss_client(document_storage_client.clone()).with_lexical_client(lexical_client).with_sync_service_client(sync_service_client)+ .with_macro_db(pool.clone()).build(),).with_channel_client(comms_service_client.clone())diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rsindex ee4f7ed98a..bf05f5a6c1 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs@@ -102,6 +102,7 @@ async fn build_completion_request(file_type: f.as_str().to_string(),name: document.name,content: context,+ properties: None,}.boxed(),);@@ -129,6 +130,7 @@ async fn build_completion_request(file_type: file_type.as_str().to_string(),name: document.name,content,+ properties: None,}.boxed(),);diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 574d88bd65..a4c538e524 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -169,7 +169,7 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized static file service client");api::setup_and_serve(ApiContext {- db,+ db: db.clone(),email_service_client_external: Arc::new(EmailServiceClientExternal::new(email_service_client.url().to_owned(),)),@@ -180,6 +180,7 @@ async fn main() -> anyhow::Result<()> {.with_dss_client(document_storage_client.clone()).with_lexical_client(lexical_client).with_sync_service_client(sync_service_client.clone())+ .with_macro_db(db.clone()).build(),).with_channel_client(comms_service_client.clone())diff --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 898764e4d2..a0031b5e15 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@@ -39,6 +39,7 @@ pub async fn fetchium(file_type: "Project".into(),name: attachment.name().unwrap_or_default().into(),content: project_items,+ properties: None,}.boxed(),))@@ -70,6 +71,7 @@ pub async fn fetchium(file_type: "channel".into(),id: attachment.attachment_id.clone(),name: "unknown channel name".into(),+ properties: None,}.boxed(),))@@ -83,15 +85,10 @@ pub async fn fetchium(if document.file_type().is_image() {Ok(Attachment::Image(ImageData::try_from(document.content)?))} else {- Ok(Attachment::Text(- Document {- id: attachment.attachment_id,- name: document.metadata().document_name.clone(),- file_type: document.file_type().to_string(),- content: document.content.text_content()?,- }- .boxed(),- ))+ document+ .text_attachment()+ .ok_or(anyhow::anyhow!("Expected text content found image"))+ .map(Attachment::Text)}}AttachmentType::Email => {@@ -130,6 +127,7 @@ pub async fn fetchium(name: subject.clone(),file_type: "email".to_string(),content,+ properties: None,}.boxed(),))diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.tomlindex 486dfbc01d..68073ed191 100644--- a/rust/cloud-storage/scribe/Cargo.toml+++ b/rust/cloud-storage/scribe/Cargo.toml@@ -14,6 +14,9 @@ document = ["document_storage_service_client","lexical_client","sync_service_client",+ "properties_db_client",+ "models_properties",+ "dep:sqlx",# TODO# "static_file_service_client??",]@@ -32,6 +35,7 @@ futures = { workspace = true }reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }+sqlx = { workspace = true, optional = true }thiserror = { workspace = true }tokio = { workspace = true }tracing = { workspace = true }@@ -55,5 +59,7 @@ document_cognition_service_client = { path = "../document_cognition_service_clieemail_service_client = { path = "../email_service_client", optional = true }models_comms = { path = "../models_comms", optional = true }models_email = { path = "../models_email", optional = true }+models_properties = { path = "../models_properties", optional = true }models_sfs = { path = "../models_sfs", optional = true }+properties_db_client = { path = "../properties_db_client", optional = true }static_file_service_client = { path = "../static_file_service_client", optional = true }diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rsindex 4ea8dd5639..26beaef5d8 100644--- a/rust/cloud-storage/scribe/src/channel/client.rs+++ b/rust/cloud-storage/scribe/src/channel/client.rs@@ -125,7 +125,7 @@ impl ChannelClient {let formatted_text = InsightContextLog {name: "conversation".to_string(),metadata: vec![],- content: Indent(formatted_messages, 4),+ content: Indent(4, formatted_messages),}.to_string();diff --git a/rust/cloud-storage/scribe/src/document/client.rs b/rust/cloud-storage/scribe/src/document/client.rsindex de3ebbb5a0..0463a28e8c 100644--- a/rust/cloud-storage/scribe/src/document/client.rs+++ b/rust/cloud-storage/scribe/src/document/client.rs@@ -2,6 +2,7 @@ use super::fetcher::NewDocumentFetcher;use super::project::ProjectFetcher;use document_storage_service_client::DocumentStorageServiceClient;use lexical_client::LexicalClient;+use sqlx::{Pool, Postgres};use std::sync::Arc;use sync_service_client::SyncServiceClient;@@ -10,6 +11,7 @@ pub struct DocumentClient {pub dss_client: Arc<DocumentStorageServiceClient>,pub sync_service_client: Arc<SyncServiceClient>,pub lexical_client: Arc<LexicalClient>,+ pub macro_db: Arc<Pool<Postgres>>,}impl DocumentClient {@@ -21,11 +23,13 @@ impl DocumentClient {dss_client: Arc<DocumentStorageServiceClient>,sync_service_client: Arc<SyncServiceClient>,lexical_client: Arc<LexicalClient>,+ macro_db: Arc<Pool<Postgres>>,) -> Self {Self {dss_client,sync_service_client,lexical_client,+ macro_db,}}}@@ -36,6 +40,7 @@ impl DocumentClient {self.dss_client.clone(),self.sync_service_client.clone(),self.lexical_client.clone(),+ self.macro_db.clone(),document_id.into(),)}@@ -50,6 +55,7 @@ impl DocumentClient {self.dss_client.clone(),self.sync_service_client.clone(),self.lexical_client.clone(),+ self.macro_db.clone(),document_id.into(),).with_jwt_token(jwt_token)@@ -62,7 +68,7 @@ impl DocumentClient {// --- builder --- //// slight insanity but its good ong-pub type NewDocumentClientBuilder = DocumentClientBuilder<(), (), ()>;+pub type NewDocumentClientBuilder = DocumentClientBuilder<(), (), (), ()>;impl Default for NewDocumentClientBuilder {fn default() -> Self {Self::new()@@ -75,51 +81,70 @@ impl NewDocumentClientBuilder {dss_client: (),lexical_client: (),sync_service_client: (),+ macro_db: (),}}}-pub struct DocumentClientBuilder<A, B, C> {+pub struct DocumentClientBuilder<A, B, C, D> {pub dss_client: A,pub sync_service_client: B,pub lexical_client: C,+ pub macro_db: D,}-impl<A, B, C> DocumentClientBuilder<A, B, C> {+impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {pub fn with_dss_client<T: Into<Arc<DocumentStorageServiceClient>>>(self,dss_client: T,- ) -> DocumentClientBuilder<Arc<DocumentStorageServiceClient>, B, C> {+ ) -> DocumentClientBuilder<Arc<DocumentStorageServiceClient>, B, C, D> {DocumentClientBuilder {dss_client: dss_client.into(),lexical_client: self.lexical_client,sync_service_client: self.sync_service_client,+ macro_db: self.macro_db,}}}-impl<A, B, C> DocumentClientBuilder<A, B, C> {+impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {pub fn with_sync_service_client<T: Into<Arc<SyncServiceClient>>>(self,sync_service_client: T,- ) -> DocumentClientBuilder<A, Arc<SyncServiceClient>, C> {+ ) -> DocumentClientBuilder<A, Arc<SyncServiceClient>, C, D> {DocumentClientBuilder {dss_client: self.dss_client,lexical_client: self.lexical_client,sync_service_client: sync_service_client.into(),+ macro_db: self.macro_db,}}}-impl<A, B, C> DocumentClientBuilder<A, B, C> {+impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {pub fn with_lexical_client<T: Into<Arc<LexicalClient>>>(self,lexical_client: T,- ) -> DocumentClientBuilder<A, B, Arc<LexicalClient>> {+ ) -> DocumentClientBuilder<A, B, Arc<LexicalClient>, D> {DocumentClientBuilder {dss_client: self.dss_client,lexical_client: lexical_client.into(),sync_service_client: self.sync_service_client,+ macro_db: self.macro_db,+ }+ }+}++impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {+ pub fn with_macro_db<T: Into<Arc<Pool<Postgres>>>>(+ self,+ macro_db: T,+ ) -> DocumentClientBuilder<A, B, C, Arc<Pool<Postgres>>> {+ DocumentClientBuilder {+ dss_client: self.dss_client,+ lexical_client: self.lexical_client,+ sync_service_client: self.sync_service_client,+ macro_db: macro_db.into(),}}}@@ -129,6 +154,7 @@ implArc<DocumentStorageServiceClient>,Arc<SyncServiceClient>,Arc<LexicalClient>,+ Arc<Pool<Postgres>>,>{pub fn build(self) -> DocumentClient {@@ -136,6 +162,7 @@ impldss_client: self.dss_client,sync_service_client: self.sync_service_client,lexical_client: self.lexical_client,+ macro_db: self.macro_db,}}}diff --git a/rust/cloud-storage/scribe/src/document/fetcher.rs b/rust/cloud-storage/scribe/src/document/fetcher.rsindex 95e728d4b3..04aa94e830 100644--- a/rust/cloud-storage/scribe/src/document/fetcher.rs+++ b/rust/cloud-storage/scribe/src/document/fetcher.rs@@ -1,9 +1,14 @@use crate::document::types::{Data, DocumentContent};+use ai_format::document::Document;+use ai_format::properties::Properties;+use ai_format::traits::TextAttachment;use anyhow::{Context, Error};use document_storage_service_client::DocumentStorageServiceClient;use lexical_client::LexicalClient;use model::document::FileTypeExt;use model::document::{DocumentBasic, FileType, response::LocationResponseV3};+use models_properties::EntityType;+use sqlx::{Pool, Postgres};use std::fmt::Debug;use std::sync::Arc;use sync_service_client::SyncServiceClient;@@ -21,6 +26,7 @@ pub struct DocumentFetcher<Location, Content> {inner_lexical: Arc<LexicalClient>,document_id: String,jwt_token: Option<String>,+ macro_db: Arc<Pool<Postgres>>,}// A client is a wrapper around methods that may be applied to a single document@@ -30,6 +36,7 @@ impl DocumentFetcher<NoData, NoData> {dss_client: Arc<DocumentStorageServiceClient>,sync_service_client: Arc<SyncServiceClient>,lexical_client: Arc<LexicalClient>,+ macro_db: Arc<Pool<Postgres>>,document_id: String,) -> Self {Self {@@ -40,6 +47,7 @@ impl DocumentFetcher<NoData, NoData> {content: (),location: (),jwt_token: None,+ macro_db,}}@@ -75,6 +83,7 @@ impl DocumentFetcher<NoData, NoData> {inner_lexical: self.inner_lexical,inner_sync_service: self.inner_sync_service,jwt_token: self.jwt_token,+ macro_db: self.macro_db,})}@@ -101,6 +110,7 @@ impl DocumentFetcher<Fetched<LocationResponseV3>, NoData> {inner_lexical: self.inner_lexical,inner_sync_service: self.inner_sync_service,jwt_token: self.jwt_token,+ macro_db: self.macro_db,})}}@@ -115,10 +125,36 @@ impl<T> DocumentFetcher<Fetched<LocationResponseV3>, T> {}}-impl<T> DocumentFetcher<T, Fetched<DocumentContent>> {+impl DocumentFetcher<LocationResponseV3, Fetched<DocumentContent>> {pub fn file_type(&self) -> FileType {self.content.file_type}++ pub fn text_attachment(self) -> Option<Box<dyn TextAttachment>> {+ if self.content.file_type.is_image() {+ None+ } else {+ let name = self.location.metadata().document_name.clone();+ let file_type = self.file_type().to_string();+ let properties = self+ .content+ .properties+ .clone()+ .map(|p| Properties::from_properties(EntityType::Task, p));+ let text = self.content.text_content().ok()?;++ Some(+ Document {+ content: text,+ file_type,+ id: self.document_id,+ name,+ properties,+ }+ .boxed(),+ )+ }+ }}// -- internal util / fetching logic --@@ -149,6 +185,7 @@ impl<L: Debug, D: Debug> DocumentFetcher<L, D> {document_id: location.metadata().document_id.clone(),file_type,location: location.clone(),+ properties: None,})}// md content is usually in sync service but may be in s3@@ -164,6 +201,7 @@ impl<L: Debug, D: Debug> DocumentFetcher<L, D> {.await.context("HTTP (body) error when fetching from S3 [other]").map(|text| DocumentContent {+ properties: None,data: Data::Text(text),document_id: self.document_id.clone(),file_type,@@ -177,6 +215,7 @@ impl<L: Debug, D: Debug> DocumentFetcher<L, D> {.await.context("HTTP (body) error when fetching from S3 [other]").map(|bytes| DocumentContent {+ properties: None,data: Data::Binary(bytes),document_id: self.document_id.clone(),file_type,@@ -199,10 +238,19 @@ impl<L: Debug, D: Debug> DocumentFetcher<L, D> {&self,location: &LocationResponseV3,) -> Result<DocumentContent, Error> {+ let properties =+ properties_db_client::entity_properties::get::get_entity_properties_values(+ &self.macro_db,+ &self.document_id,+ models_properties::EntityType::Task,+ )+ .await?;+self.inner_lexical.parse_markdown_for_ai(&self.document_id).await.map(|content| DocumentContent {+ properties: Some(properties),data: Data::Markdown(content),document_id: self.document_id.clone(),location: location.clone(),diff --git a/rust/cloud-storage/scribe/src/document/types.rs b/rust/cloud-storage/scribe/src/document/types.rsindex db8c729dcc..b55830f74e 100644--- a/rust/cloud-storage/scribe/src/document/types.rs+++ b/rust/cloud-storage/scribe/src/document/types.rs@@ -4,6 +4,7 @@ use bytes::Bytes;use lexical_client::types::CognitionResponseData;use model::document::response::LocationResponseV3;use model::document::{DocumentBasic, FileType, FileTypeExt};+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;#[derive(Debug, Clone)]pub struct DocumentContent {@@ -11,6 +12,7 @@ pub struct DocumentContent {pub document_id: String,pub file_type: FileType,pub location: LocationResponseV3,+ pub properties: Option<Vec<EntityPropertyWithDefinition>>,}#[derive(Clone)]