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): paywall models (#2234)
Eric Hayes47ac9fd37e45
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex fd4f65b087..6c58c8a38a 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -914,6 +914,11 @@ export type sendChatMessageResponse401 = {status: 401;};+export type sendChatMessageResponse402 = {+ data: void;+ status: 402;+};+export type sendChatMessageResponse403 = {data: void;status: 403;@@ -925,6 +930,7 @@ export type sendChatMessageResponseSuccess = sendChatMessageResponse200 & {export type sendChatMessageResponseError = (| sendChatMessageResponse400| sendChatMessageResponse401+ | sendChatMessageResponse402| sendChatMessageResponse403) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex 15c3ac25e6..205cc9de93 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -786,6 +786,9 @@"401": {"description": "Unauthorized"},+ "402": {+ "description": "Payment required — user lacks access to the requested model"+ },"403": {"description": "Forbidden"}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex dc774419b9..0c42b51c0f 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1815,6 +1815,7 @@ dependencies = ["model","model_user","models_permissions",+ "roles_and_permissions","serde","serde_json","sqlx",@@ -2931,6 +2932,7 @@ dependencies = ["regex","reqwest","rmcp",+ "roles_and_permissions","schemars","scribe","search_service_client",diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.tomlindex 336481e4b7..92922e62b9 100644--- a/rust/cloud-storage/chat/Cargo.toml+++ b/rust/cloud-storage/chat/Cargo.toml@@ -6,7 +6,7 @@ version = "0.1.0"[features]default = ["inbound", "outbound", "ports"]-inbound = ["dep:axum", "dep:model_user", "entity_access/inbound", "ports"]+inbound = ["dep:axum", "dep:model_user", "dep:roles_and_permissions", "entity_access/inbound", "ports"]outbound = ["dep:macro_share_permissions","dep:macro_uuid",@@ -34,6 +34,7 @@ unicode-segmentation = { workspace = true }# Inbound (HTTP handlers)axum = { workspace = true, optional = true }model_user = { path = "../model_user", optional = true }+roles_and_permissions = { path = "../roles_and_permissions", optional = true, default-features = false }utoipa = { workspace = true }# Outbound (database adapters)diff --git a/rust/cloud-storage/chat/src/inbound/http/extractors.rs b/rust/cloud-storage/chat/src/inbound/http/extractors.rsnew file mode 100644index 0000000000..9f9d264bda--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/http/extractors.rs@@ -0,0 +1,82 @@+//! Axum extractors for chat inbound handlers.++use ai::types::Model;+use axum::extract::FromRequestParts;+use axum::http::StatusCode;+use axum::http::request::Parts;+use axum::response::IntoResponse;+use model::user::UserContext;+use roles_and_permissions::domain::model::PermissionId;++/// Axum extractor that resolves the best AI model a user has access to based+/// on their permissions.+///+/// The permission hierarchy is: Opus > Sonnet > Haiku. If the user has none+/// of these permissions the extractor rejects with `402 Payment Required`.+#[derive(Debug)]+pub struct ChatModelAccess(Model);++impl ChatModelAccess {+ /// Returns the resolved model.+ pub fn model(&self) -> Model {+ self.0+ }+}++/// Error returned when [`ChatModelAccess`] cannot be extracted.+pub enum ChatModelAccessRejection {+ /// The `UserContext` extension was missing (middleware not applied).+ MissingUserContext,+ /// The `UserContext` had no permissions attached.+ MissingPermissions,+ /// The user has no AI model permissions (free tier).+ NoModelAccess,+}++impl IntoResponse for ChatModelAccessRejection {+ fn into_response(self) -> axum::response::Response {+ match self {+ Self::MissingUserContext => {+ (StatusCode::INTERNAL_SERVER_ERROR, "missing user context").into_response()+ }+ Self::MissingPermissions => (+ StatusCode::INTERNAL_SERVER_ERROR,+ "missing user permissions",+ )+ .into_response(),+ Self::NoModelAccess => (+ StatusCode::PAYMENT_REQUIRED,+ "AI features require a paid subscription",+ )+ .into_response(),+ }+ }+}++impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {+ type Rejection = ChatModelAccessRejection;++ async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {+ let user_context = parts+ .extensions+ .get::<UserContext>()+ .ok_or(ChatModelAccessRejection::MissingUserContext)?;++ let permissions = user_context+ .permissions+ .as_ref()+ .ok_or(ChatModelAccessRejection::MissingPermissions)?;++ let model = if permissions.contains(&PermissionId::WriteOpus.to_string()) {+ Model::Claude46Opus+ } else if permissions.contains(&PermissionId::WriteSonnet.to_string()) {+ Model::Claude46Sonnet+ } else if permissions.contains(&PermissionId::WriteHaiku.to_string()) {+ Model::Claude45Haiku+ } else {+ return Err(ChatModelAccessRejection::NoModelAccess);+ };++ Ok(ChatModelAccess(model))+ }+}diff --git a/rust/cloud-storage/chat/src/inbound/http/mod.rs b/rust/cloud-storage/chat/src/inbound/http/mod.rsnew file mode 100644index 0000000000..17f47c715a--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/http/mod.rs@@ -0,0 +1,4 @@+//! HTTP-specific inbound adapters: routers, handlers, and extractors.++pub mod extractors;+pub mod router;diff --git a/rust/cloud-storage/chat/src/inbound/http/router.rs b/rust/cloud-storage/chat/src/inbound/http/router.rsnew file mode 100644index 0000000000..76bd9f6e61--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/http/router.rs@@ -0,0 +1,383 @@+//! Axum router builders and HTTP handlers for the chat API.++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{delete, get, post, put},+};+use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;+use model::response::StringIDResponse;+use model_user::axum_extractor::MacroUserExtractor;+use models_permissions::share_permission::SharePermissionV2;+use serde::Deserialize;+use utoipa::ToSchema;++use crate::domain::models::{ChatErr, CreateChatArgs, GetChatResponse, PatchChatArgs};+use crate::domain::ports::ChatService;++/// Shared state for the chat router, wrapping a [`ChatService`] implementation+/// and an [`EntityAccessService`] for authorization.+pub struct ChatRouterState<S, Svc> {+ inner: Arc<S>,+ access_service: Arc<Svc>,+}++impl<S, Svc> Clone for ChatRouterState<S, Svc> {+ fn clone(&self) -> Self {+ Self {+ inner: Arc::clone(&self.inner),+ access_service: Arc::clone(&self.access_service),+ }+ }+}++impl<S, Svc> FromRef<ChatRouterState<S, Svc>> for Arc<Svc> {+ fn from_ref(state: &ChatRouterState<S, Svc>) -> Self {+ state.access_service.clone()+ }+}++impl<S: ChatService, Svc: EntityAccessService> ChatRouterState<S, Svc> {+ /// Create a new [`ChatRouterState`] from a service and access service.+ pub fn new(service: S, access_service: Svc) -> Self {+ Self {+ inner: Arc::new(service),+ access_service: Arc::new(access_service),+ }+ }+}++/// Build the router for the `POST /` create-chat route.+///+/// This is separated so that DCS can apply different middleware+/// (e.g. `ensure_user_exists` + quota checks) without `ensure_chat_exists`.+pub fn chat_create_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(+ state: ChatRouterState<S, Svc>,+) -> Router<T> {+ Router::new()+ .route("/", post(create_chat_handler::<S, Svc>))+ .with_state(state)+}++/// Build the router for all `/{chat_id}` routes.+///+/// These routes require `ensure_chat_exists` middleware to populate+/// `ChatBasic` in extensions before the [`ChatAccessLevelExtractor`] runs.+pub fn chat_id_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(+ state: ChatRouterState<S, Svc>,+) -> Router<T> {+ Router::new()+ .route(+ "/{chat_id}",+ get(get_chat_handler::<S, Svc>)+ .delete(delete_chat_handler::<S, Svc>)+ .patch(patch_chat_handler::<S, Svc>),+ )+ .route(+ "/{chat_id}/permanent",+ delete(permanently_delete_chat_handler::<S, Svc>),+ )+ .route("/{chat_id}/copy", post(copy_chat_handler::<S, Svc>))+ .route(+ "/{chat_id}/revert_delete",+ put(revert_delete_handler::<S, Svc>),+ )+ .route(+ "/{chat_id}/permissions",+ get(get_chat_permissions_handler::<S, Svc>),+ )+ .with_state(state)+}++/// HTTP error type for chat handlers, mapped from [`ChatErr`].+#[derive(Debug)]+pub enum ChatHandlerErr {+ /// Something went wrong internally.+ Internal,+ /// The requested resource was not found.+ NotFound,+ /// The request was bad+ BadRequest(String),+}++impl From<ChatErr> for ChatHandlerErr {+ fn from(err: ChatErr) -> Self {+ match err {+ ChatErr::BadRequest(e) => ChatHandlerErr::BadRequest(e),+ ChatErr::NotFound => ChatHandlerErr::NotFound,+ ChatErr::Unknown(e) => {+ tracing::error!(error=?e, "chat handler error");+ ChatHandlerErr::Internal+ }+ }+ }+}++impl IntoResponse for ChatHandlerErr {+ fn into_response(self) -> axum::response::Response {+ let (status, msg) = match self {+ ChatHandlerErr::Internal => (+ StatusCode::INTERNAL_SERVER_ERROR,+ "Internal server error".to_string(),+ ),+ ChatHandlerErr::NotFound => (StatusCode::NOT_FOUND, "Not found".to_string()),+ ChatHandlerErr::BadRequest(e) => (StatusCode::BAD_REQUEST, e),+ };++ (status, msg).into_response()+ }+}++/// Request body for creating a chat.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateChatRequest {+ /// Optional name for the chat.+ pub name: Option<String>,+ /// Optional project to associate the chat with.+ pub project_id: Option<String>,+}++#[utoipa::path(+ post,+ path = "/chats",+ tag = "chats",+ operation_id = "create_chat",+ responses(+ (status = 200, body = StringIDResponse),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Create a new chat.+#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id))]+pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(+ State(state): State<ChatRouterState<S, Svc>>,+ user: MacroUserExtractor,+ Json(req): Json<CreateChatRequest>,+) -> Result<Json<StringIDResponse>, ChatHandlerErr> {+ let id = state+ .inner+ .create(+ user.macro_user_id,+ CreateChatArgs {+ name: req.name.unwrap_or_else(|| "New Chat".to_string()),+ project_id: req.project_id,+ },+ )+ .await?;++ Ok(Json(StringIDResponse { id }))+}++#[utoipa::path(+ get,+ path = "/chats/{chat_id}",+ tag = "chats",+ operation_id = "get_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200, body = GetChatResponse),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+/// Get a chat by ID with messages and web citations.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<Json<GetChatResponse>, ChatHandlerErr> {+ let response = state.inner.get_chat(access.entity_access_receipt).await?;++ Ok(Json(response))+}++#[utoipa::path(+ delete,+ path = "/chat/{chat_id}",+ tag = "chats",+ operation_id = "delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Soft-delete a chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<StatusCode, ChatHandlerErr> {+ state.inner.delete(access.entity_access_receipt).await?;+ Ok(StatusCode::OK)+}++#[utoipa::path(+ delete,+ path = "/chat/{chat_id}/permanent",+ tag = "chats",+ operation_id = "permanently_delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Permanently delete a chat and all associated data.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .permanently_delete(access.entity_access_receipt)+ .await?;+ Ok(StatusCode::OK)+}++/// Request body for patching a chat.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct PatchChatRequest {+ /// New name for the chat.+ pub name: Option<String>,+ /// New project ID for the chat. Empty string clears the project.+ pub project_id: Option<String>,+ /// Share permission updates.+ pub share_permission:+ Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,+}++#[utoipa::path(+ patch,+ path = "/chat/{chat_id}",+ tag = "chats",+ operation_id = "patch_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Patch a chat's name, project, or share permissions.+#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id))]+pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+ Json(req): Json<PatchChatRequest>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .patch(+ access.entity_access_receipt,+ PatchChatArgs {+ name: req.name,+ project_id: req.project_id,+ share_permission: req.share_permission,+ },+ )+ .await?;++ Ok(StatusCode::OK)+}++#[utoipa::path(+ post,+ path = "/chats/{chat_id}/copy",+ tag = "chats",+ operation_id = "copy_chat",+ params(("chat_id" = String, Path, description = "ID of the chat to copy")),+ responses(+ (status = 200, body = StringIDResponse),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+/// Copy a chat and its messages into a new chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<Json<StringIDResponse>, ChatHandlerErr> {+ let id = state.inner.copy_chat(access.entity_access_receipt).await?;+ Ok(Json(StringIDResponse { id }))+}++#[utoipa::path(+ put,+ path = "/chats/{chat_id}/revert_delete",+ tag = "chats",+ operation_id = "revert_delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat to restore")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Revert a soft-deleted chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn revert_delete_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .revert_delete(access.entity_access_receipt)+ .await?;+ Ok(StatusCode::OK)+}++/// Response body for get chat permissions.+#[derive(Debug, serde::Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct GetChatPermissionsResponse {+ /// The share permissions for the chat.+ pub permissions: SharePermissionV2,+}++#[utoipa::path(+ get,+ path = "/chats/{chat_id}/permissions",+ tag = "chats",+ operation_id = "get_chat_permissions",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200, body = GetChatPermissionsResponse),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Get the share permissions for a chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<EditAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<Json<GetChatPermissionsResponse>, ChatHandlerErr> {+ let permissions = state+ .inner+ .get_permissions(access.entity_access_receipt)+ .await?;+ Ok(Json(GetChatPermissionsResponse { permissions }))+}diff --git a/rust/cloud-storage/chat/src/inbound/mod.rs b/rust/cloud-storage/chat/src/inbound/mod.rsindex 1454506d92..0f3951a6d5 100644--- a/rust/cloud-storage/chat/src/inbound/mod.rs+++ b/rust/cloud-storage/chat/src/inbound/mod.rs@@ -1,386 +1,10 @@-//! HTTP handlers and router for the chat API.+//! Inbound HTTP adapters for the chat domain.#[cfg(test)]mod test;-use std::sync::Arc;+mod http;-use axum::{- Json, Router,- extract::{FromRef, Path, State},- http::StatusCode,- response::IntoResponse,- routing::{delete, get, post, put},-};-use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};-use entity_access::domain::ports::EntityAccessService;-use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;-use model::response::StringIDResponse;-use model_user::axum_extractor::MacroUserExtractor;-use models_permissions::share_permission::SharePermissionV2;-use serde::Deserialize;-use utoipa::ToSchema;--use crate::domain::models::{ChatErr, CreateChatArgs, GetChatResponse, PatchChatArgs};-use crate::domain::ports::ChatService;--/// Shared state for the chat router, wrapping a [`ChatService`] implementation-/// and an [`EntityAccessService`] for authorization.-pub struct ChatRouterState<S, Svc> {- inner: Arc<S>,- access_service: Arc<Svc>,-}--impl<S, Svc> Clone for ChatRouterState<S, Svc> {- fn clone(&self) -> Self {- Self {- inner: Arc::clone(&self.inner),- access_service: Arc::clone(&self.access_service),- }- }-}--impl<S, Svc> FromRef<ChatRouterState<S, Svc>> for Arc<Svc> {- fn from_ref(state: &ChatRouterState<S, Svc>) -> Self {- state.access_service.clone()- }-}--impl<S: ChatService, Svc: EntityAccessService> ChatRouterState<S, Svc> {- /// Create a new [`ChatRouterState`] from a service and access service.- pub fn new(service: S, access_service: Svc) -> Self {- Self {- inner: Arc::new(service),- access_service: Arc::new(access_service),- }- }-}--/// Build the router for the `POST /` create-chat route.-///-/// This is separated so that DCS can apply different middleware-/// (e.g. `ensure_user_exists` + quota checks) without `ensure_chat_exists`.-pub fn chat_create_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(- state: ChatRouterState<S, Svc>,-) -> Router<T> {- Router::new()- .route("/", post(create_chat_handler::<S, Svc>))- .with_state(state)-}--/// Build the router for all `/{chat_id}` routes.-///-/// These routes require `ensure_chat_exists` middleware to populate-/// `ChatBasic` in extensions before the [`ChatAccessLevelExtractor`] runs.-pub fn chat_id_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(- state: ChatRouterState<S, Svc>,-) -> Router<T> {- Router::new()- .route(- "/{chat_id}",- get(get_chat_handler::<S, Svc>)- .delete(delete_chat_handler::<S, Svc>)- .patch(patch_chat_handler::<S, Svc>),- )- .route(- "/{chat_id}/permanent",- delete(permanently_delete_chat_handler::<S, Svc>),- )- .route("/{chat_id}/copy", post(copy_chat_handler::<S, Svc>))- .route(- "/{chat_id}/revert_delete",- put(revert_delete_handler::<S, Svc>),- )- .route(- "/{chat_id}/permissions",- get(get_chat_permissions_handler::<S, Svc>),- )- .with_state(state)-}--/// HTTP error type for chat handlers, mapped from [`ChatErr`].-#[derive(Debug)]-pub enum ChatHandlerErr {- /// Something went wrong internally.- Internal,- /// The requested resource was not found.- NotFound,- /// The request was bad- BadRequest(String),-}--impl From<ChatErr> for ChatHandlerErr {- fn from(err: ChatErr) -> Self {- match err {- ChatErr::BadRequest(e) => ChatHandlerErr::BadRequest(e),- ChatErr::NotFound => ChatHandlerErr::NotFound,- ChatErr::Unknown(e) => {- tracing::error!(error=?e, "chat handler error");- ChatHandlerErr::Internal- }- }- }-}--impl IntoResponse for ChatHandlerErr {- fn into_response(self) -> axum::response::Response {- let (status, msg) = match self {- ChatHandlerErr::Internal => (- StatusCode::INTERNAL_SERVER_ERROR,- "Internal server error".to_string(),- ),- ChatHandlerErr::NotFound => (StatusCode::NOT_FOUND, "Not found".to_string()),- ChatHandlerErr::BadRequest(e) => (StatusCode::BAD_REQUEST, e),- };-- (status, msg).into_response()- }-}--/// Request body for creating a chat.-#[derive(Debug, Deserialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CreateChatRequest {- /// Optional name for the chat.- pub name: Option<String>,- /// Optional project to associate the chat with.- pub project_id: Option<String>,-}--#[utoipa::path(- post,- path = "/chats",- tag = "chats",- operation_id = "create_chat",- responses(- (status = 200, body = StringIDResponse),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Create a new chat.-#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id))]-pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(- State(state): State<ChatRouterState<S, Svc>>,- user: MacroUserExtractor,- Json(req): Json<CreateChatRequest>,-) -> Result<Json<StringIDResponse>, ChatHandlerErr> {- let id = state- .inner- .create(- user.macro_user_id,- CreateChatArgs {- name: req.name.unwrap_or_else(|| "New Chat".to_string()),- project_id: req.project_id,- },- )- .await?;-- Ok(Json(StringIDResponse { id }))-}--#[utoipa::path(- get,- path = "/chats/{chat_id}",- tag = "chats",- operation_id = "get_chat",- params(("chat_id" = String, Path, description = "ID of the chat")),- responses(- (status = 200, body = GetChatResponse),- (status = 401, body = String),- (status = 404, body = String),- (status = 500, body = String),- )-)]-/// Get a chat by ID with messages and web citations.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<Json<GetChatResponse>, ChatHandlerErr> {- let response = state.inner.get_chat(access.entity_access_receipt).await?;-- Ok(Json(response))-}--#[utoipa::path(- delete,- path = "/chat/{chat_id}",- tag = "chats",- operation_id = "delete_chat",- params(("chat_id" = String, Path, description = "ID of the chat")),- responses(- (status = 200),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Soft-delete a chat.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<StatusCode, ChatHandlerErr> {- state.inner.delete(access.entity_access_receipt).await?;- Ok(StatusCode::OK)-}--#[utoipa::path(- delete,- path = "/chat/{chat_id}/permanent",- tag = "chats",- operation_id = "permanently_delete_chat",- params(("chat_id" = String, Path, description = "ID of the chat")),- responses(- (status = 200),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Permanently delete a chat and all associated data.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<StatusCode, ChatHandlerErr> {- state- .inner- .permanently_delete(access.entity_access_receipt)- .await?;- Ok(StatusCode::OK)-}--/// Request body for patching a chat.-#[derive(Debug, Deserialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PatchChatRequest {- /// New name for the chat.- pub name: Option<String>,- /// New project ID for the chat. Empty string clears the project.- pub project_id: Option<String>,- /// Share permission updates.- pub share_permission:- Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,-}--#[utoipa::path(- patch,- path = "/chat/{chat_id}",- tag = "chats",- operation_id = "patch_chat",- params(("chat_id" = String, Path, description = "ID of the chat")),- responses(- (status = 200),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Patch a chat's name, project, or share permissions.-#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id))]-pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,- Json(req): Json<PatchChatRequest>,-) -> Result<StatusCode, ChatHandlerErr> {- state- .inner- .patch(- access.entity_access_receipt,- PatchChatArgs {- name: req.name,- project_id: req.project_id,- share_permission: req.share_permission,- },- )- .await?;-- Ok(StatusCode::OK)-}--#[utoipa::path(- post,- path = "/chats/{chat_id}/copy",- tag = "chats",- operation_id = "copy_chat",- params(("chat_id" = String, Path, description = "ID of the chat to copy")),- responses(- (status = 200, body = StringIDResponse),- (status = 401, body = String),- (status = 404, body = String),- (status = 500, body = String),- )-)]-/// Copy a chat and its messages into a new chat.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<Json<StringIDResponse>, ChatHandlerErr> {- let id = state.inner.copy_chat(access.entity_access_receipt).await?;- Ok(Json(StringIDResponse { id }))-}--#[utoipa::path(- put,- path = "/chats/{chat_id}/revert_delete",- tag = "chats",- operation_id = "revert_delete_chat",- params(("chat_id" = String, Path, description = "ID of the chat to restore")),- responses(- (status = 200),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Revert a soft-deleted chat.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn revert_delete_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<StatusCode, ChatHandlerErr> {- state- .inner- .revert_delete(access.entity_access_receipt)- .await?;- Ok(StatusCode::OK)-}--/// Response body for get chat permissions.-#[derive(Debug, serde::Serialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct GetChatPermissionsResponse {- /// The share permissions for the chat.- pub permissions: SharePermissionV2,-}--#[utoipa::path(- get,- path = "/chats/{chat_id}/permissions",- tag = "chats",- operation_id = "get_chat_permissions",- params(("chat_id" = String, Path, description = "ID of the chat")),- responses(- (status = 200, body = GetChatPermissionsResponse),- (status = 401, body = String),- (status = 500, body = String),- )-)]-/// Get the share permissions for a chat.-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]-pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessService>(- access: ChatAccessLevelExtractor<EditAccessLevel, Svc>,- State(state): State<ChatRouterState<S, Svc>>,- Path(chat_id): Path<String>,-) -> Result<Json<GetChatPermissionsResponse>, ChatHandlerErr> {- let permissions = state- .inner- .get_permissions(access.entity_access_receipt)- .await?;- Ok(Json(GetChatPermissionsResponse { permissions }))-}+// Re-exports for backwards compatibility.+pub use self::http::extractors::ChatModelAccess;+pub use self::http::router::*;diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rsindex 8d577801aa..a6de7b9d51 100644--- a/rust/cloud-storage/chat/src/inbound/test.rs+++ b/rust/cloud-storage/chat/src/inbound/test.rs@@ -1,4 +1,5 @@use axum::Extension;+use axum::Router;use axum::body::Body;use axum::http::{Request, StatusCode};use http_body_util::BodyExt;diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex c925e9c7e5..f870b250a4 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -97,6 +97,7 @@ models_opensearch = { path = "../models_opensearch" }models_permissions = { path = "../models_permissions" }regex = { workspace = true }reqwest.workspace = true+roles_and_permissions = { path = "../roles_and_permissions", default-features = false }rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }schemars = { workspace = true }scribe = { path = "../scribe", features = [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 ae50af9134..5bda036606 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@@ -6,7 +6,6 @@ use super::util::chat_permissions;use crate::api::context::ApiContext;use crate::api::utils::log;use crate::core::constants::DEFAULT_CHAT_NAME;-use crate::core::model::FALLBACK_MODEL;use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};use crate::service::get_chat::get_chat;use crate::service::notification::notify;@@ -20,6 +19,7 @@ use axum::extract::{Extension, Request, State};use axum::http::StatusCode;use axum::middleware::Next;use axum::response::IntoResponse;+use chat::inbound::ChatModelAccess;use futures::StreamExt;use macro_db_client::dcs::create_chat;use macro_user_id::user_id::MacroUserIdStr;@@ -96,6 +96,8 @@ pub struct SendChatMessageResponse {pub struct ChatMessageError {pub error: String,pub stream_id: Option<String>,+ #[serde(skip)]+ pub status: Option<StatusCode>,}impl fmt::Display for ChatMessageError {@@ -106,7 +108,8 @@ impl fmt::Display for ChatMessageError {impl IntoResponse for ChatMessageError {fn into_response(self) -> axum::response::Response {- (StatusCode::BAD_REQUEST, Json(self)).into_response()+ let status = self.status.unwrap_or(StatusCode::BAD_REQUEST);+ (status, Json(self)).into_response()}}@@ -122,12 +125,14 @@ impl IntoResponse for ChatMessageError {(status = 200, description = "Stream initiated successfully", body = SendChatMessageResponse),(status = 400, description = "Bad request", body = ChatMessageError),(status = 401, description = "Unauthorized"),+ (status = 402, description = "Payment required — user lacks access to the requested model"),(status = 403, description = "Forbidden"),))]-#[tracing::instrument(skip(state, user_context, bearer, request), fields(chat_id=?request.chat_id, user_id = %user_context.user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.attachment_id.as_str()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]+#[tracing::instrument(skip(state, model_access, user_context, bearer, request), fields(chat_id=?request.chat_id, user_id = %user_context.user_id, attachment_ids=?request.attachments.as_ref().map(|a| a.iter().map(|att| att.attachment_id.as_str()).collect::<Vec<_>>()).unwrap_or_default()), ret, err)]pub async fn send_chat_message(State(state): State<ApiContext>,+ model_access: ChatModelAccess,Extension(user_context): Extension<UserContext>,Extension(bearer): Extension<BearerToken>,Json(request): Json<HttpSendChatMessageRequest>,@@ -145,6 +150,7 @@ pub async fn send_chat_message(MacroUserIdStr::try_from(user_context.user_id.clone()).map_err(|_| ChatMessageError {error: "Invalid user ID".to_string(),stream_id: Some(stream_id.clone()),+ status: None,})?;let user_id = Arc::new(user_id);@@ -171,6 +177,7 @@ pub async fn send_chat_message(return Err(ChatMessageError {error: format!("Permission check failed: {:?}", e),stream_id: Some(stream_id),+ status: None,});}Ok(access) => match access {@@ -178,6 +185,7 @@ pub async fn send_chat_message(return Err(ChatMessageError {error: "Insufficient permissions to send messages".to_string(),stream_id: Some(stream_id),+ status: None,});}_ => (),@@ -196,11 +204,7 @@ pub async fn send_chat_message(}};- let model = if request.model == Model::Claude45Opus {- Model::Claude45Opus- } else {- FALLBACK_MODEL- };+ let model = model_access.model();// Convert HTTP request to internal payload for existing functionslet payload = SendChatMessagePayload {@@ -225,6 +229,7 @@ pub async fn send_chat_message(ChatMessageError {error: "Failed to store message".to_string(),stream_id: Some(stream_id.clone()),+ status: None,}})?;@@ -254,6 +259,7 @@ pub async fn send_chat_message(ChatMessageError {error: "Failed to build request".to_string(),stream_id: Some(stream_id.clone()),+ status: None,}})?;@@ -317,6 +323,7 @@ async fn create_new_chat(ChatMessageError {error: "Failed to create chat".to_string(),stream_id: Some(stream_id.to_string()),+ status: None,}})?;@@ -328,6 +335,7 @@ async fn create_new_chat(ChatMessageError {error: "Failed to get chat".to_string(),stream_id: Some(stream_id.to_string()),+ status: None,}})?;