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): dss tools (#1801)

Eric Hayes7fedcf8b496f
diff --git a/infra/stacks/document-cognition-service/Pulumi.dev.yaml b/infra/stacks/document-cognition-service/Pulumi.dev.yaml
index 3d8a042a7d..7cfff4d829 100644
--- a/infra/stacks/document-cognition-service/Pulumi.dev.yaml
+++ b/infra/stacks/document-cognition-service/Pulumi.dev.yaml
@@ -15,3 +15,4 @@ config:
document-cognition:sync_service_auth_key: sync-service-key-dev
document-cognition:perplexity-api-key: perplexity-api-key
document-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-dev
+ datadog:validate: "false"
diff --git a/infra/stacks/document-cognition-service/document-cognition-service.ts b/infra/stacks/document-cognition-service/document-cognition-service.ts
index ea0bb3f089..b174001544 100644
--- a/infra/stacks/document-cognition-service/document-cognition-service.ts
+++ b/infra/stacks/document-cognition-service/document-cognition-service.ts
@@ -38,6 +38,7 @@ type CreateDocumentCognitionServiceArgs = {
tags: { [key: string]: string };
secretKeyArns: pulumi.Output<string>[] | string[];
queueArns: pulumi.Output<string>[] | string[];
+ bucketArns: (pulumi.Output<string> | string)[];
connectionTablePolicyArn: pulumi.Output<string> | string;
};
@@ -67,6 +68,7 @@ export class DocumentCognitionService extends pulumi.ComponentResource {
cloudStorageClusterName,
secretKeyArns,
queueArns,
+ bucketArns,
connectionTablePolicyArn,
tags,
}: CreateDocumentCognitionServiceArgs,
@@ -163,6 +165,33 @@ export class DocumentCognitionService extends pulumi.ComponentResource {
{ parent: this }
);
+ const s3Policy = new aws.iam.Policy(
+ `${BASE_NAME}-s3-bucket-policy`,
+ {
+ name: `${BASE_NAME}-s3-bucket-policy-${stack}`,
+ policy: {
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: [
+ 's3:ListBucket',
+ 's3:GetObject',
+ 's3:PutObject',
+ 's3:DeleteObject',
+ ],
+ Resource: bucketArns.flatMap((arn) => [
+ arn,
+ pulumi.interpolate`${arn}/*`,
+ ]),
+ Effect: 'Allow',
+ },
+ ],
+ },
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
this.role = new aws.iam.Role(
`${BASE_NAME}-role`,
{
@@ -183,6 +212,7 @@ export class DocumentCognitionService extends pulumi.ComponentResource {
managedPolicyArns: [
sqsPolicy.arn,
secretsManagerPolicy.arn,
+ s3Policy.arn,
connectionTablePolicyArn,
],
tags: this.tags,
diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.ts
index bb91dee59d..aac6e035a0 100644
--- a/infra/stacks/document-cognition-service/index.ts
+++ b/infra/stacks/document-cognition-service/index.ts
@@ -131,6 +131,34 @@ const cloudStorageServiceStack = new pulumi.StackReference(
}
);
+const linksharingStack = new pulumi.StackReference('linksharing-stack', {
+ name: `macro-inc/link-sharing/${stack}`,
+});
+
+const cloudfronDistributionUrl: pulumi.Output<string> = linksharingStack
+ .getOutput('cloudfrontDistributionUrl')
+ .apply((url) => url as string);
+
+const cloudfronSignerPublicKeyId: pulumi.Output<string> = linksharingStack
+ .getOutput('cloudfrontDistributionPublicKeyId')
+ .apply((key) => key as string);
+
+const CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME = `linksharing-private-key-${stack}`;
+
+const cloudfrontPrivateKeySecretArn: pulumi.Output<string> = aws.secretsmanager
+ .getSecretOutput({
+ name: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,
+ })
+ .apply((secret) => secret.arn);
+
+const docxUploadBucketName: pulumi.Output<string> = cloudStorageServiceStack
+ .getOutput('docxUploadBucketName')
+ .apply((name) => name as string);
+
+const docxUploadBucketArn: pulumi.Output<string> = cloudStorageServiceStack
+ .getOutput('docxUploadBucketArn')
+ .apply((arn) => arn as string);
+
export const documentStorageServiceUrl: pulumi.Output<string> =
cloudStorageServiceStack
.getOutput('cloudStorageServiceUrl')
@@ -165,6 +193,10 @@ const documentStorageBucketId: pulumi.Output<string> = cloudStorageStack
.getOutput('documentStorageBucketId')
.apply((id) => id as string);
+const documentStorageBucketArn: pulumi.Output<string> = cloudStorageStack
+ .getOutput('documentStorageBucketArn')
+ .apply((arn) => arn as string);
+
export const deleteChatQueueArn: pulumi.Output<string> =
cloudStorageServiceStack
.getOutput('deleteChatQueueArn')
@@ -197,9 +229,11 @@ const documentCognitionService = new DocumentCognitionService(
syncServiceAuthKeyArn,
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
authenticationServiceInternalApiKeyArn,
+ cloudfrontPrivateKeySecretArn,
],
serviceContainerPort: 8080,
healthCheckPath: '/health',
+ bucketArns: [documentStorageBucketArn, docxUploadBucketArn],
queueArns: [
documentTextExtractorQueueArn,
deleteChatQueueArn,
@@ -341,6 +375,22 @@ const documentCognitionService = new DocumentCognitionService(
name: 'CONNECTION_GATEWAY_TABLE',
value: pulumi.interpolate`${connectionGatewayTableName}`,
},
+ {
+ name: 'DOCX_DOCUMENT_UPLOAD_BUCKET',
+ value: pulumi.interpolate`${docxUploadBucketName}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL',
+ value: pulumi.interpolate`${cloudfronDistributionUrl}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',
+ value: pulumi.interpolate`${cloudfronSignerPublicKeyId}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME',
+ value: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,
+ },
// OpenTelemetry / Datadog tracing configuration
{
name: 'DD_SERVICE',
@@ -361,3 +411,5 @@ export const documentCognitionServiceSgId =
export const documentCognitionServiceAlbSgId =
documentCognitionService.serviceAlbSg.id;
export const documentCognitionServiceUrl = pulumi.interpolate`${documentCognitionService.domain}`;
+export const documentCognitionServiceRoleArn =
+ documentCognitionService.role.arn;
diff --git a/infra/stacks/link-sharing/file-storage-bucket.ts b/infra/stacks/link-sharing/file-storage-bucket.ts
index ab54daa375..abb2108efc 100644
--- a/infra/stacks/link-sharing/file-storage-bucket.ts
+++ b/infra/stacks/link-sharing/file-storage-bucket.ts
@@ -45,6 +45,7 @@ export const attachPolicyToBucket = ({
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
convertServiceRoleArn,
+ documentCognitionRoleArn,
}: {
cloudfrontDistributionArn: pulumi.Output<string>;
bucket: pulumi.Output<GetStorageBucketResult>;
@@ -59,6 +60,7 @@ export const attachPolicyToBucket = ({
searchProcessingServiceRoleArn: pulumi.Output<string>;
bulkUploadLambdaRoleArn: pulumi.Output<string>;
convertServiceRoleArn: pulumi.Output<string>;
+ documentCognitionRoleArn: pulumi.Output<string>;
}) => {
const groupName = config.require('adminGroupName');
@@ -88,6 +90,7 @@ export const attachPolicyToBucket = ({
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
convertServiceRoleArn,
+ documentCognitionRoleArn,
];
});
@@ -220,6 +223,20 @@ export const attachPolicyToBucket = ({
Action: ['s3:GetObject', 's3:PutObject'],
Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],
},
+ {
+ Sid: 'AllowAccessForDocumentCognitionService',
+ Effect: 'Allow',
+ Principal: {
+ AWS: documentCognitionRoleArn,
+ },
+ Action: [
+ 's3:ListBucket',
+ 's3:GetObject',
+ 's3:PutObject',
+ 's3:DeleteObject',
+ ],
+ Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],
+ },
{
Sid: 'AllowCloudFrontServicePrincipal',
Effect: 'Allow',
diff --git a/infra/stacks/link-sharing/index.ts b/infra/stacks/link-sharing/index.ts
index be18e1e8c9..23e84dbc33 100644
--- a/infra/stacks/link-sharing/index.ts
+++ b/infra/stacks/link-sharing/index.ts
@@ -130,10 +130,21 @@ const convertServiceStack = new pulumi.StackReference('convert-service-stack', {
name: `macro-inc/convert-service/${stack}`,
});
+const documentCognitionStack = new pulumi.StackReference(
+ 'document-cognition-stack',
+ {
+ name: `macro-inc/document-cognition/${stack}`,
+ }
+);
+
const convertServiceRoleArn: pulumi.Output<string> = convertServiceStack
.getOutput('convertServiceRoleArn')
.apply((arn) => arn as string);
+const documentCognitionRoleArn: pulumi.Output<string> = documentCognitionStack
+ .getOutput('documentCognitionServiceRoleArn')
+ .apply((arn) => arn as string);
+
export const bucketPolicy = attachPolicyToBucket({
cloudfrontDistributionArn: s3CloudfrontDistribution.distribution.arn,
bucket: fileStorageBucket,
@@ -148,4 +159,5 @@ export const bucketPolicy = attachPolicyToBucket({
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
convertServiceRoleArn,
+ documentCognitionRoleArn,
});
diff --git a/js/app/packages/core/component/AI/component/debug/mockData.ts b/js/app/packages/core/component/AI/component/debug/mockData.ts
index a170776318..d0b5a74ec3 100644
--- a/js/app/packages/core/component/AI/component/debug/mockData.ts
+++ b/js/app/packages/core/component/AI/component/debug/mockData.ts
@@ -96,11 +96,11 @@ export function toolCall(_delay: NetworkDelay = noDelay) {
type: 'toolCall',
tool: {
data: {
- contentType: 'document',
+ contentType: 'channel',
ids: ['this-is-not-a-real-id'],
messagesSince: null,
},
- name: 'Read',
+ name: 'ReadThread',
},
},
{
diff --git a/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx
new file mode 100644
index 0000000000..cb9542201b
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx
@@ -0,0 +1,23 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import FilePlus from '@phosphor-icons/core/regular/file-plus.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'CreateDocument',
+ renderCall: (ctx) => (
+ <BaseTool icon={FilePlus} renderContext={ctx.renderContext} type="call">
+ Create{' '}
+ <span class="text-accent">
+ {ctx.tool.data.documentName}.{ctx.tool.data.fileExtension}
+ </span>
+ </BaseTool>
+ ),
+ renderResponse: (ctx) => (
+ <BaseTool renderContext={ctx.renderContext} type="response">
+ <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ </BaseTool>
+ ),
+});
+
+export const createDocumentHandler = 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
new file mode 100644
index 0000000000..3bbb81a247
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/ReadContent.tsx
@@ -0,0 +1,19 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import FileText from '@phosphor-icons/core/regular/file-text.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'ReadContent',
+ renderCall: (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" />
+ </div>
+ </BaseTool>
+ ),
+ renderResponse: (_) => undefined,
+});
+
+export const readContentHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx
new file mode 100644
index 0000000000..5d0d1eae44
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx
@@ -0,0 +1,19 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import Info from '@phosphor-icons/core/regular/info.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'ReadMetadata',
+ renderCall: (ctx) => (
+ <BaseTool icon={Info} renderContext={ctx.renderContext} type="call">
+ <div class="flex flex-row gap-2">
+ <div>Get info of </div>
+ <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ </div>
+ </BaseTool>
+ ),
+ renderResponse: (_) => undefined,
+});
+
+export const readMetadataHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/Read.tsx b/js/app/packages/core/component/AI/component/tool/ReadThread.tsx
similarity index 89%
rename from js/app/packages/core/component/AI/component/tool/Read.tsx
rename to js/app/packages/core/component/AI/component/tool/ReadThread.tsx
index eab5733129..a60cff108c 100644
--- a/js/app/packages/core/component/AI/component/tool/Read.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ReadThread.tsx
@@ -3,7 +3,7 @@ import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
const handler = createToolRenderer({
- name: 'Read',
+ name: 'ReadThread',
renderCall: (ctx) => (
<BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>
Read{' '}
@@ -16,4 +16,4 @@ const handler = createToolRenderer({
renderResponse: (_) => undefined,
});
-export const readHandler = handler;
+export const readThreadHandler = handler;
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 6d8860e5d8..dfde4096b5 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -10,8 +10,11 @@ import {
} from '@service-cognition/generated/tools/tool';
import { Dynamic } from 'solid-js/web';
import { bashCodeExecutionHandler } from './BashCodeExecution';
+import { createDocumentHandler } from './CreateDocument';
import { listEntitiesHandler } from './ListEntities';
-import { readHandler } from './Read';
+import { readThreadHandler } from './ReadThread';
+import { readContentHandler } from './ReadContent';
+import { readMetadataHandler } from './ReadMetadata';
import { contentSearchHandler, nameSearchHandler } from './Search';
import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';
import type { RenderContext } from './ToolRenderer';
@@ -22,8 +25,11 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListEntities: listEntitiesHandler,
bash_code_execution: bashCodeExecutionHandler,
ContentSearch: contentSearchHandler,
+ CreateDocument: createDocumentHandler,
NameSearch: nameSearchHandler,
- Read: readHandler,
+ ReadThread: readThreadHandler,
+ ReadContent: readContentHandler,
+ ReadMetadata: readMetadataHandler,
text_editor_code_execution: textEditorCodeExecutionHandler,
web_fetch: webFetchHandler,
web_search: webSearchHandler,
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 d4da39bece..cb0db94d96 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
@@ -321,6 +321,18 @@ export const SearchToolResponse = z.object({
),
});
+export const CreateDocument = z
+ .object({
+ documentName: z.string(),
+ fileContentBytes: z.array(z.number().int().gte(0).lte(255)),
+ fileExtension: z.string(),
+ })
+ .strict();
+
+export const CreateDocumentResponse = z.object({
+ documentId: z.string().uuid(),
+});
+
export const ListEntities = z
.object({
includeTypes: z.union([
@@ -390,10 +402,77 @@ export const NameSearch = z
})
.strict();
-export const Read = z
+export const ReadContent = z.object({ documentId: z.string().uuid() }).strict();
+
+export const ReadContentResponse = z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ text: z.string() }).strict(),
+ z
+ .object({
+ markdown: z.array(
+ z.object({
+ content: z.string(),
+ nodeId: z.string(),
+ rawContent: z.string(),
+ type: z.string(),
+ })
+ ),
+ })
+ .strict(),
+ ];
+ 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 ReadMetadata = z
+ .object({ documentId: z.string().uuid() })
+ .strict();
+
+export const ReadMetadataResponse = z.object({
+ documentMetadata: z.object({
+ branchedFromId: z.union([z.string(), z.null()]).optional(),
+ branchedFromVersionId: z.union([z.number().int(), z.null()]).optional(),
+ createdAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ documentBom: z.any().optional(),
+ documentFamilyId: z.union([z.number().int(), z.null()]).optional(),
+ documentId: z.string(),
+ documentName: z.string(),
+ documentVersionId: z.number().int(),
+ fileType: z.union([z.string(), z.null()]).optional(),
+ modificationData: z.any().optional(),
+ owner: z.string(),
+ projectId: z.union([z.string(), z.null()]).optional(),
+ projectName: z.union([z.string(), z.null()]).optional(),
+ sha: z.union([z.string(), z.null()]).optional(),
+ subType: z.union([z.literal('task'), z.null()]).optional(),
+ updatedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ }),
+ userAccessLevel: z.enum(['view', 'comment', 'edit', 'owner']),
+});
+
+export const ReadThread = z
.object({
contentType: z.enum([
- 'document',
'channel',
'channel-message',
'chat-thread',
@@ -410,10 +489,6 @@ export const Read = z
export const ReadResponse = z.object({
content: z.any().superRefine((x, ctx) => {
const schemas = [
- z.object({
- documents: z.array(z.object({ formattedDocument: z.string() })),
- type: z.literal('documents'),
- }),
z.object({
channel_id: z.string(),
channel_name: z.union([z.string(), z.null()]).optional(),
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 b1300dd482..f82e9c6a6b 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
@@ -17,12 +17,21 @@ type ToolParserMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateDocument: {
+ call: types.CreateDocument;
+ response: types.CreateDocumentResponse;
+ };
ListEntities: {
call: types.ListEntities;
response: types.ListEntitiesResponse;
};
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
- Read: { call: types.Read; response: types.ReadResponse };
+ ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
+ ReadMetadata: {
+ call: types.ReadMetadata;
+ response: types.ReadMetadataResponse;
+ };
+ ReadThread: { call: types.ReadThread; response: types.ReadResponse };
text_editor_code_execution: {
call: types.TextEditorCodeExecutionToolCall;
response: types.TextEditorCodeExecutionResponse;
@@ -43,6 +52,10 @@ const toolParserMap = {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
},
+ CreateDocument: {
+ call: schemas.CreateDocument,
+ response: schemas.CreateDocumentResponse,
+ },
ListEntities: {
call: schemas.ListEntities,
response: schemas.ListEntitiesResponse,
@@ -51,7 +64,15 @@ const toolParserMap = {
call: schemas.NameSearch,
response: schemas.SearchToolResponse,
},
- Read: { call: schemas.Read, response: schemas.ReadResponse },
+ ReadContent: {
+ call: schemas.ReadContent,
+ response: schemas.ReadContentResponse,
+ },
+ ReadMetadata: {
+ call: schemas.ReadMetadata,
+ response: schemas.ReadMetadataResponse,
+ },
+ ReadThread: { call: schemas.ReadThread, response: schemas.ReadResponse },
text_editor_code_execution: {
call: schemas.TextEditorCodeExecutionToolCall,
response: schemas.TextEditorCodeExecutionResponse,
@@ -83,12 +104,21 @@ type ToolDataMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateDocument: {
+ call: types.CreateDocument;
+ response: types.CreateDocumentResponse;
+ };
ListEntities: {
call: types.ListEntities;
response: types.ListEntitiesResponse;
};
NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };
- Read: { call: types.Read; response: types.ReadResponse };
+ ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
+ ReadMetadata: {
+ call: types.ReadMetadata;
+ response: types.ReadMetadataResponse;
+ };
+ ReadThread: { call: types.ReadThread; response: types.ReadResponse };
text_editor_code_execution: {
call: types.TextEditorCodeExecutionToolCall;
response: types.TextEditorCodeExecutionResponse;
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 f37dcf47fe..98f170a594 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
@@ -576,6 +576,48 @@ export interface SearchToolResponse {
)[];
}
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Create a document
+ */
+export interface CreateDocument {
+ /**
+ * The name of the document without the file extension
+ */
+ documentName: string;
+ /**
+ * The raw bytes of the local file you created.
+ */
+ fileContentBytes: number[];
+ /**
+ * The extension of the file you are going to create.
+ */
+ fileExtension: string;
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * The read content response
+ */
+export interface CreateDocumentResponse {
+ /**
+ * The id of the document
+ */
+ documentId: string;
+}
+
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
@@ -666,15 +708,180 @@ export interface NameSearch {
*/
/**
- * Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).
+ * Retrieve a documents content
+ */
+export interface ReadContent {
+ /**
+ * The id of the document you want to retrieve content for.
+ */
+ documentId: string;
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * The read content response
+ */
+export type ReadContentResponse =
+ | {
+ text: string;
+ }
+ | {
+ markdown: {
+ /**
+ * Human readable content
+ */
+ content: string;
+ /**
+ * The node id
+ */
+ nodeId: string;
+ /**
+ * Json respresentation
+ */
+ rawContent: string;
+ /**
+ * The style on the node, H1, em, code, etc.
+ */
+ type: string;
+ }[];
+ };
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Retrieve a documents metadata
+ */
+export interface ReadMetadata {
+ /**
+ * The id of the document you want to retrieve metadata for.
+ */
+ documentId: string;
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+export interface ReadMetadataResponse {
+ /**
+ * The metadata of the document
+ */
+ documentMetadata: {
+ /**
+ * The id of the document this document branched from
+ */
+ branchedFromId?: string | null;
+ /**
+ * The id of the version this document branched from
+ * This could be either DocumentInstance or DocumentBom id depending on
+ * the file type
+ */
+ branchedFromVersionId?: number | null;
+ /**
+ * The time the document was created
+ */
+ createdAt?: string | null;
+ /**
+ * The time the document was deleted
+ */
+ deletedAt?: string | null;
+ /**
+ * If the document is a DOCX document and unzipped, the document_bom will be present
+ */
+ documentBom?: {
+ [k: string]: unknown;
+ };
+ /**
+ * The id of the document family this document belongs to
+ */
+ documentFamilyId?: number | null;
+ /**
+ * The document id
+ */
+ documentId: string;
+ /**
+ * The name of the document
+ */
+ documentName: string;
+ /**
+ * The version of the document
+ * This could be the document_instance_id or document_bom_id depending on
+ * the file type
+ */
+ documentVersionId: number;
+ /**
+ * The file type of the document (file extension)
+ */
+ fileType?: string | null;
+ /**
+ * The modification data for the document instance.
+ * This is only used for PDF documents.
+ */
+ modificationData?: {
+ [k: string]: unknown;
+ };
+ /**
+ * The owner of the document
+ */
+ owner: string;
+ /**
+ * The id of the project that this document belongs to
+ */
+ projectId?: string | null;
+ /**
+ * The name of the project that this document belongs to
+ */
+ projectName?: string | null;
+ /**
+ * If the document is a PDF, this is the SHA of the pdf
+ * If the document is a DOCX, this will not be present
+ */
+ sha?: string | null;
+ /**
+ * The sub type of the document if present.
+ */
+ subType?: 'task' | null;
+ /**
+ * The time the document instance / document BOM was updated
+ */
+ updatedAt?: string | null;
+ };
+ /**
+ * The users level of access to the document
+ */
+ userAccessLevel: 'view' | 'comment' | 'edit' | 'owner';
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Read threaded content by ID(s). Supports reading channels, chats, emails, 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.
*/
-export interface Read {
+export interface ReadThread {
/**
* The type of content to read. Choose based on the type of content you want to retrieve.
*/
contentType:
- | 'document'
| 'channel'
| 'channel-message'
| 'chat-thread'
@@ -683,7 +890,7 @@ export interface Read {
| 'email-message'
| 'project';
/**
- * ID(s) of the content to read. IMPORTANT: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.
+ * ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.
*/
ids: string[];
/**
@@ -701,12 +908,6 @@ export interface Read {
export interface ReadResponse {
content:
- | {
- documents: {
- formattedDocument: string;
- }[];
- type: 'documents';
- }
| {
channel_id: string;
channel_name?: string | null;
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 6bdae26852..ed1eaa36ed 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -97,8 +97,10 @@ dependencies = [
"chrono",
"comms",
"cool_asserts",
+ "documents",
"email",
"email_service_client",
+ "entity_access",
"frecency",
"item_filters",
"lazy_static",
@@ -2774,6 +2776,7 @@ dependencies = [
"async-stream",
"async-trait",
"aws-sdk-dynamodb",
+ "aws-sdk-s3",
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
@@ -2786,9 +2789,11 @@ dependencies = [
"dashmap",
"document_cognition_service_client",
"document_storage_service_client",
+ "documents",
"doppleganger",
"email",
"email_service_client",
+ "entity_access",
"frecency",
"futures",
"http-body-util",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 9ace4e658e..528c6c1a86 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -12,7 +12,9 @@ async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
chrono.workspace = true
comms = { path = "../comms", features = ["outbound"] }
+documents = { path = "../documents", features = ["ai_tools"] }
email = { path = "../email", features = ["ai_schema", "axum", "outbound"] }
+entity_access = { path = "../entity_access" }
email_service_client = { path = "../email_service_client" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
item_filters = { path = "../item_filters" }
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 12a92ccc4a..5c7ac7d62b 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -13,6 +13,7 @@ pub mod web_fetch;
use code_execution::{
anthropic_bash_code_execution_tool, anthropic_text_editor_code_execution_tool,
};
+use documents::inbound::toolset::document_toolset;
use search::web::anthropic_web_search::anthropic_web_search_tool;
use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
@@ -43,8 +44,10 @@ pub fn all_tools() -> ToolSetWithPrompt {
// .expect("failed to add list toolset")
.add_tool::<ListEntities, SoupToolContext<ToolSoupService>>()
.expect("failed to add list entities tool")
- .add_tool::<read::Read, Arc<ToolScribe>>()
- .expect("read tool");
+ .add_tool::<read::ReadThread, Arc<ToolScribe>>()
+ .expect("read thread tool")
+ .add_subtoolset::<ToolDocumentToolContext>(document_toolset())
+ .expect("failed to add document toolset");
let prompt = prompts::TOOLS_PROMPT;
ToolSetWithPrompt { toolset, prompt }
}
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index a23b976c60..ec9a6f4ac5 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -24,9 +24,6 @@ pub struct ReadResponse {
#[serde(rename_all = "camelCase")]
#[serde(tag = "type")]
pub enum ReadContent {
- Documents {
- documents: Vec<DocumentItem>,
- },
Channel {
channel_id: String,
channel_name: Option<String>,
@@ -56,12 +53,6 @@ pub struct DocumentMetadata {
pub deleted: bool,
}
-#[derive(Debug, JsonSchema, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentItem {
- pub formatted_document: String,
-}
-
#[derive(Debug, JsonSchema, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EmailMessage {
@@ -99,17 +90,17 @@ impl From<ParsedMessage> for EmailMessage {
#[derive(Debug, JsonSchema, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
- description = "Read content by ID(s). Supports reading documents, channels, chats, and emails by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s).
+ description = "Read threaded content by ID(s). Supports reading channels, chats, emails, 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 = "Read"
+ title = "ReadThread"
)]
-pub struct Read {
+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: document, channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id."
+ description = "ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id."
)]
pub ids: Vec<String>,
#[schemars(
@@ -122,7 +113,6 @@ pub struct Read {
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum ContentType {
- Document,
Channel,
ChannelMessage,
ChatThread,
@@ -133,7 +123,7 @@ pub enum ContentType {
}
#[async_trait]
-impl AsyncTool<Arc<ToolScribe>> for Read {
+impl AsyncTool<Arc<ToolScribe>> for ReadThread {
type Output = ReadResponse;
#[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
@@ -142,7 +132,7 @@ impl AsyncTool<Arc<ToolScribe>> for Read {
scribe: ServiceContext<Arc<ToolScribe>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- tracing::info!(self=?self, "Read tool params");
+ tracing::info!(self=?self, "ReadThread tool params");
if self.ids.is_empty() {
return Err(ToolCallError {
@@ -152,7 +142,6 @@ impl AsyncTool<Arc<ToolScribe>> for Read {
}
let content = match self.content_type {
- ContentType::Document => self.read_document(&scribe, &request_context).await?,
ContentType::Channel => self.read_channel(&scribe, &request_context).await?,
ContentType::ChannelMessage => {
self.read_channel_message(&scribe, &request_context).await?
@@ -170,7 +159,7 @@ impl AsyncTool<Arc<ToolScribe>> for Read {
}
}
-impl Read {
+impl ReadThread {
fn provide_single_id(&self) -> Result<String, ToolCallError> {
if self.ids.len() > 1 {
return Err(ToolCallError {
@@ -211,46 +200,6 @@ impl Read {
})
}
- #[allow(deprecated)]
- async fn read_document(
- &self,
- scribe: &ToolScribe,
- request_context: &RequestContext,
- ) -> Result<ReadContent, ToolCallError> {
- let mut documents = Vec::new();
-
- for id in &self.ids {
- let document_fetcher = scribe
- .document
- .fetch_with_auth(id, (*request_context.jwt).clone());
-
- let document_with_content = match document_fetcher.document_content().await {
- Ok(doc) => doc,
- Err(e) => {
- tracing::warn!("failed to fetch document {}: {}", id, e);
- continue; // Skip failed documents instead of failing the entire request
- }
- };
-
- if let Some(doc) = document_with_content.text_attachment() {
- documents.push(DocumentItem {
- formatted_document: doc.to_string(),
- });
- } else {
- tracing::warn!("Unexpected document type for fetch");
- }
- }
-
- if documents.is_empty() {
- return Err(ToolCallError {
- description: "failed to fetch any documents".to_string(),
- internal_error: anyhow::anyhow!("all document fetches failed"),
- });
- }
-
- Ok(ReadContent::Documents { documents })
- }
-
#[allow(deprecated)]
async fn read_channel(
&self,
@@ -476,7 +425,7 @@ mod tests {
#[test]
#[ignore = "prints the input schema"]
fn print_input_schema() {
- let schema = generate_tool_input_schema!(Read);
+ let schema = generate_tool_input_schema!(ReadThread);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
@@ -490,15 +439,18 @@ mod tests {
#[test]
fn test_read_schema_validation() {
- let schema = generate_tool_input_schema!(Read);
+ 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, "Read", "Tool name should match the schemars title");
+ assert_eq!(
+ name, "ReadThread",
+ "Tool name should match the schemars title"
+ );
assert!(
- description.contains("Read content by ID"),
+ description.contains("Read threaded content by ID"),
"Description should contain expected text"
);
}
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index c432b98f89..8737289c76 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -3,7 +3,13 @@ use comms::{
domain::service::ChannelServiceImpl,
outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},
};
+use documents::{
+ domain::ports::TaskPropertiesPort,
+ inbound::toolset::DocumentToolContext,
+ outbound::{pg_document_repo::PgDocumentRepo, s3_upload_url::S3UploadUrlAdapter},
+};
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use scribe::{
ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
@@ -34,6 +40,33 @@ pub type ToolEmailService = EmailServiceImpl<
/// Type alias for the comms/channels service implementation
pub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
+/// No-op task properties service (not needed for AI tools)
+#[derive(Clone)]
+pub struct NoOpTaskProperties;
+
+impl TaskPropertiesPort for NoOpTaskProperties {
+ async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+/// Type alias for the document service implementation used by AI tools
+pub type ToolDocumentService = documents::domain::service::DocumentServiceImpl<
+ PgDocumentRepo,
+ S3UploadUrlAdapter,
+ NoOpTaskProperties,
+>;
+
+/// Type alias for the entity access service implementation
+pub type ToolEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+
+/// Type alias for the document tool context
+pub type ToolDocumentToolContext =
+ DocumentToolContext<ToolDocumentService, ToolEntityAccessService>;
+
/// Type alias for the soup service implementation
pub type ToolSoupService =
SoupImpl<PgSoupRepo, ToolFrecencyService, ToolEmailService, ToolCommsService>;
@@ -46,6 +79,7 @@ pub struct ToolServiceContext {
pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,
pub scribe: Arc<ToolScribe>,
pub soup_service: Arc<ToolSoupService>,
+ pub document_tool_context: ToolDocumentToolContext,
}
impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index a7a9a56314..011bb4c44a 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -37,8 +37,9 @@ ai_tools = { path = "../ai_tools" }
anyhow = { workspace = true }
async-openai = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
-macro_aws_config = { path = "../macro_aws_config" }
+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
aws-sdk-dynamodb = { workspace = true }
+aws-sdk-s3 = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true, features = ["tower-log", "ws"] }
base64 = { workspace = true }
@@ -50,6 +51,8 @@ cookie = { workspace = true }
dashmap = { workspace = true }
document_cognition_service_client = { path = "../document_cognition_service_client" }
document_storage_service_client = { path = "../document_storage_service_client" }
+documents = { path = "../documents", features = ["ai_tools"] }
+entity_access = { path = "../entity_access" }
doppleganger = { workspace = true }
email = { path = "../email", features = ["outbound"] }
email_service_client = { path = "../email_service_client" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index 9ab2ea65b3..05e218ceb3 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -1,5 +1,5 @@
use crate::config::Config;
-use ai_tools::ToolSoupService;
+use ai_tools::{ToolDocumentToolContext, ToolSoupService};
use axum::extract::FromRef;
use connection_gateway_client::service::connection::ConnectionRepo;
use document_storage_service_client::DocumentStorageServiceClient;
@@ -61,6 +61,7 @@ pub struct ApiContext {
pub connection_repo: Arc<dyn ConnectionRepo>,
pub soup_service: Arc<ToolSoupService>,
pub stream_repo: Arc<dyn StreamRepo>,
+ pub document_tool_context: ToolDocumentToolContext,
}
pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
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 f59cdcf8ad..683bf80abe 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
@@ -180,7 +180,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
DocumentClient::builder()
.with_dss_client(document_storage_client.clone())
.with_lexical_client(lexical_client)
- .with_sync_service_client(sync_service_client)
+ .with_sync_service_client(sync_service_client.clone())
.with_macro_db(pool.clone())
.build(),
)
@@ -248,6 +248,42 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
NotificationIngressService::new(notification_repository, notification_queue, state_machine)
});
+ // Build document tool context for AI tools
+ let s3_config = aws_sdk_s3::Config::builder()
+ .behavior_version(aws_sdk_s3::config::BehaviorVersion::latest())
+ .build();
+ let s3_client = aws_sdk_s3::Client::from_conf(s3_config);
+ let s3_upload_adapter = documents::outbound::s3_upload_url::S3UploadUrlAdapter::new(
+ s3_client,
+ "test-bucket",
+ "test-docx-bucket",
+ );
+ let document_repo = documents::outbound::pg_document_repo::PgDocumentRepo::new(pool.clone());
+ let cloudfront_config = documents::domain::models::CloudFrontConfig {
+ distribution_url: "https://test.cloudfront.net".to_string(),
+ signer_public_key_id: "test-key-id".to_string(),
+ signer_private_key: "test-private-key".to_string(),
+ presigned_url_expiry_seconds: 3600,
+ browser_cache_expiry_seconds: 86400,
+ };
+ let document_service = documents::domain::service::DocumentServiceImpl::new(
+ document_repo,
+ cloudfront_config,
+ sync_service_client.as_ref().clone(),
+ s3_upload_adapter,
+ ai_tools::NoOpTaskProperties,
+ pool.clone(),
+ );
+ let entity_access_service = entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ );
+ let test_lexical_client = LexicalClient::new("test".into(), "http://nofileshere".into());
+ let document_tool_context = documents::inbound::toolset::DocumentToolContext::new(
+ document_service,
+ entity_access_service,
+ test_lexical_client,
+ );
+
let api_context = ApiContext {
db: pool.clone(),
sqs_client: Arc::new(sqs_client),
@@ -263,6 +299,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
connection_repo: MockConnectionRepo::new(),
soup_service,
stream_repo: MockStreamRepo::new(),
+ document_tool_context,
};
Arc::new(api_context)
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
index 3d82962acc..1292fb1f1d 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
@@ -345,6 +345,7 @@ fn stream_and_save_message(
search_service_client: ctx.search_service_client.clone(),
scribe: ctx.scribe.clone(),
soup_service: ctx.soup_service.clone(),
+ document_tool_context: ctx.document_tool_context.clone(),
};
#[expect(deprecated)]
diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rs
index 6ce316bd1e..ea163c2e6c 100644
--- a/rust/cloud-storage/document_cognition_service/src/config.rs
+++ b/rust/cloud-storage/document_cognition_service/src/config.rs
@@ -44,6 +44,14 @@ pub struct Config {
pub authentication_service_secret_key: String,
/// Redis host for stream service
pub redis_host: RedisHost,
+ /// The S3 bucket for DOCX document uploads
+ pub docx_document_upload_bucket: String,
+ /// CloudFront distribution URL for document storage
+ pub cloudfront_distribution_url: String,
+ /// CloudFront signer public key ID
+ pub cloudfront_signer_public_key_id: String,
+ /// CloudFront signer private key (secret name or value)
+ pub cloudfront_signer_private_key: String,
}
env_var!(
@@ -109,6 +117,25 @@ impl Config {
let authentication_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
.context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;
+ let docx_document_upload_bucket = std::env::var("DOCX_DOCUMENT_UPLOAD_BUCKET")
+ .context("DOCX_DOCUMENT_UPLOAD_BUCKET must be provided")?;
+
+ let cloudfront_distribution_url =
+ std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")
+ .context("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be provided")?;
+
+ let cloudfront_signer_public_key_id = std::env::var(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID",
+ )
+ .context("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be provided")?;
+
+ let cloudfront_signer_private_key = std::env::var(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME",
+ )
+ .context(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME must be provided",
+ )?;
+
let EnvVars { redis_host } = env_vars;
Ok(Config {
@@ -131,6 +158,10 @@ impl Config {
authentication_service_url,
authentication_service_secret_key,
redis_host,
+ docx_document_upload_bucket,
+ cloudfront_distribution_url,
+ cloudfront_signer_public_key_id,
+ cloudfront_signer_private_key,
})
}
@@ -156,6 +187,10 @@ impl Config {
authentication_service_url: Default::default(),
authentication_service_secret_key: Default::default(),
redis_host: RedisHost::Comptime("redis://localhost:6379"),
+ docx_document_upload_bucket: Default::default(),
+ cloudfront_distribution_url: Default::default(),
+ cloudfront_signer_public_key_id: Default::default(),
+ cloudfront_signer_private_key: Default::default(),
}
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index c88f2d5085..3d0aa3e58a 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -1,4 +1,5 @@
use crate::api::context::ApiContext;
+use ai_tools::NoOpTaskProperties;
use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
@@ -7,9 +8,15 @@ use comms_service_client::CommsServiceClient;
use config::{Config, EnvVars, Environment};
use document_cognition_service_client::DocumentCognitionServiceClient;
use document_storage_service_client::DocumentStorageServiceClient;
+use documents::{
+ domain::{models::CloudFrontConfig, service::DocumentServiceImpl},
+ inbound::toolset::DocumentToolContext,
+ outbound::{pg_document_repo::PgDocumentRepo, s3_upload_url::S3UploadUrlAdapter},
+};
use email::domain::service::EmailServiceImpl;
use email::outbound::EmailPgRepo;
use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -235,6 +242,47 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized notification ingress service");
+ // Build document tool context for AI tools
+ let s3_client = macro_aws_config::s3_client().await;
+ let s3_upload_adapter = S3UploadUrlAdapter::new(
+ s3_client,
+ config.document_storage_bucket.clone(),
+ config.docx_document_upload_bucket.clone(),
+ );
+ let document_repo = PgDocumentRepo::new(db.clone());
+ let cloudfront_private_key = match config.environment {
+ Environment::Local => config.cloudfront_signer_private_key.clone(),
+ _ => secretsmanager_client
+ .get_secret_value(&config.cloudfront_signer_private_key)
+ .await
+ .context("failed to get CloudFront signer private key from secrets manager")?
+ .to_string(),
+ };
+ let cloudfront_config = CloudFrontConfig {
+ distribution_url: config.cloudfront_distribution_url.clone(),
+ signer_public_key_id: config.cloudfront_signer_public_key_id.clone(),
+ signer_private_key: cloudfront_private_key,
+ presigned_url_expiry_seconds: 3600,
+ browser_cache_expiry_seconds: 86400,
+ };
+ let document_service = DocumentServiceImpl::new(
+ document_repo,
+ cloudfront_config,
+ sync_service_client.clone(),
+ s3_upload_adapter,
+ NoOpTaskProperties,
+ db.clone(),
+ );
+ let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone()));
+ let lexical_client_for_tools = (*lexical_client).clone();
+ let document_tool_context = DocumentToolContext::new(
+ document_service,
+ entity_access_service,
+ lexical_client_for_tools,
+ );
+
+ tracing::info!("initialized document tool context");
+
api::setup_and_serve(ApiContext {
db: db.clone(),
email_service_client_external: Arc::new(EmailServiceClientExternal::new(
@@ -266,6 +314,7 @@ async fn main() -> anyhow::Result<()> {
connection_repo: connection_manager.persistence,
soup_service,
stream_repo,
+ document_tool_context,
})
.await
.context("failed to setup and serve api")?;