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-tools): support projects (folders) in AI tools (#5430)

gbirman5c3a644bcdeb
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 1d3d2b6180..f6fe14e357 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -49,6 +49,7 @@
"crates/crm",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -79,6 +80,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -109,6 +111,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -217,6 +220,7 @@
"crates/crm",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -247,6 +251,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -277,6 +282,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -673,6 +679,7 @@
"crates/crm",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -703,6 +710,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -733,6 +741,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -1429,6 +1438,7 @@
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -1465,6 +1475,7 @@
"crates/macro_middleware",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -1497,6 +1508,7 @@
"crates/onboarding",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -3755,6 +3767,7 @@
"crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -3788,6 +3801,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -3818,6 +3832,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -3864,6 +3879,7 @@
"crates/crm",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -3894,6 +3910,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -3925,6 +3942,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -4872,6 +4890,7 @@
"crates/database_env_vars",
"crates/document_sub_type",
"crates/documents",
+ "crates/dynamodb_client",
"crates/email",
"crates/email_service_client",
"crates/email_utils",
@@ -4905,6 +4924,7 @@
"crates/macro_event_topics",
"crates/macro_queues",
"crates/macro_service_urls",
+ "crates/macro_sha_count_client",
"crates/macro_sync_service_jwt",
"crates/macro_tower_layers",
"crates/macro_user_id",
@@ -4936,6 +4956,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/projects",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
diff --git a/Cargo.lock b/Cargo.lock
index 02f61e5518..682cb1e41c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -288,6 +288,7 @@ dependencies = [
"models_soup",
"non_empty",
"notification",
+ "projects",
"prompt",
"properties",
"rand 0.9.4",
@@ -11487,8 +11488,10 @@ dependencies = [
name = "projects"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
"anyhow",
"async-recursion",
+ "async-trait",
"aws-sdk-s3",
"aws-sdk-sqs",
"axum",
@@ -11526,6 +11529,7 @@ dependencies = [
"rdkafka",
"rootcause",
"s3_key",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/web/src/lib/core/component/AI/component/tool/CreateProject.tsx b/apps/web/src/lib/core/component/AI/component/tool/CreateProject.tsx
new file mode 100644
index 0000000000..2db17f07b2
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/CreateProject.tsx
@@ -0,0 +1,33 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import FolderPlus from '@phosphor-icons/core/regular/folder-plus.svg';
+import { Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'CreateProject',
+ render: (ctx) => (
+ <BaseTool icon={FolderPlus} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ Create folder <span class="text-ink">{ctx.tool.data.projectName}</span>
+ <Show when={ctx.response}>
+ {(response) => (
+ <>
+ {' '}
+ <span class="text-ink-placeholder">·</span>{' '}
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={response().data.projectId}
+ type="project"
+ />
+ </Suspense>
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const createProjectHandler = handler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/MoveToProject.tsx b/apps/web/src/lib/core/component/AI/component/tool/MoveToProject.tsx
new file mode 100644
index 0000000000..82d892ac90
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/MoveToProject.tsx
@@ -0,0 +1,53 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import ArrowSquareIn from '@phosphor-icons/core/regular/arrow-square-in.svg';
+import type { MoveableEntityType } from '@service-cognition/generated/tools/types';
+import type { ItemType } from '@service-storage/client';
+import { Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const ITEM_TYPES: Record<MoveableEntityType, ItemType> = {
+ document: 'document',
+ chat: 'chat',
+ email: 'email',
+ project: 'project',
+};
+
+const handler = createToolRenderer({
+ name: 'MoveToProject',
+ render: (ctx) => (
+ <BaseTool
+ icon={ArrowSquareIn}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <div class="min-w-0 flex-1">
+ Move{' '}
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={ctx.tool.data.entityId}
+ type={ITEM_TYPES[ctx.tool.data.entityType]}
+ />
+ </Suspense>{' '}
+ to{' '}
+ <Show
+ when={ctx.tool.data.projectId}
+ fallback={<span class="text-ink">top level</span>}
+ >
+ {(projectId) => (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={projectId()}
+ type="project"
+ />
+ </Suspense>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+export const moveToProjectHandler = handler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx
new file mode 100644
index 0000000000..6be3ee970a
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadProject.tsx
@@ -0,0 +1,141 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import FolderOpen from '@phosphor-icons/core/regular/folder-open.svg';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import { createSignal } from 'solid-js';
+import { VList } from 'virtua/solid';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+type ReadProjectItem = NamedTool<
+ 'ReadProject',
+ 'response'
+>['data']['items'][number];
+
+const ReadProjectToolResponse = (props: { items: ReadProjectItem[] }) => {
+ const getItemIcon = (item: ReadProjectItem) => {
+ switch (item.itemType) {
+ case 'document':
+ return (
+ <EntityIcon
+ targetType={fileTypeToBlockName(item.fileType, true)}
+ size="xs"
+ theme="monochrome"
+ />
+ );
+ case 'chat':
+ return <EntityIcon targetType="chat" size="xs" theme="monochrome" />;
+ case 'project':
+ return <EntityIcon targetType="project" size="xs" theme="monochrome" />;
+ default:
+ return undefined;
+ }
+ };
+
+ const { replaceOrInsertSplit } = useSplitLayout();
+
+ const getClickHandler = (item: ReadProjectItem) => {
+ switch (item.itemType) {
+ case 'document':
+ return () => {
+ replaceOrInsertSplit({
+ type: fileTypeToBlockName(item.fileType),
+ id: item.id,
+ });
+ };
+ case 'chat':
+ return () => {
+ replaceOrInsertSplit({ type: 'chat', id: item.id });
+ };
+ case 'project':
+ return () => {
+ replaceOrInsertSplit({ type: 'project', id: item.id });
+ };
+ default:
+ return undefined;
+ }
+ };
+
+ const itemHeight = 32;
+ const maxHeight = 240;
+
+ return (
+ <Tool.List>
+ <VList
+ class="overscroll-contain"
+ data={props.items}
+ bufferSize={itemHeight * 5}
+ itemSize={itemHeight}
+ style={{
+ height: `${Math.min(props.items.length * itemHeight, maxHeight)}px`,
+ contain: 'content',
+ }}
+ >
+ {(item) => {
+ const clickHandler = getClickHandler(item);
+
+ return (
+ <button
+ type="button"
+ class="block w-full text-left hover:bg-surface-hover"
+ onClick={clickHandler}
+ >
+ <Tool.ListItem icon={getItemIcon(item)}>
+ <div class="truncate text-xs text-ink">{item.name}</div>
+ </Tool.ListItem>
+ </button>
+ );
+ }}
+ </VList>
+ </Tool.List>
+ );
+};
+
+const handler = createToolRenderer({
+ name: 'ReadProject',
+ render: (ctx) => {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const items = () => ctx.response?.data.items ?? [];
+ const hasResults = () => items().length > 0;
+ const statusText = () => {
+ if (!ctx.response) return undefined;
+ if (items().length === 0) return 'Empty';
+ if (items().length === 1) return '1 item';
+ return `${items().length} items`;
+ };
+
+ return (
+ <BaseTool
+ icon={FolderOpen}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ hasResults() && isExpanded() ? (
+ <ReadProjectToolResponse items={items()} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <div class="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
+ <span class="min-w-0 truncate">
+ Read folder{' '}
+ <span class="text-ink">
+ {ctx.response?.data.projectName ?? ctx.tool.data.projectId}
+ </span>
+ </span>
+ </div>
+ <Tool.ResultToggle
+ expanded={isExpanded()}
+ onToggle={() => setIsExpanded((expanded) => !expanded)}
+ showToggle={hasResults()}
+ status={statusText()}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const readProjectHandler = handler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 3f252d0f38..ebce5158a0 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -6,6 +6,7 @@ import {
import { Dynamic } from 'solid-js/web';
import { bashCodeExecutionHandler } from './BashCodeExecution';
import { createDocumentHandler } from './CreateDocument';
+import { createProjectHandler } from './CreateProject';
import { createTagHandler } from './CreateTag';
import { getCompanyHandler, listCompaniesHandler } from './Crm';
import { deleteTagHandler } from './DeleteTag';
@@ -25,6 +26,7 @@ import { listLabelsHandler } from './ListLabels';
import { listTagsHandler } from './ListTags';
import { listTeamMembersHandler } from './ListTeamMembers';
import { loadToolsHandler } from './LoadTools';
+import { moveToProjectHandler } from './MoveToProject';
import {
listNotificationsHandler,
markNotificationsDoneHandler,
@@ -44,6 +46,7 @@ import {
import { readChatHandler } from './ReadChat';
import { readContentHandler } from './ReadContent';
import { readMetadataHandler } from './ReadMetadata';
+import { readProjectHandler } from './ReadProject';
import { readThreadHandler } from './ReadThread';
import { renameDocumentHandler } from './RenameDocument';
import { contentSearchHandler, nameSearchHandler } from './Search';
@@ -81,10 +84,12 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
LoadTools: loadToolsHandler,
MarkNotificationsDone: markNotificationsDoneHandler,
MarkNotificationsSeen: markNotificationsSeenHandler,
+ MoveToProject: moveToProjectHandler,
BashCodeExecution: bashCodeExecutionHandler,
DisplayResults: displayResultsHandler,
ContentSearch: contentSearchHandler,
CreateDocument: createDocumentHandler,
+ CreateProject: createProjectHandler,
CreateTag: createTagHandler,
DeleteTag: deleteTagHandler,
EditDocument: editDocumentHandler,
@@ -99,6 +104,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ReadThread: readThreadHandler,
ReadContent: readContentHandler,
ReadMetadata: readMetadataHandler,
+ ReadProject: readProjectHandler,
RenameDocument: renameDocumentHandler,
SearchTools: searchToolsHandler,
SelfKnowledge: selfKnowledgeHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index b70cab7ad0..2a0f9dc9cb 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -647,6 +647,7 @@ export const CreateDocument = z.object({
fileContent: z.string(),
fileExtension: z.string(),
isTask: z.boolean().optional(),
+ projectId: z.union([z.string().uuid(), z.null()]).optional(),
});
export const CreateDocumentResponse = z.object({
@@ -757,6 +758,16 @@ export const CreateImportEntityResponse = z.object({
outcome: z.string(),
});
+export const CreateProject = z.object({
+ parentProjectId: z.union([z.string().uuid(), z.null()]).optional(),
+ projectName: z.string(),
+});
+
+export const CreateProjectResponse = z.object({
+ projectId: z.string().uuid(),
+ projectName: z.string(),
+});
+
export const CreateTag = z.object({
color: z.any().superRefine((x, ctx) => {
const schemas = [
@@ -1796,6 +1807,39 @@ export const MarkNotificationsSeen = z.object({
notificationIds: z.array(z.string().uuid()),
});
+export const MoveToProject = z.object({
+ entityId: z.string().uuid(),
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('email'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ projectId: z.union([z.string().uuid(), z.null()]).optional(),
+});
+
+export const MoveToProjectResponse = z.object({
+ message: z.string(),
+ success: z.boolean(),
+});
+
export const NameSearch = z.object({
entityTypes: z
.array(
@@ -2945,6 +2989,46 @@ export const ReadMetadataResponse = z.object({
userAccessLevel: z.enum(['view', 'comment', 'edit', 'owner']),
});
+export const ReadProject = z.object({ projectId: z.string().uuid() });
+
+export const ReadProjectResponse = z.object({
+ items: z.array(
+ z.object({
+ fileType: z.union([z.string(), z.null()]).optional(),
+ id: z.string(),
+ itemType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ ];
+ 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',
+ });
+ }
+ }),
+ name: z.string(),
+ updatedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ })
+ ),
+ parentProjectId: z.union([z.string(), z.null()]).optional(),
+ projectId: z.string().uuid(),
+ projectName: z.string(),
+});
+
export const RenameDocument = z.object({
documentId: z.string().uuid(),
documentName: z.string(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 03fd452409..eead264678 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -28,6 +28,10 @@ type ToolParserMap = {
call: types.CreateImportEntity;
response: types.CreateImportEntityResponse;
};
+ CreateProject: {
+ call: types.CreateProject;
+ response: types.CreateProjectResponse;
+ };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
DeleteImportEntity: {
call: types.DeleteImportEntity;
@@ -85,6 +89,10 @@ type ToolParserMap = {
call: types.MarkNotificationsSeen;
response: types.MarkNotificationsResponse;
};
+ MoveToProject: {
+ call: types.MoveToProject;
+ response: types.MoveToProjectResponse;
+ };
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
ReadCallRecord: {
call: types.ReadCallRecord;
@@ -108,6 +116,7 @@ type ToolParserMap = {
call: types.ReadMetadata;
response: types.ReadMetadataResponse;
};
+ ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };
ReadThread: { call: types.ReadThread; response: types.ReadResponse };
RenameDocument: {
call: types.RenameDocument;
@@ -161,6 +170,10 @@ const toolParserMap = {
call: schemas.CreateImportEntity,
response: schemas.CreateImportEntityResponse,
},
+ CreateProject: {
+ call: schemas.CreateProject,
+ response: schemas.CreateProjectResponse,
+ },
CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },
DeleteImportEntity: {
call: schemas.DeleteImportEntity,
@@ -227,6 +240,10 @@ const toolParserMap = {
call: schemas.MarkNotificationsSeen,
response: schemas.MarkNotificationsResponse,
},
+ MoveToProject: {
+ call: schemas.MoveToProject,
+ response: schemas.MoveToProjectResponse,
+ },
NameSearch: {
call: schemas.NameSearch,
response: schemas.SearchToolResponse,
@@ -256,6 +273,10 @@ const toolParserMap = {
call: schemas.ReadMetadata,
response: schemas.ReadMetadataResponse,
},
+ ReadProject: {
+ call: schemas.ReadProject,
+ response: schemas.ReadProjectResponse,
+ },
ReadThread: { call: schemas.ReadThread, response: schemas.ReadResponse },
RenameDocument: {
call: schemas.RenameDocument,
@@ -320,6 +341,10 @@ type ToolDataMap = {
call: types.CreateImportEntity;
response: types.CreateImportEntityResponse;
};
+ CreateProject: {
+ call: types.CreateProject;
+ response: types.CreateProjectResponse;
+ };
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
DeleteImportEntity: {
call: types.DeleteImportEntity;
@@ -377,6 +402,10 @@ type ToolDataMap = {
call: types.MarkNotificationsSeen;
response: types.MarkNotificationsResponse;
};
+ MoveToProject: {
+ call: types.MoveToProject;
+ response: types.MoveToProjectResponse;
+ };
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
ReadCallRecord: {
call: types.ReadCallRecord;
@@ -400,6 +429,7 @@ type ToolDataMap = {
call: types.ReadMetadata;
response: types.ReadMetadataResponse;
};
+ ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };
ReadThread: { call: types.ReadThread; response: types.ReadResponse };
RenameDocument: {
call: types.RenameDocument;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index f4957d57dd..b9914fe89d 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -400,10 +400,18 @@ export type NotificationItemType =
| 'call'
| 'task'
| 'github';
+/**
+ * The kind of entity to move.
+ */
+export type MoveableEntityType = 'document' | 'chat' | 'email' | 'project';
/**
* Direction for reading more messages around a cursor.
*/
export type PageDirection = 'older' | 'newer';
+/**
+ * The kind of an item inside a project.
+ */
+export type ProjectItemType = 'document' | 'chat' | 'project';
/**
* Position of a channel message.
*/
@@ -1228,6 +1236,10 @@ export interface CreateDocument {
* Whether this document is a task. Only applies to md documents.
*/
isTask?: boolean;
+ /**
+ * The id of the project (shown as a folder in the app UI) to create the document in. Requires edit access to the project. Omit to create the document at the top level of the user's files.
+ */
+ projectId?: string | null;
}
/**
* The read content response
@@ -1306,6 +1318,32 @@ export interface ImportEntityView {
source: ImportSource;
status: ImportStatus;
}
+/**
+ * Create a project — shown as a folder in the app UI. Documents, AI chats, email threads, and other projects can be placed inside it.
+ */
+export interface CreateProject {
+ /**
+ * The id of an existing project to nest the new project inside. Requires edit access to that project. Omit to create the project at the top level.
+ */
+ parentProjectId?: string | null;
+ /**
+ * The name of the project.
+ */
+ projectName: string;
+}
+/**
+ * The create project response.
+ */
+export interface CreateProjectResponse {
+ /**
+ * The id of the created project.
+ */
+ projectId: string;
+ /**
+ * The name of the created project.
+ */
+ projectName: string;
+}
/**
* Create a new tag — a colored label the user can apply to documents, emails, tasks, AI chats, and projects — in the user's personal set or their team's shared set. The set is provisioned automatically the first time a tag is created. Tags are matched by label, so call ListTags first and avoid creating one whose label duplicates an existing tag in the same set. Returns the new tag's id and its set's propertyDefinitionId, which you can pass straight to SetEntityProperty (add_option_ids) to apply the tag to an item. Use this only to create a brand-new tag; to apply an existing tag to an item, use ListTags then SetEntityProperty instead.
*/
@@ -2525,6 +2563,33 @@ export interface MarkNotificationsSeen {
*/
notificationIds: string[];
}
+/**
+ * Move a document, AI chat, email thread, or project into another project (projects are shown as folders in the app UI), or move it out to the top level. Requires edit access to the destination project. Moving a document or email thread requires edit access to it; moving an AI chat or a project requires owning it.
+ */
+export interface MoveToProject {
+ /**
+ * The id of the entity to move.
+ */
+ entityId: string;
+ entityType: MoveableEntityType;
+ /**
+ * The id of the destination project. Omit to move the entity out of its current project to the top level.
+ */
+ projectId?: string | null;
+}
+/**
+ * The move to project response.
+ */
+export interface MoveToProjectResponse {
+ /**
+ * A human-readable result message.
+ */
+ message: string;
+ /**
+ * Whether the move succeeded.
+ */
+ success: boolean;
+}
/**
* Search items by their name or title: document name, email subject, chat title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).
*/
@@ -2548,6 +2613,28 @@ export interface NameSearch {
tags?: TagFilter[] | null;
tagsMatch?: TagMatch;
}
+/**
+ * A single item inside a project.
+ */
+export interface ProjectItem {
+ /**
+ * The file type, for documents (e.g. md, pdf, docx).
+ */
+ fileType?: string | null;
+ /**
+ * The id of the item.
+ */
+ id: string;
+ itemType: ProjectItemType;
+ /**
+ * The display name of the item.
+ */
+ name: string;
+ /**
+ * When the item was last updated.
+ */
+ updatedAt?: string | null;
+}
/**
* Metadata for a project fetched from the database
*/
@@ -3289,6 +3376,36 @@ export interface ReadMetadataResponse {
documentMetadata: ReadDocumentMetadata;
userAccessLevel: AccessLevel;
}
+/**
+ * List the direct contents of a project (shown as a folder in the app UI): its documents, AI chats, and nested projects. Requires view access to the project. Email threads filed into the project are not included.
+ */
+export interface ReadProject {
+ /**
+ * The id of the project to read.
+ */
+ projectId: string;
+}
+/**
+ * The read project response.
+ */
+export interface ReadProjectResponse {
+ /**
+ * The project's direct children in display order.
+ */
+ items: ProjectItem[];
+ /**
+ * The id of the parent project, if this project is nested.
+ */
+ parentProjectId?: string | null;
+ /**
+ * The id of the project.
+ */
+ projectId: string;
+ /**
+ * The name of the project.
+ */
+ projectName: string;
+}
export interface ReadResponse {
content: ReadThreadReadContent;
}
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 8e840e7fba..311f3dd15a 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -71,6 +71,7 @@ schemars.workspace = true
search_service_client = { path = "../search_service_client" }
serde.workspace = true
serde_json.workspace = true
+projects = { path = "../projects", default-features = false, features = ["ai_tools", "outbound", "service"] }
properties = { path = "../properties", features = ["ai_tools"] }
soup = { path = "../soup", features = ["ai_tools", "outbound"] }
sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 496d5fd75b..1e996e7df6 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -310,20 +310,21 @@ pub async fn build_tool_service_context_from_env(
entity_access_service.clone(),
);
+ let user_email_service = Arc::new(
+ EmailServiceImpl::new(
+ EmailPgRepo::new(pool.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
+ sqs_client,
+ crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
+ 0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone()),
+ );
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
- Arc::new(
- EmailServiceImpl::new(
- EmailPgRepo::new(pool.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
- sqs_client,
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- 0,
- )
- .with_macro_event_broker(macro_event_broker.clone()),
- ),
+ user_email_service.clone(),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
pool.clone(),
@@ -372,6 +373,15 @@ pub async fn build_tool_service_context_from_env(
(*entity_access_service).clone(),
);
+ let project_tool_context = crate::tool_context::build_project_tool_context(
+ pool.clone(),
+ macro_event_broker.clone(),
+ entity_access_service.clone(),
+ document_tool_context.service.clone(),
+ chat_tool_context.service.clone(),
+ user_email_service,
+ );
+
let anthropic_tool_context = build_anthropic_tool_context();
Ok(ToolServiceContext {
@@ -387,6 +397,7 @@ pub async fn build_tool_service_context_from_env(
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
channel_tool_context,
+ project_tool_context,
team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),
crm_tool_context: crate::tool_context::build_crm_tool_context(pool.clone()),
schedule_tool_context: crate::NoOpScheduleContext,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 4eab9ad061..470a5ff6bc 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -27,6 +27,7 @@ use documents::inbound::toolset::document_toolset;
use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};
use import::inbound::toolset::import_toolset;
use notification::inbound::ai_tool::notification_toolset;
+use projects::inbound::toolset::project_toolset;
use properties::inbound::toolset::properties_toolset;
use schemas::read;
use search_tools::{LoadTools, SearchTools};
@@ -52,11 +53,12 @@ pub use tool_context::{
ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolImportService,
ToolImportToolContext, ToolNotificationQueue, ToolNotificationService,
- ToolNotificationToolContext, ToolPropertiesService, ToolPropertiesToolContext,
- ToolServiceContext, ToolSoupService, ToolSystemPropertiesService, ToolTeamService,
- ToolTeamToolContext, ToolUserEmailService, build_channel_tool_context_with_dispatcher,
- build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
- build_crm_tool_context, build_properties_service, build_properties_tool_context,
+ ToolNotificationToolContext, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,
+ ToolPropertiesToolContext, ToolServiceContext, ToolSoupService, ToolSystemPropertiesService,
+ ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
+ build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,
+ build_channel_tool_context_without_side_effects, build_crm_tool_context,
+ build_project_tool_context, build_properties_service, build_properties_tool_context,
build_task_properties_adapter, build_team_repository, build_team_tool_context,
};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
@@ -83,6 +85,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
.add_tool::<SelfKnowledge, ToolServiceContext>()
.add_tool::<ListEntities, SoupToolContext<ToolSoupService, ToolEmailService>>()
.add_subtoolset::<ToolDocumentToolContext>(document_toolset())
+ .add_subtoolset::<ToolProjectToolContext>(project_toolset())
.add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
.add_subtoolset::<ToolCallToolContext>(call_toolset())
.add_subtoolset::<ToolChatToolContext>(chat_toolset())
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index bc967bca90..c1e354620e 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -38,6 +38,7 @@ use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use macro_user_id::user_id::MacroUserIdStr;
use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
+use projects::inbound::toolset::ProjectToolContext;
use properties::inbound::toolset::PropertiesToolContext;
use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
use std::sync::Arc;
@@ -711,6 +712,63 @@ pub type ToolNotificationToolContext = NotificationToolContext<ToolNotificationS
/// Uses an empty toolset — the read-only tool never invokes tool execution.
pub type ToolChatService = ChatServiceImpl<PgChatRepo, (), ToolEntityAccessManagementService>;
+/// Type alias for the project service implementation used by AI tools.
+/// Upload, content-hash, and search-cleanup ports are unwired — project
+/// tools only create, read, and move projects, never run upload or purge
+/// flows.
+pub type ToolProjectService = projects::domain::service::ProjectServiceImpl<
+ projects::outbound::PgProjectRepo,
+ projects::domain::ports::UnavailableProjectUploadUrlPort,
+ projects::domain::ports::UnavailableBulkUploadRequestPort,
+ projects::domain::ports::UnavailableShaCounterPort,
+ ToolEntityAccessManagementService,
+ projects::domain::ports::UnavailableProjectSearchIndexer,
+ ToolEventBroker,
+>;
+
+/// Type alias for the project tool context. Move dispatch uses the same
+/// domain services the other tool contexts run on, so moves fire the same
+/// events and side effects as the REST/GraphQL paths.
+pub type ToolProjectToolContext = ProjectToolContext<
+ ToolProjectService,
+ ToolEntityAccessService,
+ ToolDocumentService,
+ ToolChatService,
+ ToolUserEmailService,
+>;
+
+/// Build the project tool context from shared domain and access services.
+/// The move services must be the same instances the document, chat, and
+/// email tool contexts run on so moves share their side-effect wiring.
+pub fn build_project_tool_context(
+ pool: sqlx::PgPool,
+ macro_event_broker: ToolEventBroker,
+ entity_access_service: Arc<ToolEntityAccessService>,
+ document_service: Arc<ToolDocumentService>,
+ chat_service: Arc<ToolChatService>,
+ email_service: Arc<ToolUserEmailService>,
+) -> ToolProjectToolContext {
+ let project_service = projects::domain::service::ProjectServiceImpl::new(
+ projects::outbound::PgProjectRepo::new(pool.clone()),
+ projects::domain::ports::UnavailableProjectUploadUrlPort,
+ projects::domain::ports::UnavailableBulkUploadRequestPort,
+ projects::domain::ports::UnavailableShaCounterPort,
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool),
+ ),
+ projects::domain::ports::UnavailableProjectSearchIndexer,
+ None,
+ macro_event_broker,
+ );
+ ProjectToolContext::new(
+ Arc::new(project_service),
+ entity_access_service,
+ document_service,
+ chat_service,
+ email_service,
+ )
+}
+
/// Type alias for the chat tool context
pub type ToolChatToolContext = ChatToolContext<ToolChatService, ToolEntityAccessService>;
@@ -1046,6 +1104,7 @@ pub struct ToolServiceContext {
#[from_ref(skip)]
pub chat_tool_context: ToolChatToolContext,
pub channel_tool_context: ToolChannelToolContext,
+ pub project_tool_context: ToolProjectToolContext,
pub team_tool_context: ToolTeamToolContext,
pub crm_tool_context: ToolCrmToolContext,
pub schedule_tool_context: NoOpScheduleContext,
diff --git a/crates/documents/src/inbound/toolset/create_document.rs b/crates/documents/src/inbound/toolset/create_document.rs
index 6a897600b5..bafa7ab449 100644
--- a/crates/documents/src/inbound/toolset/create_document.rs
+++ b/crates/documents/src/inbound/toolset/create_document.rs
@@ -10,6 +10,7 @@ use crate::domain::ports::editing::EditingWorkerService;
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use anyhow::Context;
use async_trait::async_trait;
+use entity_access::domain::models::{EditAccessLevel, EntityType};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::FileType;
@@ -57,6 +58,12 @@ pub struct CreateDocument {
#[schemars(description = "Whether this document is a task. Only applies to md documents.")]
#[serde(default)]
pub is_task: bool,
+
+ #[schemars(
+ description = "The id of the project (shown as a folder in the app UI) to create the document in. Requires edit access to the project. Omit to create the document at the top level of the user's files."
+ )]
+ #[serde(default)]
+ pub project_id: Option<uuid::Uuid>,
}
#[async_trait]
@@ -82,6 +89,25 @@ where
})?;
let user_id: MacroUserIdStr<'static> = request_context.user_id.clone();
+ // Mirrors the axum create route's project body extractor: creating
+ // inside a project requires edit access to that project.
+ if let Some(project_id) = self.project_id {
+ service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &user_id,
+ None,
+ &project_id.to_string(),
+ EntityType::Project,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "you need edit access to the target project, or it does not exist"
+ .to_string(),
+ internal_error: e.into(),
+ })?;
+ }
+
// gets the members team if exists so we can track the task number correctly
let maybe_team = if self.is_task {
service_context
@@ -97,13 +123,17 @@ where
None
};
- let document =
- NewPlainTextDocument::builder(NewDocumentMetadata::new(self.document_name.clone()))
- .file_type(parsed_file_type)
- .text(self.file_content.clone())
- .task_flag(self.is_task, maybe_team)
- .build()
- .map_err(failed_to_create_document)?;
+ let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone());
+ if let Some(project_id) = self.project_id {
+ metadata_builder = metadata_builder.project_id(project_id);
+ }
+
+ let document = NewPlainTextDocument::builder(metadata_builder.build())
+ .file_type(parsed_file_type)
+ .text(self.file_content.clone())
+ .task_flag(self.is_task, maybe_team)
+ .build()
+ .map_err(failed_to_create_document)?;
let response = service_context
.creator
diff --git a/crates/projects/Cargo.toml b/crates/projects/Cargo.toml
index 96263f337b..84fefa1e3b 100644
--- a/crates/projects/Cargo.toml
+++ b/crates/projects/Cargo.toml
@@ -5,6 +5,12 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai_toolset",
+ "dep:async-trait",
+ "dep:schemars",
+ "ports",
+]
axum = [
"dep:axum",
"dep:axum-extra",
@@ -68,6 +74,11 @@ s3_key = { path = "../s3_key" }
# Async runtime (for ports)
tokio = { workspace = true, optional = true }
+# AI toolset dependencies
+ai_toolset = { path = "../ai_toolset", optional = true }
+async-trait = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
+
# Axum dependencies
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
diff --git a/crates/projects/src/domain/ports.rs b/crates/projects/src/domain/ports.rs
index 6031b00a16..bdbfa364f9 100644
--- a/crates/projects/src/domain/ports.rs
+++ b/crates/projects/src/domain/ports.rs
@@ -222,6 +222,100 @@ pub trait ProjectSearchIndexer: Send + Sync + 'static {
) -> impl Future<Output = anyhow::Result<()>> + Send;
}
+/// Unwired upload-URL port for hosts that expose project operations without
+/// upload flows (e.g. AI tools). Upload methods fail loudly if reached.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UnavailableProjectUploadUrlPort;
+
+impl ProjectUploadUrlPort for UnavailableProjectUploadUrlPort {
+ async fn put_upload_zip_staging_presigned_url(
+ &self,
+ _key: BulkUploadStagingKey,
+ _sha: String,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("project upload URLs are not available in this host")
+ }
+
+ async fn put_document_storage_presigned_url(
+ &self,
+ _key: String,
+ _sha: String,
+ _content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("project upload URLs are not available in this host")
+ }
+
+ async fn put_docx_upload_presigned_url(
+ &self,
+ _key: String,
+ _sha: String,
+ _content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("project upload URLs are not available in this host")
+ }
+
+ fn document_storage_bucket(&self) -> &str {
+ ""
+ }
+
+ fn docx_upload_bucket(&self) -> &str {
+ ""
+ }
+}
+
+/// Unwired bulk-upload port for hosts that expose project operations without
+/// upload flows (e.g. AI tools). Methods fail loudly if reached.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UnavailableBulkUploadRequestPort;
+
+impl BulkUploadRequestPort for UnavailableBulkUploadRequestPort {
+ async fn create_bulk_upload_request(
+ &self,
+ _request_id: Uuid,
+ _user_id: &str,
+ _name: Option<&str>,
+ _parent_id: Option<&str>,
+ ) -> anyhow::Result<BulkUploadRequest> {
+ anyhow::bail!("bulk-upload requests are not available in this host")
+ }
+
+ async fn get_bulk_upload_document_statuses(
+ &self,
+ _upload_request_id: &str,
+ ) -> anyhow::Result<BulkUploadRequestDocuments> {
+ anyhow::bail!("bulk-upload requests are not available in this host")
+ }
+}
+
+/// Unwired content-hash counter for hosts that expose project operations
+/// without deletion flows (e.g. AI tools). Fails loudly if reached.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UnavailableShaCounterPort;
+
+impl ShaCounterPort for UnavailableShaCounterPort {
+ async fn decrement_counts(&self, _sha_counts: &[(String, i64)]) -> anyhow::Result<()> {
+ anyhow::bail!("content-hash counting is not available in this host")
+ }
+}
+
+/// Unwired search indexer for hosts that expose project operations without
+/// deletion flows (e.g. AI tools). Methods fail loudly if reached.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UnavailableProjectSearchIndexer;
+
+impl ProjectSearchIndexer for UnavailableProjectSearchIndexer {
+ async fn remove_documents(&self, _document_ids: Vec<String>) -> anyhow::Result<()> {
+ anyhow::bail!("project search indexing is not available in this host")
+ }
+
+ async fn enqueue_document_deletes(
+ &self,
+ _documents: Vec<(String, String)>,
+ ) -> anyhow::Result<()> {
+ anyhow::bail!("project search indexing is not available in this host")
+ }
+}
+
/// Inbound-facing service interface for project operations.
pub trait ProjectService: Send + Sync + 'static {
/// List projects visible through the user's project history.
diff --git a/crates/projects/src/inbound.rs b/crates/projects/src/inbound.rs
index 2b34e4c682..775fae40e7 100644
--- a/crates/projects/src/inbound.rs
+++ b/crates/projects/src/inbound.rs
@@ -5,3 +5,7 @@
/// Axum project route adapter.
#[cfg(feature = "axum")]
pub mod axum_router;
+
+/// AI toolset adapter.
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/crates/projects/src/inbound/toolset/create_project.rs b/crates/projects/src/inbound/toolset/create_project.rs
new file mode 100644
index 0000000000..e444acc3ff
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/create_project.rs
@@ -0,0 +1,130 @@
+//! CreateProject tool for creating projects (folders).
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use anyhow::Context;
+use async_trait::async_trait;
+use entity_access::domain::models::EditAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::MoveEntity;
+use model::project::request::CreateProjectRequest;
+use model_entity::EntityType;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::ProjectToolContext;
+use crate::domain::models::ProjectError;
+use crate::domain::ports::ProjectService;
+
+fn failed_to_create_project(error: ProjectError) -> ToolCallError {
+ let description = match &error {
+ ProjectError::BadRequest(message) => message.clone(),
+ ProjectError::NameTooLong { max } => {
+ format!("name too long (max {max} characters)")
+ }
+ _ => "failed to create project".to_string(),
+ };
+
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
+/// The create project response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateProjectResponse {
+ /// The id of the created project.
+ pub project_id: uuid::Uuid,
+ /// The name of the created project.
+ pub project_name: String,
+}
+
+/// CreateProject tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateProject",
+ description = "Create a project — shown as a folder in the app UI. Documents, AI chats, email threads, and other projects can be placed inside it."
+)]
+pub struct CreateProject {
+ /// The name of the project.
+ #[schemars(description = "The name of the project.")]
+ pub project_name: String,
+
+ /// The project to nest the new project inside.
+ #[schemars(
+ description = "The id of an existing project to nest the new project inside. Requires edit access to that project. Omit to create the project at the top level."
+ )]
+ #[serde(default)]
+ pub parent_project_id: Option<uuid::Uuid>,
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for CreateProject
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = CreateProjectResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Create project");
+
+ let user_id = request_context.user_id.clone();
+
+ // Mirrors the axum route's ProjectBodyAccessLevelExtractorV2: creating
+ // inside a parent requires edit access to that parent.
+ if let Some(parent_id) = self.parent_project_id {
+ service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &user_id,
+ None,
+ &parent_id.to_string(),
+ EntityType::Project,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "you need edit access to the parent project, or it does not exist"
+ .to_string(),
+ internal_error: e.into(),
+ })?;
+ }
+
+ let project = service_context
+ .service
+ .create_project(
+ user_id,
+ CreateProjectRequest {
+ name: self.project_name.clone(),
+ project_parent_id: self.parent_project_id,
+ },
+ )
+ .await
+ .map_err(failed_to_create_project)?;
+
+ let project_id = project
+ .id
+ .parse()
+ .context("expected valid uuid")
+ .map_err(|e| ToolCallError {
+ description: format!("invalid project id was output {}", project.id),
+ internal_error: e,
+ })?;
+
+ Ok(CreateProjectResponse {
+ project_id,
+ project_name: project.name,
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/mod.rs b/crates/projects/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..be54529d22
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/mod.rs
@@ -0,0 +1,106 @@
+//! Toolset inbound adapter for projects.
+
+mod create_project;
+mod move_to_project;
+mod read_project;
+
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use ai_toolset::AsyncToolCollection;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::MoveEntity;
+
+use crate::domain::ports::ProjectService;
+
+pub use create_project::{CreateProject, CreateProjectResponse};
+pub use move_to_project::{MoveToProject, MoveToProjectResponse, MoveableEntityType};
+pub use read_project::{ProjectItem, ProjectItemType, ReadProject, ReadProjectResponse};
+
+/// Service context for project AI tools.
+///
+/// The move services are the per-domain [`MoveEntity`] capability impls the
+/// `MoveToProject` tool dispatches to, mirroring the DSS entity-mutation
+/// router.
+pub struct ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ /// The project service instance.
+ pub service: Arc<PSvc>,
+ /// The entity access service — used to mint access receipts.
+ pub entity_access_service: Arc<ESvc>,
+ /// Move capability for documents.
+ pub document_move_service: Arc<DSvc>,
+ /// Move capability for AI chats.
+ pub chat_move_service: Arc<CSvc>,
+ /// Move capability for email threads.
+ pub email_move_service: Arc<EmSvc>,
+}
+
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> Clone for ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ document_move_service: self.document_move_service.clone(),
+ chat_move_service: self.chat_move_service.clone(),
+ email_move_service: self.email_move_service.clone(),
+ }
+ }
+}
+
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ /// Create a new project tool context.
+ pub fn new(
+ service: Arc<PSvc>,
+ entity_access_service: Arc<ESvc>,
+ document_move_service: Arc<DSvc>,
+ chat_move_service: Arc<CSvc>,
+ email_move_service: Arc<EmSvc>,
+ ) -> Self {
+ Self {
+ service,
+ entity_access_service,
+ document_move_service,
+ chat_move_service,
+ email_move_service,
+ }
+ }
+}
+
+/// Create a project toolset.
+pub fn project_toolset<PSvc, ESvc, DSvc, CSvc, EmSvc>()
+-> AsyncToolCollection<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ AsyncToolCollection::new()
+ .add_tool::<CreateProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<ReadProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+ .add_tool::<MoveToProject, ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>()
+}
diff --git a/crates/projects/src/inbound/toolset/move_to_project.rs b/crates/projects/src/inbound/toolset/move_to_project.rs
new file mode 100644
index 0000000000..6a358d7ac3
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/move_to_project.rs
@@ -0,0 +1,244 @@
+//! MoveToProject tool for moving entities into and out of projects (folders).
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::models::EditAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::{EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::ProjectToolContext;
+use crate::domain::ports::ProjectService;
+
+/// The kind of entity to move.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum MoveableEntityType {
+ /// A document (includes tasks).
+ #[default]
+ Document,
+ /// An AI chat conversation.
+ Chat,
+ /// An email thread.
+ Email,
+ /// A project (folder) nested into another project.
+ Project,
+}
+
+impl MoveableEntityType {
+ fn entity_type(self) -> EntityType {
+ match self {
+ Self::Document => EntityType::Document,
+ Self::Chat => EntityType::Chat,
+ Self::Email => EntityType::EmailThread,
+ Self::Project => EntityType::Project,
+ }
+ }
+}
+
+fn entity_access_failed(error: entity_access::domain::models::AccessError) -> ToolCallError {
+ ToolCallError {
+ description:
+ "you do not have the access required to move this entity, or it does not exist"
+ .to_string(),
+ internal_error: error.into(),
+ }
+}
+
+fn project_access_failed(error: entity_access::domain::models::AccessError) -> ToolCallError {
+ ToolCallError {
+ description: "you do not have edit access to the destination project, or it does not exist"
+ .to_string(),
+ internal_error: error.into(),
+ }
+}
+
+fn move_failed(code: EntityMutationErrorCode) -> ToolCallError {
+ let description = match code {
+ EntityMutationErrorCode::Forbidden(_) => {
+ "you lack the required access: moving an AI chat or project requires owning it, moving a document or email thread requires edit access, and the destination project requires edit access"
+ }
+ EntityMutationErrorCode::NotFound(_) => "the entity or destination project was not found",
+ EntityMutationErrorCode::Conflict(_) => {
+ "the entity cannot be moved in its current state (it may be deleted)"
+ }
+ EntityMutationErrorCode::InvalidInput(_) => {
+ "invalid move: a project cannot be moved into itself or one of its descendants"
+ }
+ EntityMutationErrorCode::UnsupportedOperation(_) => "this entity kind cannot be moved",
+ EntityMutationErrorCode::Internal(_) => "failed to move the entity",
+ };
+
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::anyhow!("move entity failed: {code:?}"),
+ }
+}
+
+/// Mint the receipts a domain's move capability requires and dispatch to it,
+/// mirroring the DSS entity-mutation router.
+async fn move_with<S, ESvc>(
+ service: &S,
+ entity_access_service: &ESvc,
+ user_id: &MacroUserIdStr<'static>,
+ entity: Entity<'static>,
+ project_id: Option<String>,
+) -> Result<(), ToolCallError>
+where
+ S: MoveEntity,
+ ESvc: EntityAccessService,
+{
+ let receipt = entity_access_service
+ .generate_entity_access_receipt::<S::Receipt>(
+ user_id,
+ None,
+ &entity.entity_id,
+ entity.entity_type,
+ )
+ .await
+ .map_err(entity_access_failed)?;
+
+ let request = match project_id {
+ Some(project_id) => {
+ let project_receipt = entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ user_id,
+ None,
+ &project_id,
+ EntityType::Project,
+ )
+ .await
+ .map_err(project_access_failed)?;
+ MoveEntityRequest::MoveToProject {
+ entity,
+ receipt,
+ project_id,
+ project_receipt,
+ }
+ }
+ None => MoveEntityRequest::MoveToRoot { entity, receipt },
+ };
+
+ service.move_entity(request).await.map_err(move_failed)?;
+ Ok(())
+}
+
+/// The move to project response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct MoveToProjectResponse {
+ /// Whether the move succeeded.
+ pub success: bool,
+ /// A human-readable result message.
+ pub message: String,
+}
+
+/// MoveToProject tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "MoveToProject",
+ description = "Move a document, AI chat, email thread, or project into another project (projects are shown as folders in the app UI), or move it out to the top level. Requires edit access to the destination project. Moving a document or email thread requires edit access to it; moving an AI chat or a project requires owning it."
+)]
+pub struct MoveToProject {
+ /// The kind of entity to move.
+ #[schemars(description = "The kind of entity to move.")]
+ pub entity_type: MoveableEntityType,
+
+ /// The id of the entity to move.
+ #[schemars(description = "The id of the entity to move.")]
+ pub entity_id: uuid::Uuid,
+
+ /// The destination project, or `None` for the top level.
+ #[schemars(
+ description = "The id of the destination project. Omit to move the entity out of its current project to the top level."
+ )]
+ #[serde(default)]
+ pub project_id: Option<uuid::Uuid>,
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for MoveToProject
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = MoveToProjectResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_type=?self.entity_type, entity_id=?self.entity_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Move to project");
+
+ let user_id = request_context.user_id.clone();
+ let entity = self
+ .entity_type
+ .entity_type()
+ .with_entity_string(self.entity_id.to_string());
+ let project_id = self.project_id.map(|id| id.to_string());
+
+ let entity_access_service = &*service_context.entity_access_service;
+ match self.entity_type {
+ MoveableEntityType::Document => {
+ move_with(
+ &*service_context.document_move_service,
+ entity_access_service,
+ &user_id,
+ entity,
+ project_id,
+ )
+ .await?
+ }
+ MoveableEntityType::Chat => {
+ move_with(
+ &*service_context.chat_move_service,
+ entity_access_service,
+ &user_id,
+ entity,
+ project_id,
+ )
+ .await?
+ }
+ MoveableEntityType::Email => {
+ move_with(
+ &*service_context.email_move_service,
+ entity_access_service,
+ &user_id,
+ entity,
+ project_id,
+ )
+ .await?
+ }
+ MoveableEntityType::Project => {
+ move_with(
+ &*service_context.service,
+ entity_access_service,
+ &user_id,
+ entity,
+ project_id,
+ )
+ .await?
+ }
+ }
+
+ let message = match self.project_id {
+ Some(project_id) => format!("Moved to project {project_id}"),
+ None => "Moved out of its project to the top level".to_string(),
+ };
+
+ Ok(MoveToProjectResponse {
+ success: true,
+ message,
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/read_project.rs b/crates/projects/src/inbound/toolset/read_project.rs
new file mode 100644
index 0000000000..4d0a1ec0e2
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/read_project.rs
@@ -0,0 +1,175 @@
+//! ReadProject tool for listing a project's (folder's) contents.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::models::ViewAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use entity_mutation::MoveEntity;
+use model::item::Item;
+use model_entity::EntityType;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::ProjectToolContext;
+use crate::domain::ports::ProjectService;
+
+/// The kind of an item inside a project.
+#[derive(Debug, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ProjectItemType {
+ /// A document (includes tasks).
+ Document,
+ /// An AI chat conversation.
+ Chat,
+ /// A nested project.
+ Project,
+}
+
+/// A single item inside a project.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ProjectItem {
+ /// The id of the item.
+ pub id: String,
+ /// The kind of the item.
+ pub item_type: ProjectItemType,
+ /// The display name of the item.
+ pub name: String,
+ /// The file type, for documents (e.g. md, pdf, docx).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub file_type: Option<String>,
+ /// When the item was last updated.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl From<Item> for ProjectItem {
+ fn from(item: Item) -> Self {
+ match item {
+ Item::Document(document) => Self {
+ id: document.document_id,
+ item_type: ProjectItemType::Document,
+ name: document.document_name,
+ file_type: document.file_type,
+ updated_at: document.updated_at,
+ },
+ Item::Chat(chat) => Self {
+ id: chat.id,
+ item_type: ProjectItemType::Chat,
+ name: chat.name,
+ file_type: None,
+ updated_at: chat.updated_at,
+ },
+ Item::Project(project) => Self {
+ id: project.id,
+ item_type: ProjectItemType::Project,
+ name: project.name,
+ file_type: None,
+ updated_at: project.updated_at,
+ },
+ }
+ }
+}
+
+/// The read project response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadProjectResponse {
+ /// The id of the project.
+ pub project_id: uuid::Uuid,
+ /// The name of the project.
+ pub project_name: String,
+ /// The id of the parent project, if this project is nested.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub parent_project_id: Option<String>,
+ /// The project's direct children in display order.
+ pub items: Vec<ProjectItem>,
+}
+
+/// ReadProject tool input.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadProject",
+ description = "List the direct contents of a project (shown as a folder in the app UI): its documents, AI chats, and nested projects. Requires view access to the project. Email threads filed into the project are not included."
+)]
+pub struct ReadProject {
+ /// The id of the project to read.
+ #[schemars(description = "The id of the project to read.")]
+ pub project_id: uuid::Uuid,
+}
+
+#[async_trait]
+impl<PSvc, ESvc, DSvc, CSvc, EmSvc> AsyncTool<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>
+ for ReadProject
+where
+ PSvc: ProjectService + MoveEntity,
+ ESvc: EntityAccessService,
+ DSvc: MoveEntity + Send + Sync + 'static,
+ CSvc: MoveEntity + Send + Sync + 'static,
+ EmSvc: MoveEntity + Send + Sync + 'static,
+{
+ type Output = ReadProjectResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, project_id=?self.project_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Read project");
+
+ let project_id = self.project_id.to_string();
+
+ let entity_access_receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &request_context.user_id,
+ None,
+ &project_id,
+ EntityType::Project,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "you do not have access to this project, or it does not exist"
+ .to_string(),
+ internal_error: e.into(),
+ })?;
+
+ // SAFETY: This is allowed because the user has view access from the receipt above.
+ let project = service_context
+ .service
+ .internal_get_basic_project(&project_id)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get the project".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ if project.deleted_at.is_some() {
+ return Err(ToolCallError {
+ description: "cannot read a deleted project".to_string(),
+ internal_error: anyhow::anyhow!("project {project_id} is deleted"),
+ });
+ }
+
+ let items = service_context
+ .service
+ .get_project_content(entity_access_receipt)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to read the project's contents".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ Ok(ReadProjectResponse {
+ project_id: self.project_id,
+ project_name: project.name,
+ parent_project_id: project.parent_id,
+ items: items
+ .into_iter()
+ .map(|item| ProjectItem::from(item.item))
+ .collect(),
+ })
+ }
+}
diff --git a/crates/projects/src/inbound/toolset/test.rs b/crates/projects/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..9d11a613f3
--- /dev/null
+++ b/crates/projects/src/inbound/toolset/test.rs
@@ -0,0 +1,68 @@
+use super::*;
+use ai_toolset::schema::generate_validated_input_schema;
+
+#[test]
+fn test_create_project_schema_validation() {
+ let result = generate_validated_input_schema::<CreateProject>();
+ assert!(result.is_ok(), "{:?}", result);
+
+ let validated = result.unwrap();
+ assert_eq!(
+ validated.name, "CreateProject",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ validated.description.contains("Create"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_read_project_schema_validation() {
+ let result = generate_validated_input_schema::<ReadProject>();
+ assert!(result.is_ok(), "{:?}", result);
+
+ let validated = result.unwrap();
+ assert_eq!(
+ validated.name, "ReadProject",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ validated.description.contains("List"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_move_to_project_schema_validation() {
+ let result = generate_validated_input_schema::<MoveToProject>();
+ assert!(result.is_ok(), "{:?}", result);
+
+ let validated = result.unwrap();
+ assert_eq!(
+ validated.name, "MoveToProject",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ validated.description.contains("Move"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_move_to_project_deserializes_entity_types() {
+ for (raw, expected) in [
+ ("document", MoveableEntityType::Document),
+ ("chat", MoveableEntityType::Chat),
+ ("email", MoveableEntityType::Email),
+ ("project", MoveableEntityType::Project),
+ ] {
+ let tool: MoveToProject = serde_json::from_value(serde_json::json!({
+ "entityType": raw,
+ "entityId": "d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc",
+ }))
+ .expect("valid input");
+ assert_eq!(tool.entity_type, expected);
+ assert!(tool.project_id.is_none());
+ }
+}
diff --git a/crates/projects/src/lib.rs b/crates/projects/src/lib.rs
index aa54ea31f3..67c214ce5a 100644
--- a/crates/projects/src/lib.rs
+++ b/crates/projects/src/lib.rs
@@ -8,7 +8,7 @@
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
#[cfg(feature = "outbound")]
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index fb94e8760b..3ab5d10db4 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -296,22 +296,23 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access_service.clone(),
);
+ let user_email_service = Arc::new(
+ email::domain::service::EmailServiceImpl::new(
+ email::outbound::EmailPgRepo::new(pool.clone()),
+ frecency::domain::services::FrecencyQueryServiceImpl::new(
+ frecency::outbound::postgres::FrecencyPgStorage::new(pool.clone()),
+ ),
+ sqs_client.clone(),
+ crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(pool.clone()),
+ ),
+ 0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone()),
+ );
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
- Arc::new(
- email::domain::service::EmailServiceImpl::new(
- email::outbound::EmailPgRepo::new(pool.clone()),
- frecency::domain::services::FrecencyQueryServiceImpl::new(
- frecency::outbound::postgres::FrecencyPgStorage::new(pool.clone()),
- ),
- sqs_client.clone(),
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(pool.clone()),
- ),
- 0,
- )
- .with_macro_event_broker(macro_event_broker.clone()),
- ),
+ user_email_service.clone(),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
entity_access_service.clone(),
);
@@ -342,6 +343,15 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
(*entity_access_service).clone(),
);
+ let project_tool_context = ai_tools::build_project_tool_context(
+ pool.clone(),
+ macro_event_broker.clone(),
+ entity_access_service.clone(),
+ document_tool_context.service.clone(),
+ chat_tool_context.service.clone(),
+ user_email_service,
+ );
+
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
@@ -358,6 +368,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
pool.clone(),
std::sync::Arc::new(test_lexical_client),
),
+ project_tool_context,
team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),
schedule_tool_context: ai_tools::no_op_schedule_context(),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 406534e659..abedf4a074 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -375,20 +375,21 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized properties tool context");
+ let user_email_service = Arc::new(
+ EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ sqs_client.clone(),
+ crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
+ 0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone()),
+ );
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
- Arc::new(
- EmailServiceImpl::new(
- EmailPgRepo::new(db.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
- sqs_client.clone(),
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(db.clone()),
- ),
- 0,
- )
- .with_macro_event_broker(macro_event_broker.clone()),
- ),
+ user_email_service.clone(),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
db.clone(),
@@ -482,6 +483,15 @@ async fn main() -> anyhow::Result<()> {
// replicas, where a boot-time sweep would clobber other instances' jobs.
tracing::info!("initialized import service");
+ let project_tool_context = ai_tools::build_project_tool_context(
+ db.clone(),
+ macro_event_broker.clone(),
+ entity_access_service.clone(),
+ document_tool_context.service.clone(),
+ chat_tool_context.service.clone(),
+ user_email_service,
+ );
+
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
@@ -497,6 +507,7 @@ async fn main() -> anyhow::Result<()> {
),
chat_tool_context,
channel_tool_context,
+ project_tool_context,
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 86c5365809..da4f763292 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -275,20 +275,21 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
let properties_tool_context =
ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());
+ let user_email_service = Arc::new(
+ EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ sqs_client,
+ crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(db.clone()),
+ ),
+ 0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone()),
+ );
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
- Arc::new(
- EmailServiceImpl::new(
- EmailPgRepo::new(db.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
- sqs_client,
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(db.clone()),
- ),
- 0,
- )
- .with_macro_event_broker(macro_event_broker.clone()),
- ),
+ user_email_service.clone(),
Arc::new(email::domain::ports::NoOpGmailTokenProvider),
Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
db.clone(),
@@ -351,6 +352,15 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
},
);
+ let project_tool_context = ai_tools::build_project_tool_context(
+ db.clone(),
+ macro_event_broker.clone(),
+ entity_access_service.clone(),
+ document_tool_context.service.clone(),
+ chat_tool_context.service.clone(),
+ user_email_service,
+ );
+
let tool_context = ToolServiceContext {
email_service_client: Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
@@ -366,6 +376,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
channel_tool_context,
+ project_tool_context,
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),
schedule_tool_context: NoOpScheduleContext,