Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): soup replace list tool with soup tool (#1213)
Eric Hayes951fa10062df
diff --git a/infra/stacks/document-cognition-service/Pulumi.dev.yaml b/infra/stacks/document-cognition-service/Pulumi.dev.yamlindex 4a75bbab58..987a05b985 100644--- a/infra/stacks/document-cognition-service/Pulumi.dev.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.dev.yaml@@ -14,3 +14,4 @@ config:document-cognition:open-router-api-key: open-router-api-key-dev-v2document-cognition:sync_service_auth_key: sync-service-key-devdocument-cognition:perplexity-api-key: perplexity-api-key+ document-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-devdiff --git a/infra/stacks/document-cognition-service/Pulumi.prod.yaml b/infra/stacks/document-cognition-service/Pulumi.prod.yamlindex edde68190e..56fe94a8e4 100644--- a/infra/stacks/document-cognition-service/Pulumi.prod.yaml+++ b/infra/stacks/document-cognition-service/Pulumi.prod.yaml@@ -14,3 +14,4 @@ config:document-cognition:open-router-api-key: open-router-api-key-prod-v2document-cognition:sync_service_auth_key: sync-service-key-proddocument-cognition:perplexity-api-key: perplexity-api-key+ document-cognition:authentication_service_internal_api_key: authentication-service-internal-api-key-proddiff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.tsindex 54b9b1189b..8c5b68918a 100644--- a/infra/stacks/document-cognition-service/index.ts+++ b/infra/stacks/document-cognition-service/index.ts@@ -87,6 +87,17 @@ const PERPLEXITY_API_KEY = aws.secretsmanager}).apply((secret) => secret.secretString);+const AUTHENTICATION_SERVICE_INTERNAL_API_KEY_SECRET_NAME = config.require(+ 'authentication_service_internal_api_key'+);++const authenticationServiceInternalApiKeyArn: pulumi.Output<string> =+ aws.secretsmanager+ .getSecretVersionOutput({+ secretId: AUTHENTICATION_SERVICE_INTERNAL_API_KEY_SECRET_NAME,+ })+ .apply((secret) => secret.arn);+export const coparse_api_vpc = get_coparse_api_vpc();const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {@@ -173,6 +184,7 @@ const documentCognitionService = new DocumentCognitionService(jwtSecretKeyArn,syncServiceAuthKeyArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,+ authenticationServiceInternalApiKeyArn,],serviceContainerPort: 8080,healthCheckPath: '/health',@@ -308,6 +320,16 @@ const documentCognitionService = new DocumentCognitionService(name: 'STATIC_FILE_SERVICE_URL',value: `https://static-file-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,},+ {+ name: 'AUTHENTICATION_SERVICE_URL',+ value: `https://auth-service${+ stack === 'prod' ? '' : `-${stack}`+ }.macro.com`,+ },+ {+ name: 'AUTHENTICATION_SERVICE_SECRET_KEY',+ value: AUTHENTICATION_SERVICE_INTERNAL_API_KEY_SECRET_NAME,+ },],isPrivate: false,tags,diff --git a/js/app/packages/core/component/AI/component/tool/ListChannels.tsx b/js/app/packages/core/component/AI/component/tool/ListChannels.tsxdeleted file mode 100644index f4ea6582b6..0000000000--- a/js/app/packages/core/component/AI/component/tool/ListChannels.tsx+++ /dev/null@@ -1,25 +0,0 @@-import Channel from '@icon/duotone/hash-duotone.svg';-import { BaseTool } from './BaseTool';-import { createToolRenderer } from './ToolRenderer';--const handler = createToolRenderer({- name: 'ListChannels',- renderCall: (ctx) => (- <BaseTool- icon={Channel}- text="Listing channels..."- renderContext={ctx.renderContext}- type="call"- />- ),- renderResponse: (ctx) => (- <BaseTool- icon={Channel}- text={`Found ${ctx.tool.data.total} channel${ctx.tool.data.total === 1 ? '' : 's'}`}- renderContext={ctx.renderContext}- type="response"- />- ),-});--export const listChannelsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ListEmails.tsx b/js/app/packages/core/component/AI/component/tool/ListEmails.tsxdeleted file mode 100644index bc980ca62d..0000000000--- a/js/app/packages/core/component/AI/component/tool/ListEmails.tsx+++ /dev/null@@ -1,134 +0,0 @@-import { EntityIcon } from '@core/component/EntityIcon';-import { TruncatedText } from '@core/component/FileList/TruncatedText';-import ChevronDown from '@icon/regular/caret-down.svg?component-solid';-import ChevronUp from '@icon/regular/caret-up.svg?component-solid';-import List from '@phosphor-icons/core/regular/list.svg';-import type { NamedTool } from '@service-cognition/generated/tools/tool';-import { useSplitLayout } from 'app/component/split-layout/layout';-import { createMemo, createSignal, Show } from 'solid-js';-import { VList } from 'virtua/solid';-import { BaseTool } from './BaseTool';-import { createToolRenderer } from './ToolRenderer';--type ListEmailsResult = NamedTool<- 'ListEmails',- 'response'->['data']['items'][number];--const ListEmailsToolResponse = (props: { results: ListEmailsResult[] }) => {- const [isExpanded, setIsExpanded] = createSignal(false);-- const results = createMemo(() => {- // results should be unique but this is an extra safety check- const seen = new Set<string>();- return props.results.filter((result) => {- let key = result.id;- if (seen.has(key)) return false;- seen.add(key);- return true;- });- });-- const getResultTitle = (result: ListEmailsResult): string => {- return result.name || result.snippet || 'Email';- };-- const { replaceOrInsertSplit } = useSplitLayout();-- const getClickHandler = (result: ListEmailsResult) => {- return () => {- replaceOrInsertSplit({ type: 'email', id: result.id });- };- };-- // TODO: share code with unified search results display- return (- <Show when={results().length > 0}>- <div class="border border-edge rounded w-full">- <button- class={`flex items-center justify-between w-full text-left p-2 hover:bg-hover transition-colors ${- isExpanded() ? 'rounded-t border-b border-edge' : 'rounded'- }`}- onClick={() => setIsExpanded((e) => !e)}- >- <div class="flex items-center gap-2">- <div class="text-sm font-medium text-ink">- Email Results ({results().length})- </div>- </div>- <div class="flex items-center gap-1 text-ink-muted">- <Show- when={isExpanded()}- fallback={<ChevronDown class="w-4 h-4" />}- >- <ChevronUp class="w-4 h-4" />- </Show>- </div>- </button>-- <Show when={isExpanded()}>- <div class="max-h-[480px] overflow-hidden">- <VList- data={results()}- bufferSize={5 * 32}- itemSize={32}- style={{- height: `${Math.min(results().length * 32, 480)}px`,- contain: 'content',- }}- >- {(result) => {- const clickHandler = getClickHandler(result);-- return (- <div- class="flex items-center w-full h-8 px-2 hover:bg-hover transition-colors cursor-pointer"- onClick={clickHandler}- >- <div class="flex items-center flex-1 min-w-0 gap-2">- <EntityIcon size="sm" targetType="email" shared={false} />- <div class="flex-1 min-w-0">- <TruncatedText size="sm">- <span>{getResultTitle(result)}</span>- </TruncatedText>- </div>- <Show when={result.senderName}>- <div class="text-xs text-ink-muted shrink-0">- {result.senderName}- </div>- </Show>- </div>- </div>- );- }}- </VList>- </div>- </Show>- </div>- </Show>- );-};--const handler = createToolRenderer({- name: 'ListEmails',- renderCall: (ctx) => (- <BaseTool- icon={List}- text="Listing emails..."- renderContext={ctx.renderContext}- type="call"- />- ),- renderResponse: (ctx) => (- <BaseTool- icon={List}- text="Listed emails"- renderContext={ctx.renderContext}- type="response"- >- <ListEmailsToolResponse results={ctx.tool.data.items || []} />- </BaseTool>- ),-});--export const listEmailsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ListDocuments.tsx b/js/app/packages/core/component/AI/component/tool/ListEntities.tsxsimilarity index 58%rename from js/app/packages/core/component/AI/component/tool/ListDocuments.tsxrename to js/app/packages/core/component/AI/component/tool/ListEntities.tsxindex 71d39c3f37..9efe190708 100644--- a/js/app/packages/core/component/AI/component/tool/ListDocuments.tsx+++ b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx@@ -1,52 +1,98 @@import { EntityIcon } from '@core/component/EntityIcon';import { TruncatedText } from '@core/component/FileList/TruncatedText';-import { fileTypeToBlockName } from '@core/constant/allBlocks';import ChevronDown from '@icon/regular/caret-down.svg?component-solid';import ChevronUp from '@icon/regular/caret-up.svg?component-solid';import List from '@phosphor-icons/core/regular/list.svg';import type { NamedTool } from '@service-cognition/generated/tools/tool';-import type { FileType } from '@service-storage/generated/schemas/fileType';import { useSplitLayout } from 'app/component/split-layout/layout';import { createMemo, createSignal, Show } from 'solid-js';import { VList } from 'virtua/solid';import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';-type ListDocumentsResult = NamedTool<- 'ListDocuments',+type ListEntitiesItem = NamedTool<+ 'ListEntities','response'->['data']['results'][number];+>['data']['items'][number];-const ListDocumentsToolResponse = (props: {- results: ListDocumentsResult[];+const ListEntitiesToolResponse = (props: {+ items: ListEntitiesItem[];+ summary: string;}) => {const [isExpanded, setIsExpanded] = createSignal(false);const results = createMemo(() => {- // results should be unique but this is an extra safety checkconst seen = new Set<string>();- return props.results.filter((result) => {- let key = result.document_id;- if (seen.has(key)) return false;- seen.add(key);+ return props.items.filter((item) => {+ if (seen.has(item.id)) return false;+ seen.add(item.id);return true;});});- const getResultTitle = (result: ListDocumentsResult): string => {- return result.document_name || 'Document';+ const getItemTitle = (item: ListEntitiesItem): string => {+ switch (item.type) {+ case 'document':+ return item.name || 'Document';+ case 'aiChat':+ return item.name || 'Chat';+ case 'project':+ return item.name || 'Project';+ case 'email':+ return item.subject || 'Email';+ case 'channel':+ return item.name || 'Channel';+ default:+ return 'Item';+ }+ };++ const getIconType = (item: ListEntitiesItem) => {+ switch (item.type) {+ case 'document':+ return 'default';+ case 'aiChat':+ return 'chat';+ case 'project':+ return 'project';+ case 'email':+ return 'email';+ case 'channel':+ return 'channel';+ default:+ return 'default';+ }};const { replaceOrInsertSplit } = useSplitLayout();- const getClickHandler = (result: ListDocumentsResult) => {- return () => {- const blockName = fileTypeToBlockName(result.file_type);- replaceOrInsertSplit({ type: blockName, id: result.document_id });- };+ const getClickHandler = (item: ListEntitiesItem) => {+ switch (item.type) {+ case 'document':+ return () => {+ replaceOrInsertSplit({ type: 'unknown', id: item.id });+ };+ case 'aiChat':+ return () => {+ replaceOrInsertSplit({ type: 'chat', id: item.id });+ };+ case 'project':+ return () => {+ replaceOrInsertSplit({ type: 'project', id: item.id });+ };+ case 'email':+ return () => {+ replaceOrInsertSplit({ type: 'email', id: item.id });+ };+ case 'channel':+ return () => {+ replaceOrInsertSplit({ type: 'channel', id: item.id });+ };+ default:+ return undefined;+ }};- // TODO: share code with unified search results displayreturn (<Show when={results().length > 0}><div class="border border-edge rounded w-full">@@ -60,7 +106,7 @@ const ListDocumentsToolResponse = (props: {<div class="text-sm font-medium text-ink">Found<span class="text-accent pr-1"> {results().length}</span>- Documents+ Items</div></div><div class="flex items-center gap-1 text-ink-muted">@@ -84,8 +130,8 @@ const ListDocumentsToolResponse = (props: {contain: 'content',}}>- {(result) => {- const clickHandler = getClickHandler(result);+ {(item) => {+ const clickHandler = getClickHandler(item);return (<div@@ -95,12 +141,12 @@ const ListDocumentsToolResponse = (props: {<div class="flex items-center flex-1 min-w-0 gap-2"><EntityIconsize="sm"- targetType={result.file_type as FileType | undefined}+ targetType={getIconType(item)}shared={false}/><div class="flex-1 min-w-0"><TruncatedText size="sm">- <span>{getResultTitle(result)}</span>+ <span>{getItemTitle(item)}</span></TruncatedText></div></div>@@ -116,11 +162,11 @@ const ListDocumentsToolResponse = (props: {};const handler = createToolRenderer({- name: 'ListDocuments',+ name: 'ListEntities',renderCall: (ctx) => (<BaseToolicon={List}- text="Listing documents..."+ text="Browsing workspace..."renderContext={ctx.renderContext}type="call"/>@@ -128,13 +174,16 @@ const handler = createToolRenderer({renderResponse: (ctx) => (<BaseToolicon={List}- text="Listed"+ text="Found items"renderContext={ctx.renderContext}type="response">- <ListDocumentsToolResponse results={ctx.tool.data.results} />+ <ListEntitiesToolResponse+ items={ctx.tool.data.items}+ summary={ctx.tool.data.summary}+ /></BaseTool>),});-export const listDocumentsHandler = handler;+export const listEntitiesHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex 3916163ec0..ef9a0f40e1 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -11,9 +11,7 @@ import {import { createStore } from 'solid-js/store';import { Dynamic, Show } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';-import { listChannelsHandler } from './ListChannels';-import { listDocumentsHandler } from './ListDocuments';-import { listEmailsHandler } from './ListEmails';+import { listEntitiesHandler } from './ListEntities';import { readHandler } from './Read';import { contentSearchHandler, nameSearchHandler } from './Search';import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';@@ -26,11 +24,9 @@ const [renderStore, setRenderStore] = createStore<>({});const toolHandlers: ToolHandlerMap<RenderContext> = {+ ListEntities: listEntitiesHandler,bash_code_execution: bashCodeExecutionHandler,ContentSearch: contentSearchHandler,- ListChannels: listChannelsHandler,- ListDocuments: listDocumentsHandler,- ListEmails: listEmailsHandler,NameSearch: nameSearchHandler,Read: readHandler,text_editor_code_execution: textEditorCodeExecutionHandler,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.tsindex 2d265b3df8..520a933443 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@@ -287,154 +287,64 @@ export const SearchToolResponse = z.object({),});-export const ListChannels = z- .object({ unused: z.null().default(null) })- .strict();--export const ListChannelsResponse = z.object({- channels: z.array(- z.object({- channelType: z.enum([- 'public',- 'organization',- 'private',- 'direct_message',- ]),- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- })- ),- total: z.number().int().gte(0),-});--export const ListDocuments = z+export const ListEntities = z.object({- exhaustiveSearch: z.boolean().default(false),- fileTypes: z.union([z.array(z.string()), z.null()]),- minAccessLevel: z.union([- z.literal('view'),- z.literal('comment'),- z.literal('edit'),- z.literal('owner'),- z.literal(null),+ includeTypes: z.union([+ z.array(z.enum(['document', 'ai_chat', 'project', 'email', 'channel'])),+ z.null(),]),- pageOffset: z.number().int().default(0),- pageSize: z.number().int().default(50),+ sortBy: z.enum(['recently_viewed', 'recently_updated', 'recently_created']),}).strict();-export const ListDocumentsResponse = z.object({- results: z.array(- z.object({- access_level: z.enum(['view', 'comment', 'edit', 'owner']),- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- document_id: z.string(),- document_name: z.string(),- file_type: z.union([z.string(), z.null()]).optional(),- owner: z.string(),- project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- })- ),- resultsReturned: z.number().int().gte(0),- totalResults: z.number().int().gte(0),-});--export const ListEmails = z- .object({- cursor: z.union([z.string(), z.null()]).default(null),- limit: z.number().int().default(20),- sortMethod: z- .enum(['viewed_at', 'updated_at', 'created_at', 'viewed_updated'])- .default('viewed_at'),- view: z- .object({- standardLabel: z.union([- z.literal('Inbox'),- z.literal('Sent'),- z.literal('Drafts'),- z.literal('Starred'),- z.literal('All'),- z.literal('Important'),- z.literal('Other'),- z.literal(null),- ]),- userLabel: z.union([z.string(), z.null()]),- })- .strict()- .default({ standardLabel: null, userLabel: null }),- })- .strict();--export const ApiPaginatedThreadCursor = z.object({+export const ListEntitiesResponse = z.object({items: z.array(- z.object({- attachments: z.array(+ z.any().superRefine((x, ctx) => {+ const schemas = [z.object({- contentId: z.union([z.string(), z.null()]).optional(),- createdAt: z.number().int(),- filename: z.union([z.string(), z.null()]).optional(),id: z.string().uuid(),- messageId: z.string().uuid(),- mimeType: z.union([z.string(), z.null()]).optional(),- providerAttachmentId: z.union([z.string(), z.null()]).optional(),- sizeBytes: z.union([z.number().int(), z.null()]).optional(),- })- ),- contacts: z.array(+ name: z.string(),+ type: z.literal('document'),+ }),z.object({- emailAddress: z.union([z.string(), z.null()]).optional(),id: z.string().uuid(),- linkId: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- sfsPhotoUrl: z.union([z.string(), z.null()]).optional(),- })- ),- createdAt: z.number().int(),- frecencyScore: z.union([z.number(), z.null()]).optional(),- id: z.string().uuid(),- inboxVisible: z.boolean(),- isDraft: z.boolean(),- isImportant: z.boolean(),- isRead: z.boolean(),- labels: z.array(+ name: z.string(),+ type: z.literal('aiChat'),+ }),z.object({- createdAt: z.string().datetime({ offset: true }),id: z.string().uuid(),- labelListVisibility: z.enum([- 'LabelShow',- 'LabelShowIfUnread',- 'LabelHide',- ]),- linkId: z.string().uuid(),- messageListVisibility: z.enum(['Show', 'Hide']),name: z.string(),- providerLabelId: z.string(),- type: z.enum(['System', 'User']),- })- ),- metadata: z.object({- calendar_invite: z.boolean(),- generic_sender: z.boolean(),- known_sender: z.boolean(),- tabular: z.boolean(),- }),- name: z.union([z.string(), z.null()]).optional(),- ownerId: z.string(),- providerId: z.union([z.string(), z.null()]).optional(),- senderEmail: z.union([z.string(), z.null()]).optional(),- senderName: z.union([z.string(), z.null()]).optional(),- senderPhotoUrl: z.union([z.string(), z.null()]).optional(),- snippet: z.union([z.string(), z.null()]).optional(),- sortTs: z.number().int(),- updatedAt: z.number().int(),- viewedAt: z.union([z.number().int(), z.null()]).optional(),+ type: z.literal('project'),+ }),+ z.object({+ id: z.string().uuid(),+ subject: z.union([z.string(), z.null()]).optional(),+ type: z.literal('email'),+ }),+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ type: z.literal('channel'),+ }),+ ];+ 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',+ });+ }})),- next_cursor: z.union([z.string(), z.null()]).optional(),+ summary: z.string(),});export const NameSearch = zdiff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 26d66b1c6f..b1300dd482 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,17 +17,9 @@ type ToolParserMap = {call: types.ContentSearch;response: types.SearchToolResponse;};- ListChannels: {- call: types.ListChannels;- response: types.ListChannelsResponse;- };- ListDocuments: {- call: types.ListDocuments;- response: types.ListDocumentsResponse;- };- ListEmails: {- call: types.ListEmails;- response: types.ApiPaginatedThreadCursor;+ ListEntities: {+ call: types.ListEntities;+ response: types.ListEntitiesResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };Read: { call: types.Read; response: types.ReadResponse };@@ -51,17 +43,9 @@ const toolParserMap = {call: schemas.ContentSearch,response: schemas.SearchToolResponse,},- ListChannels: {- call: schemas.ListChannels,- response: schemas.ListChannelsResponse,- },- ListDocuments: {- call: schemas.ListDocuments,- response: schemas.ListDocumentsResponse,- },- ListEmails: {- call: schemas.ListEmails,- response: schemas.ApiPaginatedThreadCursor,+ ListEntities: {+ call: schemas.ListEntities,+ response: schemas.ListEntitiesResponse,},NameSearch: {call: schemas.NameSearch,@@ -99,17 +83,9 @@ type ToolDataMap = {call: types.ContentSearch;response: types.SearchToolResponse;};- ListChannels: {- call: types.ListChannels;- response: types.ListChannelsResponse;- };- ListDocuments: {- call: types.ListDocuments;- response: types.ListDocumentsResponse;- };- ListEmails: {- call: types.ListEmails;- response: types.ApiPaginatedThreadCursor;+ ListEntities: {+ call: types.ListEntities;+ response: types.ListEntitiesResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };Read: { call: types.Read; response: types.ReadResponse };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.tsindex c49ead71db..dea91ce3b1 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@@ -573,77 +573,19 @@ export interface SearchToolResponse {*//**- * List all chat channels the user has access to. Returns channel names, IDs, and types. Use this tool to discover available channels for reading messages or participating in conversations.+ * Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, and chat channels. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead.*/-export interface ListChannels {- unused: null;-}--/* 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.- */--/**- * Response from listing channels- */-export interface ListChannelsResponse {- /**- * The list of channels the user has access to- */- channels: {- /**- * The type of channel (public, private, organization, or direct_message)- */- channelType: 'public' | 'organization' | 'private' | 'direct_message';- /**- * The channel's unique identifier- */- id: string;- /**- * The channel's display name (may be None for direct messages)- */- name?: string | null;- }[];- /**- * Total number of channels returned- */- total: number;-}--/* 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.- */--/**- * List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.- */-export interface ListDocuments {- /**- * Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits.- */- exhaustiveSearch: boolean;- /**- * Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types.- */- fileTypes: string[] | null;- /**- * Minimum access level required. Defaults to 'view' if not specified.- */- minAccessLevel: 'view' | 'comment' | 'edit' | 'owner' | null;+export interface ListEntities {/**- * Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results.+ * Filter to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails.*/- pageOffset: number;+ includeTypes:+ | ('document' | 'ai_chat' | 'project' | 'email' | 'channel')[]+ | null;/**- * Number of results per page. Max is 100, default is 50. Use smaller values for focused results.+ * How to sort results: recently_viewed (default), recently_updated, or recently_created.*/- pageSize: number;+ sortBy: 'recently_viewed' | 'recently_updated' | 'recently_created';}/* eslint-disable */@@ -653,178 +595,35 @@ export interface ListDocuments {* and run json-schema-to-typescript to regenerate this file.*/-export interface ListDocumentsResponse {- /**- * The list results (truncated to `results_returned` limit if applicable)- */- results: {- /**- * The user's access level to this document- */- access_level: 'view' | 'comment' | 'edit' | 'owner';- /**- * When the document was created- */- created_at: string;- /**- * When the document was deleted (null if not deleted)- */- deleted_at?: string | null;- /**- * The document id- */- document_id: string;- /**- * The document name- */- document_name: string;- /**- * The file type of the document- */- file_type?: string | null;- /**- * The owner of the document- */- owner: string;- /**- * The project id containing the document- */- project_id?: string | null;- /**- * When the document was last updated- */- updated_at: string;- }[];- /**- * The number of results returned- */- resultsReturned: number;- /**- * Total number of results found- */- totalResults: number;-}--/* 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.- */--/**- * List the emails the user has access to. Use this tool to find all emails from / to a specific person. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.- */-export interface ListEmails {- /**- * A preview response will tell you what the next cursor id is.- * If expected emails are not in the current response and it gives you a cursor id, use this field to list the next page of emails. If no cursor id is provided you've reached the end- */- cursor: string | null;- /**- * limit the max emails returned. This defaults to 20 and has a maximum of 500- */- limit: number;- /**- * Sort response by one of: viewed_at | updated_at | created_at | viewed_updated. Prefer viewed_at unless the otherwise specified- */- sortMethod: 'viewed_at' | 'updated_at' | 'created_at' | 'viewed_updated';- /**- * Choose the view to list emails from. One of either standard label or user label must be specified, otherwise defaults to important.- */- view: {- /**- * Prefer important or all. Leave empty if using a user label- */- standardLabel:- | 'Inbox'- | 'Sent'- | 'Drafts'- | 'Starred'- | 'All'- | 'Important'- | 'Other'- | null;- /**- * Choose a custom user label to filter by (optional). Standard label will take precedence over user label if both are specified.- */- userLabel: string | null;- };-}--/* 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 ApiPaginatedThreadCursor {- items: {- attachments: {- contentId?: string | null;- createdAt: number;- filename?: string | null;- id: string;- messageId: string;- mimeType?: string | null;- providerAttachmentId?: string | null;- sizeBytes?: number | null;- }[];- contacts: {- emailAddress?: string | null;- id: string;- linkId: string;- name?: string | null;- sfsPhotoUrl?: string | null;- }[];- createdAt: number;- frecencyScore?: number | null;- id: string;- inboxVisible: boolean;- isDraft: boolean;- isImportant: boolean;- isRead: boolean;- labels: {- createdAt: string;- id: string;- labelListVisibility: 'LabelShow' | 'LabelShowIfUnread' | 'LabelHide';- linkId: string;- messageListVisibility: 'Show' | 'Hide';- name: string;- providerLabelId: string;- type: 'System' | 'User';- }[];- metadata: {- /**- * if any email contains a calendar invite- */- calendar_invite: boolean;- /**- * if any sender in the thread is a generic email- */- generic_sender: boolean;- /**- * if user has previously emailed any sender in the thread- */- known_sender: boolean;- /**- * if any email contains a <table> html tag- */- tabular: boolean;- };- name?: string | null;- ownerId: string;- providerId?: string | null;- senderEmail?: string | null;- senderName?: string | null;- senderPhotoUrl?: string | null;- snippet?: string | null;- sortTs: number;- updatedAt: number;- viewedAt?: number | null;- }[];- next_cursor?: string | null;+export interface ListEntitiesResponse {+ items: (+ | {+ id: string;+ name: string;+ type: 'document';+ }+ | {+ id: string;+ name: string;+ type: 'aiChat';+ }+ | {+ id: string;+ name: string;+ type: 'project';+ }+ | {+ id: string;+ subject?: string | null;+ type: 'email';+ }+ | {+ id: string;+ name?: string | null;+ type: 'channel';+ }+ )[];+ summary: string;}/* eslint-disable */diff --git a/justfile b/justfileindex cd1c87a29d..5a4ccf1176 100644--- a/justfile+++ b/justfile@@ -15,7 +15,7 @@ fix_environment *ARGS:get_environment *ARGS:sops --input-type dotenv --output-type dotenv -d .env-local{{ ARGS }}.enc > .env-# Creates the docker networks then runs the databases+# Creates the docker networks then runs the databases# This is used when initializing your databasesrun_dbs *ARGS:just create_networks@@ -36,7 +36,7 @@ run_local *ARGS:# afterbuild_run_local *ARGS:just rust/cloud-storage/build_dev_service_images- just run_local {{ ARGS }}+ just run_local {{ ARGS }}# Stop all local servicesstop-local:diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 4761e7c362..e0ed86fcc9 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -95,10 +95,12 @@ dependencies = ["async-trait","axum","chrono",+ "comms","comms_service_client","cool_asserts","email","email_service_client",+ "frecency","lazy_static","macro_db_client","model",@@ -113,6 +115,8 @@ dependencies = ["search_service_client","serde","serde_json",+ "soup",+ "sqlx","strum","tokio","tracing",@@ -2639,6 +2643,7 @@ dependencies = ["axum","base64 0.22.1","chrono",+ "comms","comms_service_client","connection_gateway","cookie",@@ -2646,7 +2651,9 @@ dependencies = ["document_cognition_service_client","document_storage_service_client","doppleganger",+ "email","email_service_client",+ "frecency","futures","http-body-util","lazy_static",@@ -2675,6 +2682,7 @@ dependencies = ["secretsmanager_client","serde","serde_json",+ "soup","sqlx","sqs_client","static_file_service_client",@@ -2923,12 +2931,6 @@ dependencies = ["unsynn",]-[[package]]-name = "dotenv"-version = "0.15.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"-[[package]]name = "dotenvy"version = "0.15.7"@@ -4997,7 +4999,7 @@ dependencies = [name = "macro_entrypoint"version = "0.1.0"dependencies = [- "dotenv",+ "dotenvy","macro_env","tracing","tracing-panic",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex abdbcab4e1..d1d7c0fa51 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -145,7 +145,7 @@ clap = { version = "4.5.20", features = ["derive"] }cloudfront_sign = "0.3.0"cookie = "0.18.1"dashmap = "6.1.0"-dotenv = "0.15.0"+dotenvy = "0.15.7"ego-tree = "0.6.2"either = "1"futures = "0.3.31"diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 00ecb245c1..3aac7a7f25 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -11,9 +11,11 @@ anyhow.workspace = trueasync-trait.workspace = trueaxum = { workspace = true, features = ["macros"] }chrono.workspace = true+comms = { path = "../comms", features = ["outbound"] }comms_service_client = { path = "../comms_service_client" }-email = { path = "../email", features = ["ai_schema", "axum"] }+email = { path = "../email", features = ["ai_schema", "axum", "outbound"] }email_service_client = { path = "../email_service_client" }+frecency = { path = "../frecency", features = ["outbound", "postgres"] }lazy_static.workspace = truemacro_db_client = { path = "../macro_db_client" }model = { path = "../model" }@@ -34,6 +36,8 @@ scribe = { path = "../scribe", features = [search_service_client = { path = "../search_service_client" }serde.workspace = trueserde_json.workspace = true+soup = { path = "../soup", features = ["ai_tools", "outbound"] }+sqlx.workspace = truestrum.workspace = truetokio.workspace = truetracing.workspace = truediff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 7b887d7692..ea12d83ffc 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -1,7 +1,6 @@use ai_toolset::AsyncToolSet;use ai_toolset::schema::{ToolSchemaGenerator, ToolSchemas};pub mod code_execution;-pub mod list;pub mod prompts;pub mod read;#[allow(dead_code)]@@ -13,14 +12,13 @@ use code_execution::{anthropic_bash_code_execution_tool, anthropic_text_editor_code_execution_tool,};use search::web::anthropic_web_search::anthropic_web_search_tool;+use soup::inbound::toolset::{ListEntities, SoupToolContext};use std::sync::Arc;use web_fetch::anthropic_web_fetch_tool;pub use search::search_toolset;pub use tool_context::*;-use crate::list::list_toolset;-pub type AiToolSet = AsyncToolSet<ToolServiceContext>;pub struct ToolSetWithPrompt {@@ -39,8 +37,10 @@ pub fn all_tools() -> ToolSetWithPrompt {let toolset = AsyncToolSet::new().add_toolset(search_toolset()).expect("failed to add search toolset")- .add_toolset(list_toolset())- .expect("failed to add list toolset")+ // .add_toolset(list_toolset())+ // .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");let prompt = prompts::TOOLS_PROMPT;diff --git a/rust/cloud-storage/ai_tools/src/list/channel/mod.rs b/rust/cloud-storage/ai_tools/src/list/channel/mod.rsdeleted file mode 100644index 5a25088343..0000000000--- a/rust/cloud-storage/ai_tools/src/list/channel/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-#[cfg(test)]-mod test;-mod tool;--pub use tool::*;diff --git a/rust/cloud-storage/ai_tools/src/list/channel/test.rs b/rust/cloud-storage/ai_tools/src/list/channel/test.rsdeleted file mode 100644index 56ffa57767..0000000000--- a/rust/cloud-storage/ai_tools/src/list/channel/test.rs+++ /dev/null@@ -1,38 +0,0 @@-use super::*;-use ai_toolset::generate_tool_input_schema;-use ai_toolset::tool_object::validate_tool_schema;--#[test]-fn test_list_channels_schema_validation() {- let schema = generate_tool_input_schema!(ListChannels);-- let result = validate_tool_schema(&schema);- assert!(result.is_ok(), "{:?}", result);-- let (name, description) = result.unwrap();- assert_eq!(- name, "ListChannels",- "Tool name should match the schemars title"- );- assert!(- description.contains("List all chat channels"),- "Description should contain expected text"- );-}--// run `cargo test -p ai_tools list::channel::test::print_input_schema -- --nocapture --include-ignored`-#[test]-#[ignore = "prints the input schema"]-fn print_input_schema() {- let schema = generate_tool_input_schema!(ListChannels);- println!("{}", serde_json::to_string_pretty(&schema).unwrap());-}--// run `cargo test -p ai_tools list::channel::test::print_output_schema -- --nocapture --include-ignored`-#[test]-#[ignore = "prints the output schema"]-fn print_output_schema() {- let generator = ai_toolset::tool_object::minimized_output_schema_generator();- let schema = generator.into_root_schema_for::<ListChannelsResponse>();- println!("{}", serde_json::to_string_pretty(&schema).unwrap());-}diff --git a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs b/rust/cloud-storage/ai_tools/src/list/channel/tool.rsdeleted file mode 100644index c4e8ca6d07..0000000000--- a/rust/cloud-storage/ai_tools/src/list/channel/tool.rs+++ /dev/null@@ -1,82 +0,0 @@-use crate::tool_context::ToolScribe;-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};-use async_trait::async_trait;-use model::comms::ChannelType;-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};-use std::sync::Arc;-use uuid::Uuid;--/// A channel item returned by the list channels tool-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(rename_all = "camelCase")]-pub struct ChannelListItem {- /// The channel's unique identifier- pub id: Uuid,- /// The channel's display name (may be None for direct messages)- pub name: Option<String>,- /// The type of channel (public, private, organization, or direct_message)- pub channel_type: ChannelType,-}--/// Response from listing channels-#[derive(Debug, JsonSchema, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ListChannelsResponse {- /// The list of channels the user has access to- pub channels: Vec<ChannelListItem>,- /// Total number of channels returned- pub total: usize,-}--/// List channels tool - lists all channels the user has access to-#[derive(Debug, JsonSchema, Deserialize, Clone)]-#[serde(rename_all = "camelCase")]-#[schemars(- description = "List all chat channels the user has access to. Returns channel names, IDs, and types. Use this tool to discover available channels for reading messages or participating in conversations.",- title = "ListChannels"-)]-pub struct ListChannels {- #[serde(default)]- _unused: (),-}--#[async_trait]-impl AsyncTool<Arc<ToolScribe>> for ListChannels {- type Output = ListChannelsResponse;-- #[allow(deprecated)]- #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]- async fn call(- &self,- scribe: ServiceContext<Arc<ToolScribe>>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- tracing::info!("List channels");-- let channels = scribe- .channel- .list_channels(&request_context.jwt)- .await- .map_err(|e| ToolCallError {- description: format!("failed to list channels: {}", e),- internal_error: e,- })?;-- let channel_items: Vec<ChannelListItem> = channels- .into_iter()- .map(|c| ChannelListItem {- id: c.id.0,- name: c.name,- channel_type: c.channel_type,- })- .collect();-- let total = channel_items.len();-- Ok(ListChannelsResponse {- channels: channel_items,- total,- })- }-}diff --git a/rust/cloud-storage/ai_tools/src/list/email/mod.rs b/rust/cloud-storage/ai_tools/src/list/email/mod.rsdeleted file mode 100644index 6034a6c590..0000000000--- a/rust/cloud-storage/ai_tools/src/list/email/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod tool;-pub use tool::ListEmails;--#[cfg(test)]-mod tests;diff --git a/rust/cloud-storage/ai_tools/src/list/email/tests.rs b/rust/cloud-storage/ai_tools/src/list/email/tests.rsdeleted file mode 100644index b03706f726..0000000000--- a/rust/cloud-storage/ai_tools/src/list/email/tests.rs+++ /dev/null@@ -1,118 +0,0 @@-use super::tool::*;-use ai_toolset::generate_tool_input_schema;-use ai_toolset::tool_object::validate_tool_schema;-use cool_asserts::assert_matches;-use email::inbound::ApiPaginatedThreadCursor;-use models_email::service::thread::PreviewViewStandardLabel;--// run `cargo test -p ai_tools list::email::tests::print_input_schema -- --nocapture --include-ignored`-#[test]-#[ignore = "prints the input schema"]-fn print_input_schema() {- let schema = generate_tool_input_schema!(ListEmails);- println!("{}", serde_json::to_string_pretty(&schema).unwrap());-}--// run `cargo test -p ai_tools list::email::tests::print_output_schema -- --nocapture --include-ignored`-#[test]-#[ignore = "prints the output schema"]-fn print_output_schema() {- let generator = ai_toolset::tool_object::minimized_output_schema_generator();- let schema = generator.into_root_schema_for::<ApiPaginatedThreadCursor>();- println!("{}", serde_json::to_string_pretty(&schema).unwrap());-}--#[test]-fn test_list_emails_schema_validation() {- let schema = generate_tool_input_schema!(ListEmails);-- // Test using the actual validate_tool_schema function- let result = validate_tool_schema(&schema);- assert!(result.is_ok(), "{:?}", result);-- let (name, ..) = result.unwrap();- assert_eq!(- name, "ListEmails",- "Tool name should match the schemars title"- );-}--#[test]-fn it_iterates_defaults() {- let data = ListEmails {- view: ViewSelection::default(),- limit: default_limit(),- cursor: None,- sort_method: default_sort_method(),- };- let params: Vec<_> = data.iter_params().collect();- assert_matches!(params, [("limit", l), ("sort_method", s)] => {- assert_eq!(l, "20");- assert_eq!(s, "viewed_at");- });-}--#[test]-fn it_iterates_limit() {- let data = ListEmails {- view: ViewSelection::default(),- limit: 420,- cursor: None,- sort_method: default_sort_method(),- };- let params: Vec<_> = data.iter_params().collect();- assert_matches!(params, [("limit", l), ("sort_method", s)] => {- assert_eq!(l, "420");- assert_eq!(s, "viewed_at");- });-}--#[test]-fn it_iterates_cursor() {- let data = ListEmails {- view: ViewSelection::default(),- limit: default_limit(),- cursor: Some("some_cursor".to_string()),- sort_method: default_sort_method(),- };- let params: Vec<_> = data.iter_params().collect();- assert_matches!(params, [("limit", l), ("cursor", c), ("sort_method", s)] => {- assert_eq!(l, "20");- assert_eq!(c, "some_cursor");- assert_eq!(s, "viewed_at");- });-}--#[test]-fn it_iterates_sort() {- let data = ListEmails {- view: ViewSelection::default(),- limit: default_limit(),- cursor: None,- sort_method: ApiSortMethod::CreatedAt,- };- let params: Vec<_> = data.iter_params().collect();- assert_matches!(params, [("limit", l), ("sort_method", s)] => {- assert_eq!(l, "20");- assert_eq!(s, "created_at");- });-}--#[test]-fn it_iterates_all() {- let data = ListEmails {- view: ViewSelection {- standard_label: Some(PreviewViewStandardLabel::Inbox),- user_label: None,- },- limit: 420,- cursor: Some("some_cursor".to_string()),- sort_method: ApiSortMethod::CreatedAt,- };- let params: Vec<_> = data.iter_params().collect();- assert_matches!(params, [("limit", l), ("cursor", c), ("sort_method", s)] => {- assert_eq!(l, "420");- assert_eq!(c, "some_cursor");- assert_eq!(s, "created_at");- });-}diff --git a/rust/cloud-storage/ai_tools/src/list/email/tool.rs b/rust/cloud-storage/ai_tools/src/list/email/tool.rsdeleted file mode 100644index ffe938774e..0000000000--- a/rust/cloud-storage/ai_tools/src/list/email/tool.rs+++ /dev/null@@ -1,131 +0,0 @@-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};-use async_trait::async_trait;-use email::inbound::ApiPaginatedThreadCursor;-use email_service_client::EmailServiceClientExternal;-use models_email::{- email::service::thread::PreviewView, service::thread::PreviewViewStandardLabel,-};-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};-use std::borrow::Cow;-use std::sync::Arc;--#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]-#[serde(rename_all = "camelCase")]-#[schemars(- description = "Choose the view to list emails from. One of either standard label or user label must be specified, otherwise defaults to important."-)]-pub struct ViewSelection {- #[schemars(description = "Prefer important or all. Leave empty if using a user label")]- pub standard_label: Option<PreviewViewStandardLabel>,- #[schemars(- description = "Choose a custom user label to filter by (optional). Standard label will take precedence over user label if both are specified."- )]- pub user_label: Option<String>,-}--#[derive(Debug, Serialize, Deserialize, JsonSchema)]-#[serde(rename_all = "camelCase")]-#[schemars(- description = "List the emails the user has access to. Use this tool to find all emails from / to a specific person. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",- title = "ListEmails"-)]-pub struct ListEmails {- #[serde(default)]- pub view: ViewSelection,- #[schemars(- description = "limit the max emails returned. This defaults to 20 and has a maximum of 500"- )]- #[serde(default = "default_limit")]- pub limit: i64,- #[schemars(- description = "A preview response will tell you what the next cursor id is.- If expected emails are not in the current response and it gives you a cursor id, use this field to list the next page of emails. If no cursor id is provided you've reached the end"- )]- #[serde(default)]- pub cursor: Option<String>,- #[schemars(- description = "Sort response by one of: viewed_at | updated_at | created_at | viewed_updated. Prefer viewed_at unless the otherwise specified"- )]- #[serde(default = "default_sort_method")]- pub sort_method: ApiSortMethod,-}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]-#[serde(rename_all = "snake_case")]-pub enum ApiSortMethod {- ViewedAt,- UpdatedAt,- CreatedAt,- ViewedUpdated,-}--pub fn default_view() -> PreviewView {- PreviewView::StandardLabel(PreviewViewStandardLabel::Important)-}--pub fn default_limit() -> i64 {- 20-}--pub fn default_sort_method() -> ApiSortMethod {- ApiSortMethod::ViewedAt-}--impl ListEmails {- /// get the query string parameters contained within self as an iterator over KV pairs- pub fn iter_params(&self) -> impl Iterator<Item = (&'static str, Cow<'_, str>)> {- std::iter::once(("limit", Cow::Owned(self.limit.to_string())))- .chain(- self.cursor- .iter()- .map(|v| ("cursor", Cow::Borrowed(v.as_ref()))),- )- .chain(std::iter::once((- "sort_method",- Cow::Owned(- serde_json::to_string(&self.sort_method)- .expect("infallible")- .trim_matches('"')- .to_string(),- ),- )))- }-}--#[async_trait]-impl AsyncTool<Arc<EmailServiceClientExternal>> for ListEmails {- type Output = ApiPaginatedThreadCursor;-- #[allow(deprecated)]- #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]- async fn call(- &self,- email_client: ServiceContext<Arc<EmailServiceClientExternal>>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- tracing::info!(self=?self, "List emails params");-- // builds the preview view based on the view selection- // prefer standard label over user label if both are specified- let view = self- .view- .standard_label- .as_ref()- .map(|label| PreviewView::StandardLabel(label.clone()))- .or(self- .view- .user_label- .as_ref()- .map(|label| PreviewView::UserLabel(label.clone())))- .unwrap_or(default_view());-- email_client- .get_thread_previews_external(self.iter_params(), view, &request_context.jwt)- .await- .map_err(|err| ToolCallError {- description: format!("something went wrong fetching emails {:?}", err),- internal_error: err,- })- }-}diff --git a/rust/cloud-storage/ai_tools/src/list/file.rs b/rust/cloud-storage/ai_tools/src/list/file.rsdeleted file mode 100644index 610c1c3ac6..0000000000--- a/rust/cloud-storage/ai_tools/src/list/file.rs+++ /dev/null@@ -1,345 +0,0 @@-use crate::tool_context::ToolScribe;-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};-use async_trait::async_trait;-use model::document::list::DocumentListItem;-use models_permissions::share_permission::access_level::AccessLevel;-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};-use std::cmp::min;-use std::sync::Arc;--/// Maximum number of results to return to the AI client-const TRUNCATED_RESULTS_LIMIT: usize = 150;--/// Default page size when not specified-const DEFAULT_PAGE_SIZE: i64 = 50;--/// Maximum allowed page size-const MAX_PAGE_SIZE: i64 = 1000;--fn default_page_size() -> i64 {- DEFAULT_PAGE_SIZE-}--#[derive(Debug, JsonSchema, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ListDocumentsResponse {- /// The list results (truncated to `results_returned` limit if applicable)- pub results: Vec<DocumentListItem>,- /// Total number of results found- pub total_results: usize,- /// The number of results returned- pub results_returned: usize,-}--#[derive(Debug, JsonSchema, Deserialize, Clone)]-#[serde(rename_all = "camelCase")]-#[schemars(- description = "List documents the user has access to with optional filtering and pagination. Only applies to documents, not emails, AI conversations, chat/slack threads, projects aka folders. This tool returns document metadata including access levels and supports filtering by file type, minimum access level, and pagination. Use this tool to discover and browse documents before using the Read tool to access their content. Prefer using the search tool to search on a specific matching string within the content or the name of the entity.",- title = "ListDocuments"-)]-pub struct ListDocuments {- #[schemars(- description = "Document file types to include. Examples: ['pdf'], ['md', 'txt']. Leave empty to include all document types."- )]- pub file_types: Option<Vec<String>>,-- #[schemars(- description = "Minimum access level required. Defaults to 'view' if not specified."- )]- pub min_access_level: Option<AccessLevel>,-- #[schemars(- description = "Page offset for pagination. Default is 0. Use higher values to get subsequent pages of results."- )]- #[serde(default)]- pub page_offset: i64,-- #[schemars(- description = "Number of results per page. Max is 100, default is 50. Use smaller values for focused results."- )]- #[serde(default = "default_page_size")]- pub page_size: i64,-- #[schemars(- description = "Exhaustive search to get all results. Defaults to false. Set to true when you need all matching documents, ignoring pagination limits."- )]- #[serde(default)]- pub exhaustive_search: bool,-}--impl Default for ListDocuments {- fn default() -> Self {- Self {- file_types: None,- min_access_level: None,- page_offset: 0,- page_size: DEFAULT_PAGE_SIZE,- exhaustive_search: false,- }- }-}--impl ListDocuments {- fn validate_pagination(&self) -> Result<(i64, i64), ToolCallError> {- // Validate page_offset- if self.page_offset < 0 {- return Err(ToolCallError {- description: "page_offset must be greater than or equal to 0".to_string(),- internal_error: anyhow::anyhow!("page_offset must be greater than or equal to 0"),- });- }-- // Validate and set page_size- let page_size = if self.page_size <= 0 {- DEFAULT_PAGE_SIZE- } else if self.page_size > MAX_PAGE_SIZE {- return Err(ToolCallError {- description: format!("page_size must be less than or equal to {}", MAX_PAGE_SIZE),- internal_error: anyhow::anyhow!(format!(- "page_size must be less than or equal to {}",- MAX_PAGE_SIZE- )),- });- } else {- self.page_size- };-- Ok((page_size, self.page_offset))- }-- async fn fetch_all_pages(- &self,- scribe: &ToolScribe,- request_context: &RequestContext,- min_access_level: AccessLevel,- page_size: i64,- ) -> Result<Vec<DocumentListItem>, ToolCallError> {- let mut all_results = vec![];- let mut page_offset = 0;-- loop {- let page = page_offset / page_size;- let response = scribe- .document- .dss_client- .list_documents_with_access(- (*request_context.user_id).as_ref(),- self.file_types.clone(),- Some(min_access_level),- page,- page_size,- )- .await- .map_err(|e| ToolCallError {- description: format!("failed to list documents: {}", e),- internal_error: e,- })?;-- let result_count = response.documents.len();- tracing::debug!(page_offset, result_count, "exhaustive search: fetched page");-- if result_count == 0 {- break;- }-- all_results.extend(response.documents);-- // If we got fewer results than requested, we've reached the end- if (result_count as i64) < page_size {- break;- }-- page_offset += page_size;- }-- Ok(all_results)- }-}--#[async_trait]-impl AsyncTool<Arc<ToolScribe>> for ListDocuments {- type Output = ListDocumentsResponse;-- #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]- async fn call(- &self,- scribe: ServiceContext<Arc<ToolScribe>>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- tracing::info!(self=?self, "List documents params");-- let (page_size, page_offset) = self.validate_pagination()?;- let min_access_level = self.min_access_level.unwrap_or(AccessLevel::View);-- if self.exhaustive_search {- // Use exhaustive search to get all results- return match self- .fetch_all_pages(&scribe, &request_context, min_access_level, page_size)- .await- {- Ok(all_results) => {- let total_results = all_results.len();- let results_returned = min(total_results, TRUNCATED_RESULTS_LIMIT);- let results = if results_returned < total_results {- all_results.into_iter().take(results_returned).collect()- } else {- all_results- };-- let tool_response = ListDocumentsResponse {- results,- total_results,- results_returned,- };-- tracing::debug!(- "exhaustive search returned {results_returned} results of {total_results}"- );- ToolResult::Ok(tool_response)- }- Err(e) => ToolResult::Err(e),- };- }-- // Non-exhaustive search - single page- let page = page_offset / page_size;- match scribe- .document- .dss_client- .list_documents_with_access(- (*request_context.user_id).as_ref(),- self.file_types.clone(),- Some(min_access_level),- page,- page_size,- )- .await- {- Ok(response) => {- let tool_response = ListDocumentsResponse {- results: response.documents,- total_results: response.results_returned,- results_returned: response.results_returned,- };-- tracing::debug!(- "list documents returned {} results",- response.results_returned- );- ToolResult::Ok(tool_response)- }- Err(e) => {- tracing::warn!("List documents failed with error: {}", e);- Err(ToolCallError {- description: format!("failed to list documents: {}", e),- internal_error: e,- })- }- }- }-}--#[cfg(test)]-mod tests {- use super::*;- use ai_toolset::generate_tool_input_schema;- use ai_toolset::tool_object::validate_tool_schema;-- // run `cargo test -p ai_tools list::file::tests::print_input_schema -- --nocapture --include-ignored`- #[test]- #[ignore = "prints the input schema"]- fn print_input_schema() {- let schema = generate_tool_input_schema!(ListDocuments);- println!("{}", serde_json::to_string_pretty(&schema).unwrap());- }-- // run `cargo test -p ai_tools list::file::tests::print_output_schema -- --nocapture --include-ignored`- #[test]- #[ignore = "prints the output schema"]- fn print_output_schema() {- let generator = ai_toolset::tool_object::minimized_output_schema_generator();- let schema = generator.into_root_schema_for::<ListDocumentsResponse>();- println!("{}", serde_json::to_string_pretty(&schema).unwrap());- }-- #[test]- fn test_list_documents_schema_validation() {- let schema = generate_tool_input_schema!(ListDocuments);-- // Test using the actual validate_tool_schema function- let result = validate_tool_schema(&schema);- assert!(result.is_ok(), "{:?}", result);-- let (name, description) = result.unwrap();- assert_eq!(- name, "ListDocuments",- "Tool name should match the schemars title"- );- assert!(- description.contains("List documents the user has access to"),- "Description should contain expected text"- );- }-- #[test]- fn test_validate_pagination() {- // Test valid parameters- let list_docs = ListDocuments {- file_types: Some(vec!["pdf".to_string()]),- min_access_level: Some(AccessLevel::Edit),- page_offset: 0,- page_size: 50,- exhaustive_search: false,- };-- let result = list_docs.validate_pagination();- assert!(result.is_ok());- let (page_size, page_offset) = result.unwrap();- assert_eq!(page_size, 50);- assert_eq!(page_offset, 0);-- // Test invalid page_size (too large)- let invalid_page_size = ListDocuments {- page_size: 2000,- ..Default::default()- };- assert!(invalid_page_size.validate_pagination().is_err());-- // Test negative page_offset- let invalid_offset = ListDocuments {- page_offset: -1,- ..Default::default()- };- assert!(invalid_offset.validate_pagination().is_err());-- // Test zero page_size (should use default)- let zero_page_size = ListDocuments {- page_size: 0,- ..Default::default()- };- let result = zero_page_size.validate_pagination();- assert!(result.is_ok());- let (page_size, _) = result.unwrap();- assert_eq!(page_size, DEFAULT_PAGE_SIZE);-- // Test negative page_size (should use default)- let negative_page_size = ListDocuments {- page_size: -10,- ..Default::default()- };- let result = negative_page_size.validate_pagination();- assert!(result.is_ok());- let (page_size, _) = result.unwrap();- assert_eq!(page_size, DEFAULT_PAGE_SIZE);- }- #[test]- fn test_default_values() {- let list_docs = ListDocuments::default();- assert_eq!(list_docs.file_types, None);- assert_eq!(list_docs.min_access_level, None);- assert_eq!(list_docs.page_offset, 0);- assert_eq!(list_docs.page_size, DEFAULT_PAGE_SIZE);- assert!(!list_docs.exhaustive_search);- }-}diff --git a/rust/cloud-storage/ai_tools/src/list/mod.rs b/rust/cloud-storage/ai_tools/src/list/mod.rsdeleted file mode 100644index 0d2619fe53..0000000000--- a/rust/cloud-storage/ai_tools/src/list/mod.rs+++ /dev/null@@ -1,15 +0,0 @@-use crate::AiToolSet;-use ai_toolset::AsyncToolSet;-mod channel;-mod email;-mod file;--pub fn list_toolset() -> AiToolSet {- AsyncToolSet::new()- .add_tool::<channel::ListChannels, _>()- .expect("failed to add list channels")- .add_tool::<email::ListEmails, _>()- .expect("failed to add list email")- .add_tool::<file::ListDocuments, _>()- .expect("failed to add list documents")-}diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex f70bb1174c..c7489516c6 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -1,8 +1,18 @@use axum::extract::FromRef;+use comms::{+ domain::service::ChannelServiceImpl,+ outbound::{http::user_repo::UserRepoImpl, postgres::comms_repo::PgCommsRepo},+};+use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};use scribe::{ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,email::EmailClient, static_file::StaticFileClient,};+use soup::{+ domain::service::SoupImpl, inbound::toolset::SoupToolContext,+ outbound::pg_soup_repo::PgSoupRepo,+};use std::sync::Arc;pub use ai_toolset::RequestContext;@@ -10,6 +20,19 @@ pub use ai_toolset::RequestContext;pub type ToolScribe =ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;+/// Type alias for the frecency service implementation+pub type ToolFrecencyService = FrecencyQueryServiceImpl<FrecencyPgStorage>;++/// Type alias for the email service implementation+pub type ToolEmailService = EmailServiceImpl<EmailPgRepo, ToolFrecencyService>;++/// Type alias for the comms/channels service implementation+pub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, UserRepoImpl, FrecencyPgStorage>;++/// Type alias for the soup service implementation+pub type ToolSoupService =+ SoupImpl<PgSoupRepo, ToolFrecencyService, ToolEmailService, ToolCommsService>;+/// The full service context containing all API clients./// Individual tools should extract only the clients they need via `FromRef`.#[derive(Clone, FromRef)]@@ -17,6 +40,7 @@ pub struct ToolServiceContext {pub search_service_client: Arc<search_service_client::SearchServiceClient>,pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,pub scribe: Arc<ToolScribe>,+ pub soup_service: Arc<ToolSoupService>,}impl FromRef<ToolServiceContext> for ai_toolset::NoContext {@@ -24,3 +48,11 @@ impl FromRef<ToolServiceContext> for ai_toolset::NoContext {ai_toolset::NoContext()}}++impl FromRef<ToolServiceContext> for SoupToolContext<ToolSoupService> {+ fn from_ref(ctx: &ToolServiceContext) -> Self {+ SoupToolContext {+ service: ctx.soup_service.clone(),+ }+ }+}diff --git a/rust/cloud-storage/comms/src/outbound/http/user_repo.rs b/rust/cloud-storage/comms/src/outbound/http/user_repo.rsindex a6b58bf30d..5351e4ce38 100644--- a/rust/cloud-storage/comms/src/outbound/http/user_repo.rs+++ b/rust/cloud-storage/comms/src/outbound/http/user_repo.rs@@ -50,7 +50,9 @@ impl UserRepo for UserRepoImpl {let mut url = self.url.as_ref().clone();url.set_path("/internal/get_names");- let res = self.client.post(url).json(&body).send().await?;+ let res = self.client.post(url).json(&body).send().await.inspect_err(+ |e| tracing::error!(error=?e, "failed to get names from authentication service"),+ )?;match res.status() {reqwest::StatusCode::OK => {diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex c2e8ad7112..25e3f632da 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -35,6 +35,7 @@ aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log", "ws"] }base64 = { workspace = true }chrono = { workspace = true }+comms = { path = "../comms", features = ["outbound"] }comms_service_client = { path = "../comms_service_client" }connection_gateway = { path = "../connection_gateway" }cookie = { workspace = true }@@ -42,7 +43,9 @@ dashmap = { workspace = true }document_cognition_service_client = { path = "../document_cognition_service_client" }document_storage_service_client = { path = "../document_storage_service_client" }doppleganger = { workspace = true }+email = { path = "../email", features = ["outbound"] }email_service_client = { path = "../email_service_client" }+frecency = { path = "../frecency", features = ["outbound", "postgres"] }futures = { workspace = true }http-body-util = { workspace = true }lazy_static = { workspace = true }@@ -81,6 +84,7 @@ search_service_client = { path = "../search_service_client" }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }+soup = { path = "../soup", features = ["outbound"] }sqlx = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = ["chat",diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rsindex 8d9b5f8ede..281cf7ef28 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs@@ -1,4 +1,5 @@use crate::config::Config;+use ai_tools::ToolSoupService;use axum::extract::FromRef;use document_storage_service_client::DocumentStorageServiceClient;use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -28,6 +29,7 @@ pub struct ApiContext {pub jwt_args: JwtValidationArgs,pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,+ pub soup_service: Arc<ToolSoupService>,}pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();@@ -35,14 +37,23 @@ pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();#[cfg(test)]pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {use aws_sdk_sqs;+ use comms::domain::service::ChannelServiceImpl;+ use comms::outbound::http::user_repo::UserRepoImpl;+ use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms_service_client::CommsServiceClient;use document_cognition_service_client::DocumentCognitionServiceClient;use document_storage_service_client::DocumentStorageServiceClient;+ use email::domain::service::EmailServiceImpl;+ use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};+ use frecency::domain::services::FrecencyQueryServiceImpl;+ use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;use macro_notify::MacroNotifyClient;use scribe::ScribeClient;use search_service_client::SearchServiceClient;+ use soup::domain::service::SoupImpl;+ use soup::outbound::pg_soup_repo::PgSoupRepo;use sqs_client::SQS;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;@@ -105,6 +116,24 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar.with_email_client(email_service_client).with_static_file_client(static_file_service_client.clone());+ // Build soup service dependencies+ let frecency_storage = FrecencyPgStorage::new(pool.clone());+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let email_service =+ EmailServiceImpl::new(EmailPgRepo::new(pool.clone()), frecency_service.clone());+ let user_repo = UserRepoImpl::new("dummy_auth_key".into(), "http://localhost".parse().unwrap());+ let channels_service = ChannelServiceImpl::new(+ PgCommsRepo { pool: pool.clone() },+ user_repo,+ frecency_storage,+ );+ let soup_service = Arc::new(SoupImpl::new(+ PgSoupRepo::new(pool.clone()),+ frecency_service,+ email_service,+ channels_service,+ ));+let api_context = ApiContext {db: pool.clone(),sqs_client: Arc::new(sqs_client),@@ -117,6 +146,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arjwt_args: JwtValidationArgs::new_testing(),config: Arc::new(Config::new_empty_for_test()),internal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime("testing")),+ soup_service,};Arc::new(api_context)}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rsindex 773368e742..284a4d839d 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs@@ -111,6 +111,7 @@ pub async fn stream_chat_response(email_service_client: context.email_service_client_external.clone(),search_service_client: context.search_service_client.clone(),scribe: context.scribe.clone(),+ soup_service: context.soup_service.clone(),};#[expect(deprecated)]diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rsindex 5d4bf40f29..ddddc6de59 100644--- a/rust/cloud-storage/document_cognition_service/src/config.rs+++ b/rust/cloud-storage/document_cognition_service/src/config.rs@@ -41,6 +41,10 @@ pub struct Config {pub document_cognition_service_url: String,/// static file service urlpub static_file_service_url: String,+ /// authentication service url (for soup service)+ pub authentication_service_url: String,+ /// authentication service secret key (for soup service)+ pub authentication_service_secret_key: String,}impl Config {@@ -82,6 +86,7 @@ impl Config {let sync_service_url =std::env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be provided")?;+let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY").context("SYNC_SERVICE_AUTH_KEY must be provided")?;@@ -99,6 +104,12 @@ impl Config {let static_file_service_url = std::env::var("STATIC_FILE_SERVICE_URL").context("STATIC_FILE_SERVICE_URL must be provided")?;+ let authentication_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")+ .context("AUTHENTICATION_SERVICE_URL must be provided")?;++ let authentication_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")+ .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;+Ok(Config {database_url,port,@@ -118,6 +129,8 @@ impl Config {email_service_url,document_cognition_service_url,static_file_service_url,+ authentication_service_url,+ authentication_service_secret_key,})}@@ -142,6 +155,8 @@ impl Config {email_service_url: Default::default(),document_cognition_service_url: Default::default(),static_file_service_url: Default::default(),+ authentication_service_url: Default::default(),+ authentication_service_secret_key: Default::default(),}}}diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 0c52135bfb..60d84226b6 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -1,16 +1,25 @@use crate::api::context::ApiContext;use anyhow::Context;+use comms::domain::service::ChannelServiceImpl;+use comms::outbound::http::user_repo::UserRepoImpl;+use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms_service_client::CommsServiceClient;use config::{Config, Environment};use document_cognition_service_client::DocumentCognitionServiceClient;use document_storage_service_client::DocumentStorageServiceClient;+use email::domain::service::EmailServiceImpl;+use email::outbound::EmailPgRepo;use email_service_client::{EmailServiceClient, EmailServiceClientExternal};+use frecency::domain::services::FrecencyQueryServiceImpl;+use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;use scribe::{ScribeClient, document::DocumentClient};use search_service_client::SearchServiceClient;use secretsmanager_client::SecretManager;+use soup::domain::service::SoupImpl;+use soup::outbound::pg_soup_repo::PgSoupRepo;use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;@@ -153,6 +162,42 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized static file service client");+ // Get auth service secret key for soup service+ let auth_service_secret_key = match config.environment {+ Environment::Local => config.authentication_service_secret_key.clone(),+ _ => secretsmanager_client+ .get_secret_value(&config.authentication_service_secret_key)+ .await+ .context("failed to get auth service secret key from secrets manager")?+ .to_string(),+ };++ // Build soup service+ let frecency_storage = FrecencyPgStorage::new(db.clone());+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let email_service =+ EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());+ let user_repo = UserRepoImpl::new(+ auth_service_secret_key,+ config+ .authentication_service_url+ .parse()+ .context("AUTHENTICATION_SERVICE_URL must be a valid url")?,+ );+ let channels_service = ChannelServiceImpl::new(+ PgCommsRepo { pool: db.clone() },+ user_repo,+ frecency_storage,+ );+ let soup_service = Arc::new(SoupImpl::new(+ PgSoupRepo::new(db.clone()),+ frecency_service,+ email_service,+ channels_service,+ ));++ tracing::info!("initialized soup service");+api::setup_and_serve(ApiContext {db: db.clone(),email_service_client_external: Arc::new(EmailServiceClientExternal::new(@@ -181,6 +226,7 @@ async fn main() -> anyhow::Result<()> {jwt_args,config: Arc::new(config),internal_auth_key,+ soup_service,}).await.context("failed to setup and serve api")?;diff --git a/rust/cloud-storage/macro_entrypoint/Cargo.toml b/rust/cloud-storage/macro_entrypoint/Cargo.tomlindex 11a2888389..68aa7163d3 100644--- a/rust/cloud-storage/macro_entrypoint/Cargo.toml+++ b/rust/cloud-storage/macro_entrypoint/Cargo.toml@@ -5,7 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]-dotenv = { workspace = true }+dotenvy = { workspace = true }macro_env = { path = "../macro_env" }tracing = { workspace = true }tracing-panic = "0.1"diff --git a/rust/cloud-storage/macro_entrypoint/src/lib.rs b/rust/cloud-storage/macro_entrypoint/src/lib.rsindex a564283e8d..18923646ee 100644--- a/rust/cloud-storage/macro_entrypoint/src/lib.rs+++ b/rust/cloud-storage/macro_entrypoint/src/lib.rs@@ -38,7 +38,8 @@ impl MacroEntrypoint {/// consume self, initialize this binary, and return a proof that it was initialized [InitializedEntrypoint]pub fn init(self) -> InitializedEntrypoint {- dotenv::dotenv().ok();+ // Load .env file if it exists, but don't fail if it doesn't+ let _ = dotenvy::dotenv();std::panic::set_hook(Box::new(tracing_panic::panic_hook));match (self.env, self.local) {diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex 4428adc67b..dda3f3a27e 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -5,12 +5,24 @@ publish = falseversion = "0.1.0"[features]+all = [+ "ai_tools",+ "axum",+ "inbound",+ "outbound",+ "ports",+]ai_tools = ["dep:ai","dep:async-trait","dep:schemars","models_soup/schema","ports",+ "outbound",+ "frecency/outbound",+ "frecency/postgres",+ "email/outbound",+ "comms/outbound",]axum = ["dep:axum",@@ -77,3 +89,8 @@ rootcause = { workspace = true }serde_json = { workspace = true }tokio = { workspace = true }tower = { workspace = true }+ai = { path = "../ai" }++[[example]]+name = "ai_tools_cli"+required-features = ["all"]diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rsnew file mode 100644index 0000000000..daa802cbdf--- /dev/null+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs@@ -0,0 +1,87 @@+//! CLI example for testing soup AI tools interactively.+//!+//! This example creates a CLI interface to test the soup toolset with real database connections.+//!+//! # Usage+//!+//! ```bash+//! DATABASE_URL=postgres://...+//! ANTHROPIC_API_KEY=sk_abcdefl...+//! LOCAL_USER_ID=macro|<email>+//! cargo run --example ai_tools_cli --features all+//! ```++use ai::tool::tool_loop::cli::Cli;+use ai::tool::types::RequestContext;+use ai::types::Model;+use comms::domain::service::ChannelServiceImpl;+use comms::outbound::postgres::comms_repo::PgCommsRepo;+use comms::outbound::postgres::user_repo::PgUserRepo;+use email::domain::service::EmailServiceImpl;+use email::outbound::EmailPgRepo;+use frecency::domain::services::FrecencyQueryServiceImpl;+use frecency::outbound::postgres::FrecencyPgStorage;+use macro_user_id::user_id::MacroUserIdStr;+use soup::domain::service::SoupImpl;+use soup::inbound::toolset::{SoupToolContext, soup_toolset};+use soup::outbound::pg_soup_repo::PgSoupRepo;+use sqlx::PgPool;+use std::sync::Arc;++#[tokio::main]+async fn main() {+ // Get database URL from environment+ let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");+ let usr = std::env::var("LOCAL_USER_ID").expect("LOCAL_USER_ID must bes set");+ let user_id: MacroUserIdStr<'static> = usr.try_into().expect("valid user id macro|<email>");++ println!(+ "Running with\nuser [{}]\ndatabase [{}]",+ user_id, database_url+ );++ // Connect to the database+ let pool = PgPool::connect(&database_url)+ .await+ .expect("Failed to connect to database");++ // Create the frecency service (shared by multiple services)+ let frecency_storage = FrecencyPgStorage::new(pool.clone());+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());++ // Create the email service with real database connections+ let email_repo = EmailPgRepo::new(pool.clone());+ let email_service = EmailServiceImpl::new(email_repo, frecency_service.clone());++ // Create the channels service with real database connections+ let comms_repo = PgCommsRepo { pool: pool.clone() };+ let user_repo = PgUserRepo::new(pool.clone());+ let channels_service = ChannelServiceImpl::new(comms_repo, user_repo, frecency_storage);++ // Create the soup service with real database connections+ let soup_repo = PgSoupRepo::new(pool);+ let soup_service = SoupImpl::new(soup_repo, frecency_service, email_service, channels_service);++ // Create the soup tool context+ let soup_context = SoupToolContext::new(soup_service);++ // Create the soup toolset+ let toolset = soup_toolset();++ let context = RequestContext {+ user_id: Arc::new(user_id),+ jwt: Arc::new(String::new()),+ };++ // Create the CLI+ let cli = Cli::new(+ toolset,+ soup_context,+ "You are an assistant that helps users explore and manage their documents, projects, and other entities. Use the available tools to list and find entities.",+ Model::Claude45Haiku,+ move || context.clone(),+ );++ // Run the CLI+ cli.run().await;+}diff --git a/rust/cloud-storage/soup/src/inbound/toolset/mod.rs b/rust/cloud-storage/soup/src/inbound/toolset/mod.rsindex f6d5e61c7e..f880c72bdb 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/mod.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/mod.rs@@ -12,12 +12,12 @@ use std::sync::Arc;pub use list_entities::{EntityItem, ItemType, ListEntities, ListEntitiesResponse, SortBy};/// Service context for soup AI tools-pub struct SoupToolContext<T> {+pub struct SoupToolContext<T: SoupService> {/// The soup service instancepub service: Arc<T>,}-impl<T> Clone for SoupToolContext<T> {+impl<T: SoupService> Clone for SoupToolContext<T> {fn clone(&self) -> Self {Self {service: self.service.clone(),@@ -25,7 +25,7 @@ impl<T> Clone for SoupToolContext<T> {}}-impl<T> SoupToolContext<T> {+impl<T: SoupService> SoupToolContext<T> {/// Create a new soup tool contextpub fn new(service: T) -> Self {Self {