Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): chat tool (#2925)

Eric Hayes4b130797584c
diff --git a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
index 3cac6309e1..0725ae32a8 100644
--- a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
@@ -179,8 +179,7 @@ const handler = createToolRenderer({
</span>{' '}
ordered by{' '}
<span class="text-accent">
- {ctx.tool.data.sortBy?.split('_').join(' ') ??
- 'recently viewed'}
+ {ctx.tool.data.sortBy?.split('_').join(' ') ?? 'default'}
</span>
</span>
</div>
diff --git a/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx b/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx
index 7ac8c8951a..9378dbb940 100644
--- a/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx
@@ -1,13 +1,12 @@
-import Microphone from '@phosphor-icons/core/regular/microphone.svg';
+import Newspaper from '@phosphor-icons/core/regular/newspaper.svg';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
const handler = createToolRenderer({
name: 'ReadCallRecord',
render: (ctx) => (
- <BaseTool type="call" icon={Microphone} renderContext={ctx.renderContext}>
- Read call transcript{' '}
- <span class="text-accent">{ctx.tool.data.callId}</span>
+ <BaseTool type="call" icon={Newspaper} renderContext={ctx.renderContext}>
+ Read <span class="text-accent">call transcript</span>
</BaseTool>
),
});
diff --git a/js/app/packages/core/component/AI/component/tool/ReadChat.tsx b/js/app/packages/core/component/AI/component/tool/ReadChat.tsx
new file mode 100644
index 0000000000..de82b9c6f3
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/ReadChat.tsx
@@ -0,0 +1,22 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import Newspaper from '@phosphor-icons/core/regular/newspaper.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'ReadChat',
+ render: (ctx) => (
+ <BaseTool icon={Newspaper} renderContext={ctx.renderContext} type="call">
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ Read <span class="text-accent">chat</span>
+ </span>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ <ItemPreview id={ctx.tool.data.chatId} type="chat" />
+ </span>
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const readChatHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/ReadContent.tsx b/js/app/packages/core/component/AI/component/tool/ReadContent.tsx
index b32a99fff4..01d1d603d5 100644
--- a/js/app/packages/core/component/AI/component/tool/ReadContent.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ReadContent.tsx
@@ -1,15 +1,19 @@
import { ItemPreview } from '@core/component/ItemPreview';
-import FileText from '@phosphor-icons/core/regular/file-text.svg';
+import Newspaper from '@phosphor-icons/core/regular/newspaper.svg';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
const handler = createToolRenderer({
name: 'ReadContent',
render: (ctx) => (
- <BaseTool icon={FileText} renderContext={ctx.renderContext} type="call">
- <div class="flex flex-row gap-2">
- <div>Read</div>
- <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ <BaseTool icon={Newspaper} renderContext={ctx.renderContext} type="call">
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ Read <span class="text-accent">document</span>
+ </span>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ </span>
</div>
</BaseTool>
),
diff --git a/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx
index e89d1148a6..0d03562572 100644
--- a/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx
@@ -1,15 +1,19 @@
import { ItemPreview } from '@core/component/ItemPreview';
-import Info from '@phosphor-icons/core/regular/info.svg';
+import Newspaper from '@phosphor-icons/core/regular/newspaper.svg';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
const handler = createToolRenderer({
name: 'ReadMetadata',
render: (ctx) => (
- <BaseTool icon={Info} renderContext={ctx.renderContext} type="call">
- <div class="flex flex-row gap-2">
- <div>Read metadata</div>
- <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ <BaseTool icon={Newspaper} renderContext={ctx.renderContext} type="call">
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ Read <span class="text-accent">metadata</span>
+ </span>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ </span>
</div>
</BaseTool>
),
diff --git a/js/app/packages/core/component/AI/component/tool/ReadThread.tsx b/js/app/packages/core/component/AI/component/tool/ReadThread.tsx
index eb904ab759..50544520e5 100644
--- a/js/app/packages/core/component/AI/component/tool/ReadThread.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ReadThread.tsx
@@ -1,11 +1,11 @@
-import EyeIcon from '@phosphor-icons/core/regular/eye.svg';
+import Newspaper from '@phosphor-icons/core/regular/newspaper.svg';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
const handler = createToolRenderer({
name: 'ReadThread',
render: (ctx) => (
- <BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>
+ <BaseTool type="call" icon={Newspaper} renderContext={ctx.renderContext}>
Read{' '}
<span class="text-accent">
{ctx.tool.data.ids.length}{' '}
diff --git a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx
index f2ef81e402..79ae08a156 100644
--- a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx
+++ b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx
@@ -13,7 +13,11 @@ import { ComposeTool } from './email/ChatCompose';
type SendEmailResponse = NamedTool<'SendEmail', 'response'>['data'];
function getRecipientsLabel(data: SendEmail) {
- const recipients = [...data.to, ...(data.cc ?? []), ...(data.bcc ?? [])];
+ const recipients = [
+ ...(data.to ?? []),
+ ...(data.cc ?? []),
+ ...(data.bcc ?? []),
+ ];
const labels = Array.from(
new Map(
recipients.map((recipient) => [
diff --git a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
index 48d189fef9..42c10c4afb 100644
--- a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
+++ b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
@@ -167,9 +167,15 @@ export function ComposeTool(props: ComposeToolProps) {
};
const [recipients, setRecipients] = createSignal({
- to: toEmailRecipients(props.initialData.to ?? []),
- cc: toEmailRecipients(props.initialData.cc ?? []),
- bcc: toEmailRecipients(props.initialData.bcc ?? []),
+ to: toEmailRecipients(
+ (props.initialData.to ?? []).map((r) => ({ ...r, name: r.name ?? null }))
+ ),
+ cc: toEmailRecipients(
+ (props.initialData.cc ?? []).map((r) => ({ ...r, name: r.name ?? null }))
+ ),
+ bcc: toEmailRecipients(
+ (props.initialData.bcc ?? []).map((r) => ({ ...r, name: r.name ?? null }))
+ ),
});
const [subject, setSubject] = createSignal(props.initialData.subject ?? '');
const [isSending, setIsSending] = createSignal(false);
diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsx
index 3009910953..f950722a59 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -15,6 +15,7 @@ import {
setEntityPropertyHandler,
} from './Properties';
import { readCallRecordHandler } from './ReadCallRecord';
+import { readChatHandler } from './ReadChat';
import { readContentHandler } from './ReadContent';
import { readMetadataHandler } from './ReadMetadata';
import { readThreadHandler } from './ReadThread';
@@ -23,8 +24,8 @@ import { sendEmailHandler } from './SendEmail';
import { subagentHandler } from './Subagent';
import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';
import {
- ToolErrorContext,
type RenderContext,
+ ToolErrorContext,
type ToolHandler,
type ToolHandlerMap,
type ToolRenderContext,
@@ -43,6 +44,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
GetThread: getThreadHandler,
NameSearch: nameSearchHandler,
ReadCallRecord: readCallRecordHandler,
+ ReadChat: readChatHandler,
ReadThread: readThreadHandler,
ReadContent: readContentHandler,
ReadMetadata: readMetadataHandler,
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachments.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachments.ts
index 892a42ca16..e14500c9b8 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachments.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachments.ts
@@ -16,7 +16,8 @@ export interface ChatMessageWithAttachments {
content: ChatMessageContent;
/** The chat message id */
id: string;
- /** The model used to generate the message */
+ /** The model used to generate the message
+kill */
model?: ChatMessageWithAttachmentsModel;
/** Whether the chat is from the user or system */
role: Role;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachmentsModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachmentsModel.ts
index 7f958ac9ef..a9642abea4 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachmentsModel.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageWithAttachmentsModel.ts
@@ -7,5 +7,6 @@
/**
* The model used to generate the message
+kill
*/
export type ChatMessageWithAttachmentsModel = string | null;
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.ts
index 04e57d2d15..ffa9b773d7 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
@@ -529,6 +529,20 @@ export const ReadCallRecordResponse = z.object({
),
});
+export const ReadChat = z.object({ chatId: z.string() });
+
+export const ReadChatResponse = z.object({
+ chatId: z.string(),
+ messages: z.array(
+ z.object({
+ attachmentIds: z.array(z.string()),
+ content: z.string(),
+ role: z.string(),
+ })
+ ),
+ title: z.string(),
+});
+
export const ReadContent = z.object({ documentId: z.string().uuid() });
export const ReadContentResponse = z.object({
@@ -638,54 +652,6 @@ export const ReadMetadataResponse = z.object({
userAccessLevel: z.enum(['view', 'comment', 'edit', 'owner']),
});
-export const ReadResponse = z.object({
- content: z.any().superRefine((x, ctx) => {
- const schemas = [
- 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({
- attachmentIds: z.array(z.string()),
- content: z.string(),
- date: z.string().datetime({ offset: true }),
- })
- ),
- title: z.string(),
- })
- ),
- type: z.literal('chat'),
- }),
- z.object({
- formatted_preview: z.string(),
- type: z.literal('itemPreviews'),
- }),
- ];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) => (result.error ? [...errors, result.error] : errors))(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
-});
-
export const SendEmail = z.object({
bcc: z
.array(
@@ -1152,3 +1118,51 @@ export const TextEditorCodeExecutionResponse = z.object({
}),
tool_use_id: z.string(),
});
+
+export const ReadResponse = z.object({
+ content: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ 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({
+ attachmentIds: z.array(z.string()),
+ content: z.string(),
+ date: z.string().datetime({ offset: true }),
+ })
+ ),
+ title: z.string(),
+ })
+ ),
+ type: z.literal('chat'),
+ }),
+ z.object({
+ formatted_preview: z.string(),
+ type: z.literal('itemPreviews'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+});
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
index 0b455c74d5..e6e8d3c475 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
@@ -37,6 +37,7 @@ type ToolParserMap = {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
};
+ ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadMetadata: {
call: types.ReadMetadata;
@@ -98,6 +99,7 @@ const toolParserMap = {
call: schemas.ReadCallRecord,
response: schemas.ReadCallRecordResponse,
},
+ ReadChat: { call: schemas.ReadChat, response: schemas.ReadChatResponse },
ReadContent: {
call: schemas.ReadContent,
response: schemas.ReadContentResponse,
@@ -170,6 +172,7 @@ type ToolDataMap = {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
};
+ ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadMetadata: {
call: types.ReadMetadata;
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.ts
index b3670d18eb..6134142b25 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
@@ -469,6 +469,23 @@ export interface ChannelSearchResult {
*/
updated_at?: string | null;
}
+/**
+ * A single message in the tool response.
+ */
+export interface ChatMessagePreview {
+ /**
+ * IDs of attachments referenced by this message.
+ */
+ attachmentIds: string[];
+ /**
+ * The text content of the message.
+ */
+ content: string;
+ /**
+ * The role of the message author (user, assistant, or system).
+ */
+ role: string;
+}
/**
* A chat match for a given message id
*/
@@ -1171,6 +1188,32 @@ export interface TranscriptSegment {
*/
startedAt: string;
}
+/**
+ * Retrieve a chat thread's message history by its ID. Returns the conversation title and messages with their roles, content, and attachment references.
+ */
+export interface ReadChat {
+ /**
+ * The id of the chat thread to read.
+ */
+ chatId: string;
+}
+/**
+ * Response for [`ReadChat`].
+ */
+export interface ReadChatResponse {
+ /**
+ * The chat id.
+ */
+ chatId: string;
+ /**
+ * The messages in the chat.
+ */
+ messages: ChatMessagePreview[];
+ /**
+ * The chat title.
+ */
+ title: string;
+}
/**
* Retrieve a documents content
*/
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 4514a1aa6a..b6d333e893 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -1497,7 +1497,7 @@
},
"model": {
"type": ["string", "null"],
- "description": "The model used to generate the message"
+ "description": "The model used to generate the message\nkill"
},
"role": {
"$ref": "#/components/schemas/Role",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index ca2c302979..a336a14ad6 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -97,6 +97,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"call",
+ "chat",
"chrono",
"comms",
"connection",
@@ -1921,6 +1922,7 @@ dependencies = [
"ai",
"ai_toolset",
"anyhow",
+ "async-trait",
"attachment",
"axum",
"chrono",
@@ -1939,6 +1941,7 @@ dependencies = [
"models_permissions",
"non_empty",
"roles_and_permissions",
+ "schemars",
"serde",
"serde_json",
"sqlx",
@@ -6498,6 +6501,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"call",
+ "chat",
"comms",
"document_storage_service_client",
"documents",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 40cc82bb2a..aa58f1110b 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -17,6 +17,7 @@ async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
+chat = { path = "../chat", features = ["ai_tools", "outbound"] }
chrono.workspace = true
dateparser.workspace = true
comms = { path = "../comms", features = ["outbound"] }
diff --git a/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs b/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs
index b7b5f32928..2fcab9cae7 100644
--- a/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs
+++ b/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs
@@ -1,8 +1,7 @@
//! Binary to generate combined tool schemas JSON file.
fn main() {
- let mut combined = ai_tools::all_tool_combined_schema();
- combined.mangle_collisions();
+ let combined = ai_tools::all_tool_combined_schema();
let json = serde_json::to_string_pretty(&combined).expect("serialize schemas");
std::fs::create_dir("schemas").expect("create schemas dir");
std::fs::write("schemas/tools.json", &json).expect("write tools.json");
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index fbea768c81..57f3464c13 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -269,6 +269,20 @@ pub async fn build_tool_service_context_from_env(
(*entity_access_service).clone(),
);
+ let chat_repo = chat::outbound::postgres::PgChatRepo::new(pool.clone());
+ let chat_service = chat::domain::service::ChatServiceImpl::new(
+ chat_repo,
+ Arc::new(ai_toolset::AsyncToolSet::new()),
+ (),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
+ );
+ let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
+ chat_service,
+ (*entity_access_service).clone(),
+ );
+
Ok(ToolServiceContext {
search_service_client: search_client,
email_service_client: email_ext_client,
@@ -279,6 +293,7 @@ pub async fn build_tool_service_context_from_env(
properties_tool_context,
email_tool_context,
call_tool_context,
+ chat_tool_context,
schedule_tool_context: crate::NoOpScheduleContext,
})
}
diff --git a/rust/cloud-storage/ai_tools/src/code_execution.rs b/rust/cloud-storage/ai_tools/src/code_execution.rs
deleted file mode 100644
index 880631a847..0000000000
--- a/rust/cloud-storage/ai_tools/src/code_execution.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-use ai::tool::schema::PhantomTool;
-use anthropic::types::response::code_execution::{
- BashCodeExecutionResponse, BashCodeExecutionToolCall, TextEditorCodeExecutionResponse,
- TextEditorCodeExecutionToolCall,
-};
-use lazy_static::lazy_static;
-
-lazy_static! {
- pub static ref anthropic_bash_code_execution_tool: PhantomTool<BashCodeExecutionToolCall, BashCodeExecutionResponse> =
- PhantomTool::new("bash_code_execution");
- pub static ref anthropic_text_editor_code_execution_tool: PhantomTool<TextEditorCodeExecutionToolCall, TextEditorCodeExecutionResponse> =
- PhantomTool::new("text_editor_code_execution");
-}
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 3c85bf5eb9..7067ae98c5 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -3,28 +3,22 @@
use ai_toolset::AsyncToolSet;
use ai_toolset::schema::{CombinedToolSchemas, ToolSchemaGenerator};
mod build_context;
-pub mod code_execution;
pub mod prompts;
-pub mod read;
-#[allow(dead_code)]
-mod rewrite;
+mod schemas;
pub mod search;
pub mod serde_utils;
mod subagent;
mod tool_context;
-pub mod web_fetch;
+
use call::inbound::toolset::call_toolset;
-use code_execution::{
- anthropic_bash_code_execution_tool, anthropic_text_editor_code_execution_tool,
-};
+use chat::inbound::toolset::chat_toolset;
use documents::inbound::toolset::document_toolset;
use email::inbound::toolset::email_toolset;
use properties::inbound::toolset::properties_toolset;
-use search::web::anthropic_web_search::anthropic_web_search_tool;
+use schemas::{anthropic_tools, read};
use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
use subagent::Subagent;
-use web_fetch::anthropic_web_fetch_tool;
pub use build_context::build_tool_service_context_from_env;
pub use search::search_toolset;
@@ -56,10 +50,10 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
AsyncToolSet::new()
.add_toolset(search_toolset())
.add_tool::<ListEntities, SoupToolContext<ToolSoupService, ToolEmailService>>()
- .add_tool::<read::ReadThread, Arc<ToolScribe>>()
.add_subtoolset::<ToolDocumentToolContext>(document_toolset())
.add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
.add_subtoolset::<ToolCallToolContext>(call_toolset())
+ .add_subtoolset::<ToolChatToolContext>(chat_toolset())
}
/// These are actually sent to the AI provider
@@ -87,13 +81,16 @@ pub fn all_tool_combined_schema() -> CombinedToolSchemas {
let mut tools = Vec::new();
tools.extend(all_tools().register_schemas(&mut generator));
- tools.extend(anthropic_web_search_tool.register_schemas(&mut generator));
- tools.extend(anthropic_web_fetch_tool.register_schemas(&mut generator));
- tools.extend(anthropic_bash_code_execution_tool.register_schemas(&mut generator));
- tools.extend(anthropic_text_editor_code_execution_tool.register_schemas(&mut generator));
+ tools.extend(anthropic_tools::web_search().register_schemas(&mut generator));
+ tools.extend(anthropic_tools::web_fetch().register_schemas(&mut generator));
+ tools.extend(anthropic_tools::bash_code_execution().register_schemas(&mut generator));
+ tools.extend(anthropic_tools::text_editor_code_execution().register_schemas(&mut generator));
+ tools.extend(read::read_thread().register_schemas(&mut generator));
let defs = generator.take_definitions(true);
- CombinedToolSchemas { defs, tools }
+ let mut combined = CombinedToolSchemas { defs, tools };
+ combined.mangle_collisions();
+ combined
}
pub fn no_tools() -> ToolSetWithPrompt {
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
deleted file mode 100644
index 3fcf67ec5c..0000000000
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ /dev/null
@@ -1,312 +0,0 @@
-use crate::serde_utils::deserialize_permissive_datetime_opt;
-use crate::tool_context::ToolScribe;
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
-use anyhow::anyhow;
-use async_trait::async_trait;
-use chrono::{DateTime, Utc};
-use model::chat::ChatHistory;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use std::sync::Arc;
-
-pub const MAX_MESSAGES: i64 = 150;
-
-#[derive(Debug, JsonSchema, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ReadResponse {
- pub content: ReadContent,
-}
-
-// TODO: this should be hoisted to "ai_format" so that consistent formats can be used everywhere
-// TODO: tool calls should be formatted with xml tags not json
-// TODO: We should minimize nested context
-#[derive(Debug, JsonSchema, Serialize)]
-#[serde(rename_all = "camelCase")]
-#[serde(tag = "type")]
-pub enum ReadContent {
- Channel {
- channel_id: String,
- channel_name: Option<String>,
- transcript: String,
- },
- Chat {
- #[serde(flatten)]
- history: ChatHistory,
- },
- ItemPreviews {
- formatted_preview: String,
- },
-}
-
-#[derive(Debug, JsonSchema, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentMetadata {
- pub document_name: String,
- pub owner: String,
- pub file_type: Option<String>,
- pub project_id: Option<String>,
- pub deleted: bool,
-}
-
-#[derive(Debug, JsonSchema, Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-#[schemars(
- description = "Read threaded content by ID(s). Supports reading channels, chats, and projects by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s). For documents, use ReadContent or ReadMetadata instead.
- Channel transcripts only include the latest 150 messages. Use 'messages_since' to see messages in a different time window.",
- title = "ReadThread"
-)]
-pub struct ReadThread {
- #[schemars(
- description = "The type of content to read. Choose based on the type of content you want to retrieve."
- )]
- pub content_type: ContentType,
- #[schemars(
- description = "ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and content types support MULTIPLE ids! For all other content types (channel, chat-thread) provide a single id."
- )]
- pub ids: Vec<String>,
- #[schemars(
- description = "A local datetime of the earliest message to include in a channel transcript following ISO 8601 format, only applicable to channels"
- )]
- #[serde(default, deserialize_with = "deserialize_permissive_datetime_opt")]
- pub messages_since: Option<DateTime<Utc>>,
-}
-
-#[derive(Debug, JsonSchema, Deserialize, Clone, strum::EnumString, strum::Display)]
-#[serde(rename_all = "kebab-case")]
-#[strum(serialize_all = "kebab-case")]
-pub enum ContentType {
- Channel,
- ChannelMessage,
- ChatThread,
- ChatMessage,
- Project,
-}
-
-#[async_trait]
-impl AsyncTool<Arc<ToolScribe>> for ReadThread {
- type Output = ReadResponse;
-
- #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
- async fn call(
- &self,
- scribe: ServiceContext<Arc<ToolScribe>>,
- request_context: RequestContext,
- ) -> ToolResult<Self::Output> {
- tracing::info!(self=?self, "ReadThread tool params");
-
- if self.ids.is_empty() {
- return Err(ToolCallError {
- description: "no ids provided".to_string(),
- internal_error: anyhow::anyhow!("no ids provided"),
- });
- }
-
- let content = match self.content_type {
- 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::Project => self.read_project(&scribe, &request_context).await?,
- };
-
- let tool_response = ReadResponse { content };
-
- ToolResult::Ok(tool_response)
- }
-}
-
-impl ReadThread {
- fn provide_single_id(&self) -> Result<String, ToolCallError> {
- if self.ids.len() > 1 {
- return Err(ToolCallError {
- description: format!(
- "only single id is supported in ids field for content type {}",
- self.content_type
- ),
- internal_error: anyhow::anyhow!(
- "only single id is supported in ids field for content type"
- ),
- });
- }
- Ok(self.ids[0].clone())
- }
-
- async fn read_project(
- &self,
- scribe: &ToolScribe,
- request_context: &RequestContext,
- ) -> Result<ReadContent, ToolCallError> {
- let id = self.ids.first().ok_or(ToolCallError {
- description: "Expected a single id to read a project".into(),
- internal_error: anyhow!("Bad tool args"),
- })?;
-
- 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(|f| ReadContent::ItemPreviews {
- formatted_preview: f.to_string(),
- })
- }
-
- async fn read_channel(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {
- let id = self.provide_single_id()?;
-
- let since = self
- .messages_since
- .unwrap_or_else(|| chrono::Utc::now() - chrono::Duration::days(7));
- // Get channel metadata
- let metadata = scribe
- .channel
- .get_channel_metadata(id.as_str())
- .await
- .map_err(|e| ToolCallError {
- description: format!("failed to fetch channel metadata: {}", e),
- internal_error: e,
- })?;
-
- // Get channel transcript
- let transcript = scribe
- .channel
- .get_channel_transcript(id.as_str(), Some(since), Some(MAX_MESSAGES))
- .await
- .map_err(|e| ToolCallError {
- description: format!("failed to fetch channel transcript: {}", e),
- internal_error: e,
- })?;
-
- Ok(ReadContent::Channel {
- channel_id: id,
- channel_name: Some(metadata.name),
- transcript,
- })
- }
-
- async fn read_channel_message(
- &self,
- scribe: &ToolScribe,
- ) -> Result<ReadContent, ToolCallError> {
- let mut transcripts = Vec::new();
- let mut channel_id = String::new();
-
- for id in &self.ids {
- // Get messages with context
- let transcript = match scribe
- .channel
- .get_message_with_context(id.as_str(), 0, 0)
- .await
- {
- Ok(t) => t,
- Err(e) => {
- tracing::warn!("failed to fetch channel message {}: {}", id, e);
- continue; // Skip failed messages instead of failing the entire request
- }
- };
-
- // Use the channel_id from the first message
- if channel_id.is_empty() {
- channel_id = id.clone();
- }
-
- transcripts.push(transcript);
- }
-
- if transcripts.is_empty() {
- return Err(ToolCallError {
- description: "failed to fetch any channel messages".to_string(),
- internal_error: anyhow::anyhow!("all channel message fetches failed"),
- });
- }
-
- // Combine transcripts with separators for multiple messages
- let combined_transcript = if transcripts.len() == 1 {
- transcripts.into_iter().next().unwrap()
- } else {
- transcripts.join("\n\n---\n\n")
- };
-
- // Note: We don't fetch channel metadata here since the user is focused on a specific message
- // The message_id itself doesn't directly give us the channel_id, but the transcript
- // includes the conversation context
- Ok(ReadContent::Channel {
- channel_id,
- channel_name: None,
- transcript: combined_transcript,
- })
- }
-
- 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)
- .await
- .map_err(|e| ToolCallError {
- description: format!("failed to fetch chat thread: {}", e),
- internal_error: e,
- })?;
-
- Ok(ReadContent::Chat { history })
- }
-
- 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)
- .await
- .map_err(|e| ToolCallError {
- description: format!("failed to fetch chat messages: {}", e),
- internal_error: e,
- })?;
-
- Ok(ReadContent::Chat { history })
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ai_toolset::tool_object::validate_tool_schema;
- use ai_toolset::{generate_tool_input_schema, generate_tool_output_schema};
-
- // run `cargo test -p ai_tools read::tests::print_input_schema -- --nocapture --include-ignored`
- #[test]
- #[ignore = "prints the input schema"]
- fn print_input_schema() {
- let schema = generate_tool_input_schema!(ReadThread);
- println!("{}", serde_json::to_string_pretty(&schema).unwrap());
- }
-
- // run `cargo test -p ai_tools read::tests::print_output_schema -- --nocapture --include-ignored`
- #[test]
- #[ignore = "prints the output schema"]
- fn print_output_schema() {
- let schema = generate_tool_output_schema!(ReadResponse);
- println!("{}", serde_json::to_string_pretty(&schema).unwrap());
- }
-
- #[test]
- fn test_read_schema_validation() {
- let schema = generate_tool_input_schema!(ReadThread);
-
- let result = validate_tool_schema(&schema);
- assert!(result.is_ok(), "{:?}", result);
-
- let (name, description) = result.unwrap();
- assert_eq!(
- name, "ReadThread",
- "Tool name should match the schemars title"
- );
- assert!(
- description.contains("Read threaded content by ID"),
- "Description should contain expected text"
- );
- }
-}
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/mod.rs b/rust/cloud-storage/ai_tools/src/rewrite/mod.rs
deleted file mode 100644
index e7d42b6c48..0000000000
--- a/rust/cloud-storage/ai_tools/src/rewrite/mod.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-#![allow(unused)]
-
-pub mod tool;
-pub mod types;
-
-pub use tool::MarkdownRewrite;
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/types.rs b/rust/cloud-storage/ai_tools/src/rewrite/types.rs
deleted file mode 100644
index f995eac2d6..0000000000
--- a/rust/cloud-storage/ai_tools/src/rewrite/types.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use ai::traits::Metadata;
-use ai::types::Model;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-pub static REWRITE_MODEL: Model = Model::OpenAIGPT4o;
-pub static PROMPT: &str = concat!(
- "export const rewritePrompt: string = `Using the provided list of nodeKeys (unique identifiers for nodes in a Lexical markdown editor)",
- " and their associated markdown content, generate a structured set of document diffs (revisions) to follow the users change directives",
- " Return your response as a JSON object following the AI diffs schema format with an array of diff objects, each containing: an 'operation' field",
- " (either 'INSERT_AFTER', 'INSERT_BEFORE', 'DELETE', or 'MODIFY'), a 'node_id' field (must be one of the provided nodeKeys), and a 'text' field (",
- " containing new or modified content, or empty for DELETE operations). Create meaningful diffs that add transitions between disconnected paragraphs",
- ", break up lengthy text, insert relevant subheadings, fix errors, ensure consistent formatting, remove redundancies, enhance clarity of technical ",
- " explanations, add illustrative examples, or insert concise summaries after complex sections, while only using existing nodeKeys and maintaining",
- "overall document coherence. Maintain the markdown syntax. Respect the XML components when possible, as they contain custom elements supported by our app.`;"
-);
-
-#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
-#[serde(deny_unknown_fields)]
-pub struct AIDiffResponse {
- pub diffs: Vec<Diff>,
-}
-
-#[derive(Serialize, Deserialize, JsonSchema, ToSchema, Debug)]
-#[serde(deny_unknown_fields)]
-pub struct Diff {
- pub operation: String,
- pub node_key: String,
- pub markdown_text: String,
-}
-
-impl Metadata for AIDiffResponse {
- fn name() -> String {
- "AIDiffResponse".to_string()
- }
- fn description() -> Option<String> {
- Some("An list of diffs to be applied to a markdown document.".to_string())
- }
-}
diff --git a/rust/cloud-storage/ai_tools/src/schemas/anthropic_tools.rs b/rust/cloud-storage/ai_tools/src/schemas/anthropic_tools.rs
new file mode 100644
index 0000000000..8776a16241
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/schemas/anthropic_tools.rs
@@ -0,0 +1,27 @@
+use ai_toolset::schema::PhantomTool;
+use anthropic::types::response::code_execution::{
+ BashCodeExecutionResponse, BashCodeExecutionToolCall, TextEditorCodeExecutionResponse,
+ TextEditorCodeExecutionToolCall,
+};
+use anthropic::types::response::web_fetch::{WebFetchResponse, WebFetchToolCall};
+use anthropic::types::response::web_search::{WebSearchResponse, WebSearchToolCall};
+
+/// Schemas for frontend type generation for the builtin claude web search tool
+/// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>
+/// This tool is built into anthropic so is not included in the toolset / sent in the request
+pub fn web_search() -> PhantomTool<WebSearchToolCall, WebSearchResponse> {
+ PhantomTool::new("web_search")
+}
+
+pub fn web_fetch() -> PhantomTool<WebFetchToolCall, WebFetchResponse> {
+ PhantomTool::new("web_fetch")
+}
+
+pub fn bash_code_execution() -> PhantomTool<BashCodeExecutionToolCall, BashCodeExecutionResponse> {
+ PhantomTool::new("bash_code_execution")
+}
+
+pub fn text_editor_code_execution()
+-> PhantomTool<TextEditorCodeExecutionToolCall, TextEditorCodeExecutionResponse> {
+ PhantomTool::new("text_editor_code_execution")
+}
diff --git a/rust/cloud-storage/ai_tools/src/schemas/mod.rs b/rust/cloud-storage/ai_tools/src/schemas/mod.rs
new file mode 100644
index 0000000000..1bf990514f
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/schemas/mod.rs
@@ -0,0 +1,7 @@
+//! Some of these are old tools that may still exist in the database.
+//! Some of these are tools that are executed by the AI provider.
+//! These are just schemas _not_ tools and aren't sent to AI. The
+//! schemas are kept here so that typegen and frontend rendering works.
+
+pub mod anthropic_tools;
+pub mod read;
diff --git a/rust/cloud-storage/ai_tools/src/schemas/read.rs b/rust/cloud-storage/ai_tools/src/schemas/read.rs
new file mode 100644
index 0000000000..b684a0bc1e
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/schemas/read.rs
@@ -0,0 +1,82 @@
+#![allow(dead_code)]
+use crate::serde_utils::deserialize_permissive_datetime_opt;
+use ai_toolset::schema::PhantomTool;
+use chrono::{DateTime, Utc};
+use model::chat::ChatHistory;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, JsonSchema, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadResponse {
+ pub content: ReadContent,
+}
+
+// TODO: this should be hoisted to "ai_format" so that consistent formats can be used everywhere
+// TODO: tool calls should be formatted with xml tags not json
+// TODO: We should minimize nested context
+#[derive(Debug, JsonSchema, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "type")]
+pub enum ReadContent {
+ Channel {
+ channel_id: String,
+ channel_name: Option<String>,
+ transcript: String,
+ },
+ Chat {
+ #[serde(flatten)]
+ history: ChatHistory,
+ },
+ ItemPreviews {
+ formatted_preview: String,
+ },
+}
+
+#[derive(Debug, JsonSchema, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentMetadata {
+ pub document_name: String,
+ pub owner: String,
+ pub file_type: Option<String>,
+ pub project_id: Option<String>,
+ pub deleted: bool,
+}
+
+#[derive(Debug, JsonSchema, Deserialize, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ description = "Read threaded content by ID(s). Supports reading channels, chats, and projects by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s). For documents, use ReadContent or ReadMetadata instead.
+ Channel transcripts only include the latest 150 messages. Use 'messages_since' to see messages in a different time window.",
+ title = "ReadThread"
+)]
+pub struct ReadThread {
+ #[schemars(
+ description = "The type of content to read. Choose based on the type of content you want to retrieve."
+ )]
+ pub content_type: ContentType,
+ #[schemars(
+ description = "ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and content types support MULTIPLE ids! For all other content types (channel, chat-thread) provide a single id."
+ )]
+ pub ids: Vec<String>,
+ #[schemars(
+ description = "A local datetime of the earliest message to include in a channel transcript following ISO 8601 format, only applicable to channels"
+ )]
+ #[serde(default, deserialize_with = "deserialize_permissive_datetime_opt")]
+ pub messages_since: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, JsonSchema, Deserialize, Clone, strum::EnumString, strum::Display)]
+#[serde(rename_all = "kebab-case")]
+#[strum(serialize_all = "kebab-case")]
+pub enum ContentType {
+ Channel,
+ ChannelMessage,
+ ChatThread,
+ ChatMessage,
+ Project,
+}
+
+pub fn read_thread() -> PhantomTool<ReadThread, ReadResponse> {
+ PhantomTool::new("ReadThread")
+}
diff --git a/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs b/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs
deleted file mode 100644
index 9ac8404827..0000000000
--- a/rust/cloud-storage/ai_tools/src/search/web/anthropic_web_search.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use ai_toolset::schema::PhantomTool;
-use anthropic::types::response::web_search::{WebSearchResponse, WebSearchToolCall};
-use lazy_static::lazy_static;
-
-lazy_static! {
- pub static ref anthropic_web_search_tool: PhantomTool<WebSearchToolCall, WebSearchResponse> =
- PhantomTool::new("web_search");
-}
diff --git a/rust/cloud-storage/ai_tools/src/search/web/mod.rs b/rust/cloud-storage/ai_tools/src/search/web/mod.rs
index 59c62b33a6..d356908d1f 100644
--- a/rust/cloud-storage/ai_tools/src/search/web/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/search/web/mod.rs
@@ -1,6 +1 @@
-/// Schemas for frontend type generation for the builtin claude web search tool
-/// <https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>
-/// This tool is built into anthropic so is not included in the toolset / sent in the request
-pub mod anthropic_web_search;
-
pub mod perplexity_search;
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index aca754153b..6be6ce95d7 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -5,6 +5,9 @@ use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};
use call::inbound::toolset::CallToolContext;
use call::outbound::pg_call_repo::PgCallRepo;
use call::outbound::s3_recording_storage::S3RecordingStorage;
+use chat::domain::service::ChatServiceImpl;
+use chat::inbound::toolset::ChatToolContext;
+use chat::outbound::postgres::PgChatRepo;
use connection::domain::ports::ConnectionService;
use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};
use email::{
@@ -255,6 +258,13 @@ pub type ToolCallRecordQueryService = CallRecordQueryServiceImpl<PgCallRepo>;
pub type ToolCallToolContext =
CallToolContext<ToolCallService, ToolCallRecordQueryService, ToolEntityAccessService>;
+/// Type alias for the chat service implementation used by AI tools.
+/// Uses an empty toolset — the read-only tool never invokes tool execution.
+pub type ToolChatService = ChatServiceImpl<PgChatRepo, (), ToolEntityAccessManagementService>;
+
+/// Type alias for the chat tool context
+pub type ToolChatToolContext = ChatToolContext<ToolChatService, ToolEntityAccessService>;
+
#[derive(Clone, Default)]
pub struct NoOpScheduleContext;
@@ -276,6 +286,7 @@ pub struct ToolServiceContext {
pub properties_tool_context: ToolPropertiesToolContext,
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
+ pub chat_tool_context: ToolChatToolContext,
pub schedule_tool_context: NoOpScheduleContext,
}
diff --git a/rust/cloud-storage/ai_tools/src/web_fetch.rs b/rust/cloud-storage/ai_tools/src/web_fetch.rs
deleted file mode 100644
index ead07bd86e..0000000000
--- a/rust/cloud-storage/ai_tools/src/web_fetch.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use ai_toolset::schema::PhantomTool;
-use anthropic::types::response::web_fetch::{WebFetchResponse, WebFetchToolCall};
-use lazy_static::lazy_static;
-
-lazy_static! {
- pub static ref anthropic_web_fetch_tool: PhantomTool<WebFetchToolCall, WebFetchResponse> =
- PhantomTool::new("web_fetch");
-}
diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.toml
index b122da2550..a6c539add3 100644
--- a/rust/cloud-storage/chat/Cargo.toml
+++ b/rust/cloud-storage/chat/Cargo.toml
@@ -5,7 +5,8 @@ publish = false
version = "0.1.0"
[features]
-default = ["inbound", "outbound", "ports"]
+default = ["ai_tools", "inbound", "outbound", "ports"]
+ai_tools = ["dep:async-trait", "dep:schemars", "inbound", "ports"]
attachment = [
"dep:attachment",
"dep:futures",
@@ -50,6 +51,10 @@ uuid = { workspace = true }
attachment = { path = "../attachment", optional = true }
futures = { workspace = true, optional = true }
+# AI tools (toolset adapter)
+async-trait = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
+
# Inbound (HTTP handlers)
axum = { workspace = true, optional = true }
model_user = { path = "../model_user", optional = true }
diff --git a/rust/cloud-storage/chat/src/inbound/mod.rs b/rust/cloud-storage/chat/src/inbound/mod.rs
index 97f4664b3a..555f1e6b0d 100644
--- a/rust/cloud-storage/chat/src/inbound/mod.rs
+++ b/rust/cloud-storage/chat/src/inbound/mod.rs
@@ -8,6 +8,10 @@ mod test;
mod http;
+/// AI toolset exposing chat history to agents.
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
+
// 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/toolset/mod.rs b/rust/cloud-storage/chat/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..ba72369764
--- /dev/null
+++ b/rust/cloud-storage/chat/src/inbound/toolset/mod.rs
@@ -0,0 +1,60 @@
+//! Toolset inbound adapter for chats.
+
+mod read_chat;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::ports::ChatService;
+use ai::tool::AsyncToolSet;
+use entity_access::domain::ports::EntityAccessService;
+use read_chat::ReadChat;
+use std::sync::Arc;
+
+/// Service context for chat AI tools.
+pub struct ChatToolContext<CSvc, ESvc>
+where
+ CSvc: ChatService,
+ ESvc: EntityAccessService,
+{
+ /// The chat service — used to read chat data with access checks.
+ pub service: Arc<CSvc>,
+ /// The entity access service — used to generate access receipts.
+ pub entity_access_service: Arc<ESvc>,
+}
+
+impl<CSvc, ESvc> Clone for ChatToolContext<CSvc, ESvc>
+where
+ CSvc: ChatService,
+ ESvc: EntityAccessService,
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ }
+ }
+}
+
+impl<CSvc, ESvc> ChatToolContext<CSvc, ESvc>
+where
+ CSvc: ChatService,
+ ESvc: EntityAccessService,
+{
+ /// Create a new chat tool context.
+ pub fn new(service: CSvc, entity_access_service: ESvc) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access_service: Arc::new(entity_access_service),
+ }
+ }
+}
+
+/// Create a chat toolset.
+pub fn chat_toolset<CSvc, ESvc>() -> AsyncToolSet<ChatToolContext<CSvc, ESvc>>
+where
+ CSvc: ChatService,
+ ESvc: EntityAccessService,
+{
+ AsyncToolSet::new().add_tool::<ReadChat, ChatToolContext<CSvc, ESvc>>()
+}
diff --git a/rust/cloud-storage/chat/src/inbound/toolset/read_chat.rs b/rust/cloud-storage/chat/src/inbound/toolset/read_chat.rs
new file mode 100644
index 0000000000..2ba0b7480b
--- /dev/null
+++ b/rust/cloud-storage/chat/src/inbound/toolset/read_chat.rs
@@ -0,0 +1,114 @@
+//! ReadChat tool for fetching a chat's message history.
+
+use crate::domain::ports::ChatService;
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::{
+ models::{EntityType, ViewAccessLevel},
+ ports::EntityAccessService,
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::ChatToolContext;
+
+/// A single message in the tool response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ChatMessagePreview {
+ /// The role of the message author (user, assistant, or system).
+ pub role: String,
+ /// The text content of the message.
+ pub content: String,
+ /// IDs of attachments referenced by this message.
+ pub attachment_ids: Vec<String>,
+}
+
+/// Response for [`ReadChat`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadChatResponse {
+ /// The chat id.
+ pub chat_id: String,
+ /// The chat title.
+ pub title: String,
+ /// The messages in the chat.
+ pub messages: Vec<ChatMessagePreview>,
+}
+
+/// Tool: read a chat thread's message history.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadChat",
+ description = "Retrieve a chat thread's message history by its ID. Returns the conversation title and messages with their roles, content, and attachment references."
+)]
+pub struct ReadChat {
+ #[schemars(description = "The id of the chat thread to read.")]
+ pub chat_id: String,
+}
+
+#[async_trait]
+impl<CSvc, ESvc> AsyncTool<ChatToolContext<CSvc, ESvc>> for ReadChat
+where
+ CSvc: ChatService,
+ ESvc: EntityAccessService,
+{
+ type Output = ReadChatResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, chat_id=?self.chat_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChatToolContext<CSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Read chat");
+
+ let receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &request_context.user_id,
+ None,
+ &self.chat_id,
+ EntityType::Chat,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to verify access to chat".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ let response = service_context
+ .service
+ .get_chat(receipt)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "failed to fetch chat".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ let chat = response.chat;
+ let messages = chat
+ .messages
+ .into_iter()
+ .filter_map(|msg| {
+ let content = msg.content_text()?;
+ Some(ChatMessagePreview {
+ role: msg.role.to_string(),
+ content,
+ attachment_ids: msg
+ .attachments
+ .into_iter()
+ .map(|a| a.attachment_id)
+ .collect(),
+ })
+ })
+ .collect();
+
+ Ok(ReadChatResponse {
+ chat_id: chat.id,
+ title: chat.name,
+ messages,
+ })
+ }
+}
diff --git a/rust/cloud-storage/chat/src/inbound/toolset/test.rs b/rust/cloud-storage/chat/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..c28936ecf1
--- /dev/null
+++ b/rust/cloud-storage/chat/src/inbound/toolset/test.rs
@@ -0,0 +1,21 @@
+use super::read_chat::ReadChat;
+use ai::generate_tool_input_schema;
+use ai::tool::types::tool_object::validate_tool_schema;
+
+#[test]
+fn test_read_chat_schema_validation() {
+ let schema = generate_tool_input_schema!(ReadChat);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ReadChat",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("chat"),
+ "Description should contain expected text"
+ );
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 57375245f8..27f2d823cd 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
@@ -302,6 +302,18 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
(*entity_access_service).clone(),
);
+ let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
+ chat::domain::service::ChatServiceImpl::new(
+ chat::outbound::postgres::PgChatRepo::new(pool.clone()),
+ Arc::new(ai_toolset::AsyncToolSet::new()),
+ (),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
+ ),
+ (*entity_access_service).clone(),
+ );
+
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
@@ -312,6 +324,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ chat_tool_context,
schedule_tool_context: ai_tools::no_op_schedule_context(),
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index ab8141ad63..af435247bb 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -320,6 +320,20 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized call tool context");
+ let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
+ chat::domain::service::ChatServiceImpl::new(
+ chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ Arc::new(ai_toolset::AsyncToolSet::new()),
+ (),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
+ ),
+ (*entity_access_service).clone(),
+ );
+
+ tracing::info!("initialized chat tool context");
+
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
@@ -330,6 +344,7 @@ async fn main() -> anyhow::Result<()> {
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ chat_tool_context,
schedule_tool_context: ai_tools::NoOpScheduleContext,
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/document_cognition_service/src/model/chats.rs b/rust/cloud-storage/document_cognition_service/src/model/chats.rs
index dad39604db..757d44c922 100644
--- a/rust/cloud-storage/document_cognition_service/src/model/chats.rs
+++ b/rust/cloud-storage/document_cognition_service/src/model/chats.rs
@@ -28,11 +28,15 @@ pub struct ChatResponse {
#[deprecated(note = "Attachments are now stateless and no longer float until message send")]
pub attachments: Vec<ChatAttachmentWithName>,
/// Current number of tokens in the chat
+ // kill
pub token_count: Option<i64>,
/// Available models for the chat
+ // kill
pub available_models: Vec<Model>,
/// message_id - web citation list
+ // kill
pub web_citations: Vec<(String, Vec<GetUnfurlResponse>)>,
/// whether the chat is persistent or not
+ // kill
pub is_persistent: bool,
}
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index 14e27999dc..91ed37592b 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -13,6 +13,7 @@ aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true, features = ["tower-log"] }
call = { path = "../call", default-features = false, features = ["ports"] }
+chat = { path = "../chat", features = ["ai_tools", "outbound"] }
comms = { path = "../comms", features = ["outbound"] }
document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents", features = ["ai_tools"] }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index cb13d046b3..0bf156422c 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -274,6 +274,18 @@ async fn build_tool_context(
EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),
);
+ let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
+ chat::domain::service::ChatServiceImpl::new(
+ chat::outbound::postgres::PgChatRepo::new(db.clone()),
+ Arc::new(ai_toolset::AsyncToolSet::new()),
+ (),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
+ ),
+ EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),
+ );
+
let tool_context = ToolServiceContext {
email_service_client: Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
@@ -303,6 +315,7 @@ async fn build_tool_context(
properties_tool_context,
email_tool_context,
call_tool_context,
+ chat_tool_context,
schedule_tool_context: NoOpScheduleContext,
};
diff --git a/rust/cloud-storage/model/src/chat/message.rs b/rust/cloud-storage/model/src/chat/message.rs
index 4e3faf0686..c0388410fe 100644
--- a/rust/cloud-storage/model/src/chat/message.rs
+++ b/rust/cloud-storage/model/src/chat/message.rs
@@ -28,8 +28,10 @@ pub struct ChatMessageWithAttachments {
/// Whether the chat is from the user or system
pub role: Role,
/// The ids of the attachments used to generate the message
+ // transform to Vec<Entity<'static>>
pub attachments: Vec<ChatAttachmentWithName>,
/// The model used to generate the message
+ /// kill
pub model: Option<String>,
}