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
//! CreateDocument tool for reading document content.
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use std::str::FromStr;
use crate::domain::create::{NewDocumentMetadata, NewPlainTextDocument};
use crate::domain::models::DocumentError;
use crate::domain::ports::DocumentService;
use crate::domain::ports::create::DocumentCreationService;
use crate::domain::ports::editing::EditingWorkerService;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use anyhow::Context;
use async_trait::async_trait;
use entity_access::domain::models::{EditAccessLevel, EntityType};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::FileType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::DocumentToolContext;
#[cfg(test)]
mod test;
fn failed_to_create_document(error: DocumentError) -> ToolCallError {
let description = match &error {
DocumentError::BadRequest(message) => message.clone(),
DocumentError::NameTooLong { max } => {
format!("name too long (max {max} characters)")
}
_ => "failed to create document".to_string(),
};
ToolCallError {
description,
internal_error: error.into(),
}
}
/// The read content response
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateDocumentResponse {
/// The id of the document
pub document_id: uuid::Uuid,
}
#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CreateDocument",
description = "Create a plaintext document or a native Macro spreadsheet or canvas. For a workbook use fileExtension spreadsheet, empty fileContent, and isTask false; then ReadSpreadsheet and EditSpreadsheet to populate cells, formulas and sheets. For a Canvas use fileExtension canvas, empty fileContent, and isTask false; then ReadCanvas and EditCanvas. Native documents are initialized before returning and work without an open editor. Markdown (md) content uses the same Markdown, citation and mention syntax as chat replies; other file types take raw content with no Markdown or mention tags. Images come from GenerateImage, Word documents from DuplicateItem and EditWordDocument, and decks from EditPresentation, not from this tool."
)]
pub struct CreateDocument {
#[schemars(description = "The name of the document without the file extension")]
pub document_name: String,
#[schemars(
description = "The string content of a text document. Must be empty for a native spreadsheet or canvas."
)]
pub file_content: String,
#[schemars(
description = "The extension of a plaintext file, or spreadsheet or canvas for a native collaborative document."
)]
pub file_extension: String,
#[schemars(description = "Whether this document is a task. Only applies to md documents.")]
#[serde(default)]
pub is_task: bool,
#[schemars(
description = "The id of the project (shown as a folder in the app UI) to create the document in. Requires edit access to the project. Omit to create the document at the top level of the user's files."
)]
#[serde(default)]
pub project_id: Option<uuid::Uuid>,
}
impl ToolAnnotated for CreateDocument {
const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create document");
}
#[async_trait]
impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CreateDocument
where
DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
EDSvc: EditingWorkerService,
{
type Output = CreateDocumentResponse;
async fn call(
&self,
service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
// The name and content are the user's; log only their shape.
tracing::info!(
file_extension = %self.file_extension,
is_task = self.is_task,
in_project = self.project_id.is_some(),
content_bytes = self.file_content.len(),
"Create content"
);
let parsed_file_type =
FileType::from_str(&self.file_extension).map_err(|e| ToolCallError {
description: format!("invalid file extension {}", self.file_extension),
internal_error: e.into(),
})?;
if parsed_file_type == FileType::Canvas
&& (!self.file_content.trim().is_empty() || self.is_task)
{
return Err(failed_to_create_document(DocumentError::BadRequest(
"Create canvases with empty fileContent and isTask false, then use ReadCanvas and EditCanvas to populate the scene".to_string(),
)));
}
let user_id: MacroUserIdStr<'static> = request_context.user_id.clone();
// Mirrors the axum create route's project body extractor: creating
// inside a project requires edit access to that project.
if let Some(project_id) = self.project_id {
service_context
.entity_access_service
.generate_entity_access_receipt::<EditAccessLevel>(
&user_id,
None,
&project_id.to_string(),
EntityType::Project,
)
.await
.map_err(|e| ToolCallError {
description: "you need edit access to the target project, or it does not exist"
.to_string(),
internal_error: e.into(),
})?;
}
// gets the members team if exists so we can track the task number correctly
let maybe_team = if self.is_task {
service_context
.entity_access_service
.get_user_team(&user_id)
.await
.map(|t| t.map(|tt| tt.team_id))
.map_err(|e| ToolCallError {
description: "failed to get users team".to_string(),
internal_error: e.into(),
})?
} else {
None
};
let principal = service_context.creation_principal(user_id);
let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone());
if let Some(project_id) = self.project_id {
metadata_builder = metadata_builder.project_id(project_id);
}
let response = if parsed_file_type == FileType::Spreadsheet {
if !self.file_content.is_empty() || self.is_task {
return Err(failed_to_create_document(DocumentError::BadRequest(
"Create spreadsheets with empty fileContent and isTask false, then use ReadSpreadsheet and EditSpreadsheet to populate the workbook".to_string(),
)));
}
service_context.creator.create_spreadsheet(&principal, metadata_builder.build()).await
} else {
let document = NewPlainTextDocument::builder(metadata_builder.build())
.file_type(parsed_file_type)
.text(self.file_content.clone())
.task_flag(self.is_task, maybe_team)
.build()
.map_err(failed_to_create_document)?;
service_context.creator.create_plain_text(&principal, document).await
}
.map(|document| document.into_response())
.map_err(failed_to_create_document)?;
tracing::trace!("created document");
let document_id_str = response
.document_response
.document_metadata
.metadata
.document_id
.to_string();
let document_id = document_id_str
.parse()
.context("expected valid uuid")
.map_err(|e| ToolCallError {
internal_error: e,
description: format!("invalid document id was output {}", document_id_str),
})?;
tracing::info!("got to end");
Ok(CreateDocumentResponse { document_id })
}
}