diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts index 9c5690678d2..134cb55b8f4 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/utils.ts @@ -158,6 +158,7 @@ export const TOOL_ICONS: Readonly> = { search_sources: Search, settings: Settings, list_workspaces: Search, + list_my_activity: Search, workspaces: Search, set_block_enabled: Pencil, set_environment_variables: Settings, diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index b74cf5df281..ad01138a124 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -5,7 +5,9 @@ import { } from '@/lib/api/contracts/knowledge/search' import { mcpJsonRpcMessageSchema } from '@/lib/api/contracts/mcp' import { + listMyActivityInputFieldsSchema, readDocumentInputSchema, + refineActivityWindow, refineSearchWorkspaceInput, searchWorkspaceInputFieldsSchema, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -64,6 +66,15 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema .strict() .superRefine(refineSearchWorkspaceInput) +/** list_my_activity as the Search MCP presents it: a date without an offset reads as UTC. */ +export const listMyActivityMcpSchema = listMyActivityInputFieldsSchema + .extend({ + startDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.startDate), + endDate: mcpDateFilter(listMyActivityInputFieldsSchema.shape.endDate), + }) + .strict() + .superRefine(refineActivityWindow) + /** * Previews a search returns when the caller sets no topK. A query across every source shares one * list among all of them, so it gets more room than a search of one source, a native query, or a diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 5ea374aff4f..2adea17f06a 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -335,6 +335,137 @@ export const readDocumentInputSchema = z.object({ ), }) +/** Days one activity listing may span, about a quarter. */ +export const MAX_ACTIVITY_WINDOW_DAYS = 92 +/** Activity entries one page returns when the caller sets no topK. */ +export const DEFAULT_ACTIVITY_TOP_K = 25 + +/** The activity filters, shared by every surface; refine with {@link refineActivityWindow}. */ +export const listMyActivityInputFieldsSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + `Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.' + ), + source: liveSearchProviderSchema + .optional() + .describe( + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.' + ), + topK: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe(`Maximum entries on this page: ${DEFAULT_ACTIVITY_TOP_K} by default.`), + cursor: z + .string() + .min(1) + .max(40_000) + .optional() + .describe( + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + ), + }) + .strict() + +/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ +export function refineActivityWindow( + input: { startDate?: string; endDate?: string; cursor?: string }, + context: z.RefinementCtx +) { + /** A continuation reads the window its signed cursor fixed, however long ago that was. */ + if (!input.startDate || !input.endDate || input.cursor) return + const start = Date.parse(input.startDate) + const end = Date.parse(input.endDate) + if (start >= end) + context.addIssue({ + code: 'custom', + path: ['endDate'], + message: 'endDate must be after startDate.', + }) + /** A later endDate reads up to now, so the span counts only up to now. */ else if ( + Math.min(end, Date.now()) - start > + MAX_ACTIVITY_WINDOW_DAYS * 86_400_000 + ) + context.addIssue({ + code: 'custom', + path: ['startDate'], + message: `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`, + }) +} + +export const listMyActivityInputSchema = + listMyActivityInputFieldsSchema.superRefine(refineActivityWindow) + +/** + * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: + * the provider to connect and the page where the caller connects it. + */ +const liveSourceStatusSchema = z.object({ + source: liveSearchProviderSchema, + accountId: z.string().optional(), + displayName: z.string().optional(), + status: z.enum(['ok', 'partial', 'not_connected', 'reconnect', 'unsupported', 'failed']), + reason: z.enum(['rate_limited', 'timeout', 'unavailable']).optional(), + retryAfterSeconds: z.number().optional(), + message: z.string().optional(), + connect: z.object({ providerId: z.string(), url: z.string() }).optional(), +}) +export type LiveSourceStatus = z.output + +/** What the person did to an item, as one activity entry reports it. */ +const activityActionSchema = z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', +]) +export type ActivityAction = z.output + +const activityItemSchema = z.object({ + /** Reads the item with read_document. */ + documentId: z.string(), + timestamp: z.string(), + source: liveSearchProviderSchema, + accountId: z.string(), + action: activityActionSchema, + title: z.string(), + url: z.string().nullable(), + container: z.string().optional(), + collaborators: z.array(z.string()), + snippet: z.string(), + /** The timestamp is the item's last update, possibly by someone else, not the person's action. */ + approximateTime: z.literal(true).optional(), +}) + +const listMyActivityResultSchema = z.object({ + window: z.object({ startDate: z.string(), endDate: z.string() }), + items: z.array(activityItemSchema), + /** More entries remain; continue with nextCursor. */ + truncated: z.boolean(), + nextCursor: z.string().optional(), + /** `complete` when every connected source that reports activity was read in full. */ + coverage: z.enum(['complete', 'partial']), + sources: z.array(liveSourceStatusSchema.extend({ itemCount: z.number().int().min(0) })), +}) +export type ListMyActivityResult = z.output + /** * Organization directory lookups. The bounds mirror the People page's search limits * (`lib/people/validation`) as literals, so the worker's generated copy stays standalone. @@ -490,6 +621,13 @@ export const assistantToolContracts = [ 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', inputSchema: listMyChatHistoryInputSchema, }, + { + id: 'list_my_activity', + route: 'sim', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + inputSchema: listMyActivityInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 4d77ebc50d8..47aa7c809c6 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -627,6 +627,7 @@ export const env = createEnv({ CHANGELOG: z.boolean().optional(), // Fallback for the `changelog` feature flag off AppConfig SIM_LINKS: z.boolean().optional(), // Fallback for the `sim-links` feature flag off AppConfig PEOPLE: z.boolean().optional(), // Fallback for the `people` feature flag off AppConfig + MY_ACTIVITY: z.boolean().optional(), // Fallback for the `my-activity` feature flag off AppConfig ORGANIZATION_ACTIVITY_ROLLUP_READS: z.boolean().optional(), // Fallback for the `organization-activity-rollup-reads` feature flag off AppConfig ACTIVITY_ROLLUP_MAINTENANCE: z.boolean().optional(), // Fallback for the `activity-rollup-maintenance` feature flag off AppConfig ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND: z.coerce.number().int().positive().optional(), // Source rows the activity rollup backfill reads per second (default 20000) diff --git a/apps/sim/lib/core/config/feature-flags.ts b/apps/sim/lib/core/config/feature-flags.ts index 2c3f643904b..0c2e3ca785d 100644 --- a/apps/sim/lib/core/config/feature-flags.ts +++ b/apps/sim/lib/core/config/feature-flags.ts @@ -76,6 +76,12 @@ const FEATURE_FLAGS = { 'Enable the organization People directory, org chart, profile imports, and directory sync. Supports organization rollout; disabled by default.', fallback: 'PEOPLE', }, + 'my-activity': { + description: + "Enable list_my_activity: the caller's own activity across their connected sources, in the " + + 'Search MCP and the organization Assistant. Supports organization rollout; disabled by default.', + fallback: 'MY_ACTIVITY', + }, 'mothership-model-selector': { description: 'Show the Mothership model selector, model-specific effort levels, and Fast for supported ' + diff --git a/apps/sim/lib/knowledge/application/operations.ts b/apps/sim/lib/knowledge/application/operations.ts index 3c4b43e5d5f..7c9a10f660a 100644 --- a/apps/sim/lib/knowledge/application/operations.ts +++ b/apps/sim/lib/knowledge/application/operations.ts @@ -420,6 +420,23 @@ export const knowledgeOperations = { }), { organizationDelegatedServices: ['copilot', 'slack-search', 'executor'] } ), + /** + * The caller's own activity across their connected sources. It always reads the person the + * principal represents, so a principal without one (a workspace API key, an actorless run) is + * refused rather than read as anyone else. + */ + listActivity: defineKnowledgeOperation( + defineWorkspaceOperation({ + id: 'knowledge.activity.list', + oauthScope: 'search:read', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'knowledge.use', + contentDelivery: 'sourced', + ...HUMAN_AND_COPILOT_PRINCIPAL_POLICY, + }), + { organizationDelegation: 'allow', organizationDelegatedServices: ['copilot', 'executor'] } + ), listFolders: defineKnowledgeOperation( defineWorkspaceOperation({ id: 'knowledge.folders.list', diff --git a/apps/sim/lib/knowledge/mcp/my-activity.ts b/apps/sim/lib/knowledge/mcp/my-activity.ts new file mode 100644 index 00000000000..3853a1e3b90 --- /dev/null +++ b/apps/sim/lib/knowledge/mcp/my-activity.ts @@ -0,0 +1,60 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import type { Principal } from '@sim/auth/principal' +import type { NextRequest } from 'next/server' +import { listMyActivityMcpSchema } from '@/lib/api/contracts/knowledge/mcp' +import { knowledgeOperations } from '@/lib/knowledge/application/operations' +import { + KNOWLEDGE_MCP_READ_ONLY, + type KnowledgeMcpToolRunner, + projectResult, +} from '@/lib/knowledge/mcp/tool-runner' +import { listMyActivity } from '@/lib/sim-search/live/activity' + +interface ListMyActivityToolContext { + execute: KnowledgeMcpToolRunner + principal: Principal + organizationId: string + request: NextRequest +} + +/** + * Provider reads one call makes, for the rate limit: about one listing per connected source, + * which is more than a single search's share. + */ +const LIST_MY_ACTIVITY_COST = 2 + +/** + * Registers `list_my_activity`: what the caller did across their connected sources in a window, + * newest first, with a status per source that names the ones to connect. + */ +export function registerListMyActivityTool( + server: McpServer, + { execute, principal, organizationId, request }: ListMyActivityToolContext +) { + server.registerTool( + 'list_my_activity', + { + title: 'List my activity', + description: + 'List what you did across your connected sources in a date window, newest first: Slack messages and Gmail mail you sent or replied to, Google Calendar meetings you attended, Jira issues you created or are assigned, and Confluence pages you created or edited and comments you wrote. Use it for standups, weekly reports and open action items. Defaults to the last 7 days; the window spans at most 92 days. Each item has a documentId for read_document and its url to cite. approximateTime marks a time that is the item’s last update rather than your own action. When truncated is true, call again with nextCursor and the same arguments: pages continue without gaps. sources reports every source: not_connected and reconnect carry connect.url, where you connect that account.', + inputSchema: listMyActivityMcpSchema, + annotations: KNOWLEDGE_MCP_READ_ONLY, + }, + async (input: unknown, extra: { signal: AbortSignal }) => + execute( + 'list_my_activity', + knowledgeOperations.listActivity, + extra.signal, + async (registry, signal) => { + const parsed = listMyActivityMcpSchema.parse(input) + const result = await listMyActivity.execute({ + principal, + input: { ...parsed, organizationId, resultSecretRegistry: registry, signal }, + request, + }) + return projectResult(result, registry) + }, + LIST_MY_ACTIVITY_COST + ) + ) +} diff --git a/apps/sim/lib/knowledge/mcp/route-handler.ts b/apps/sim/lib/knowledge/mcp/route-handler.ts index c0d7f44602a..8c9d67bf2bf 100644 --- a/apps/sim/lib/knowledge/mcp/route-handler.ts +++ b/apps/sim/lib/knowledge/mcp/route-handler.ts @@ -20,6 +20,7 @@ import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server' import { repairToolCallMessage, toolCallInputIssues } from '@/lib/knowledge/mcp/tool-arguments' import { getSearchMcpUrl } from '@/lib/knowledge/mcp/urls' import { canLookUpPeople } from '@/lib/people/directory-lookup' +import { isMyActivityEnabled } from '@/lib/sim-search/live/activity' import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response' const logger = createLogger('KnowledgeMcp') @@ -42,6 +43,16 @@ function mcpAuth(resource: string) { return mcpCredentialAuth({ resource, allowUnboundApiTokens: true }) } +/** + * Whether this message needs list_my_activity registered: a call to it, which its use case + * authorizes, or a tools/list while the feature is on for this organization. + */ +async function offersListMyActivity(message: Record, organizationId: string) { + if (message.method === 'tools/call') + return isRecordLike(message.params) && message.params.name === 'list_my_activity' + return message.method === 'tools/list' && isMyActivityEnabled(organizationId) +} + export function createKnowledgeMcpHandlers() { /** JSON-RPC is a protocol boundary; SDK dispatch calls the same authorized knowledge use cases. */ const handler = withRouteHandler( @@ -82,6 +93,7 @@ export function createKnowledgeMcpHandlers() { auth: admission.auth, ...parsed.data.params, searchPeople: await offersSearchPeople(message, admission.auth.principal, organizationId), + listMyActivity: await offersListMyActivity(message, organizationId), }) return await serveStatelessMcp(server, request, message) } catch (error) { diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 319dfbbbb55..db2c30eed39 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -19,6 +19,7 @@ import { type SearchMcpActivityInput, } from '@/lib/knowledge/mcp/activity' import { registerListMyChatHistoryTool } from '@/lib/knowledge/mcp/chat-history' +import { registerListMyActivityTool } from '@/lib/knowledge/mcp/my-activity' import { callerErrorMessage, readOrganizationDocuments, @@ -49,6 +50,8 @@ interface KnowledgeMcpContext { auth: V2ApiKeyAuthContext /** Registers search_people, which its use cases authorize on every call. */ searchPeople?: boolean + /** Registers list_my_activity, which its use case authorizes on every call. */ + listMyActivity?: boolean } /** A request owns its server; no credential or principal survives into another HTTP request. */ @@ -206,6 +209,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe // Only a person has a chat history; a workspace API key acts for no one. if (resolvePrincipalSubjectUserId(principal)) registerListMyChatHistoryTool(server, { execute, principal, organizationId }) + // Activity is always the caller's own; a workspace API key has no person to list. + if (context.listMyActivity && resolvePrincipalSubjectUserId(principal)) + registerListMyActivityTool(server, { execute, principal, organizationId, request }) return server } diff --git a/apps/sim/lib/knowledge/search/citation.ts b/apps/sim/lib/knowledge/search/citation.ts index e17bb6f8cf4..f8d04895388 100644 --- a/apps/sim/lib/knowledge/search/citation.ts +++ b/apps/sim/lib/knowledge/search/citation.ts @@ -10,3 +10,13 @@ import { liveDocumentKey } from '@/lib/sim-search/live/reference' export function liveCitationId(documentId: string): string { return `live:${sha256Hex(liveDocumentKey(documentId)).slice(0, 32)}` } + +/** + * The citation ID of one activity entry. Entries that read the same document can link to + * different places in it, such as two comments on one page, so the link is part of the identity. + */ +export function activityCitationId(documentId: string, url: string | null): string { + return url + ? `live:${sha256Hex(`${liveDocumentKey(documentId)}\n${url}`).slice(0, 32)}` + : liveCitationId(documentId) +} diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index 675d1417191..7a87495b29b 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -7,6 +7,7 @@ export const ASSISTANT_TOOLS = new Set([ 'read_document', 'search_people', 'list_my_chat_history', + 'list_my_activity', 'oauth_get_auth_link', 'run_function', ]) diff --git a/apps/sim/lib/mothership/chat/citation-evidence.ts b/apps/sim/lib/mothership/chat/citation-evidence.ts index ce7a48399cf..8a54f8abc40 100644 --- a/apps/sim/lib/mothership/chat/citation-evidence.ts +++ b/apps/sim/lib/mothership/chat/citation-evidence.ts @@ -16,7 +16,12 @@ type RetrievalCitationSource = { const WEB_TOOLS = new Set(['web_search', 'web_fetch']) /** Tools whose successful results supply sources: connected-source retrieval and public web research. */ -const CITATION_TOOLS = new Set(['search_workspace', 'read_document', ...WEB_TOOLS]) +const CITATION_TOOLS = new Set([ + 'search_workspace', + 'read_document', + 'list_my_activity', + ...WEB_TOOLS, +]) /** Whether a successful result of this tool may supply source destinations. */ export function isCitationTool(toolName: string): boolean { @@ -37,6 +42,15 @@ export function toCitationResult( toolName: string, result: Record ): Record { + if (toolName === 'list_my_activity' && typeof result.documentName !== 'string') + return { + citationId: result.citationId, + citationUrl: result.citationUrl, + documentName: result.title, + connectorType: result.source, + sourceDate: result.timestamp, + content: result.snippet, + } if (!isWebResearchTool(toolName) || typeof result.citationUrl === 'string') return result return { citationId: result.citationId, @@ -58,6 +72,15 @@ export function parseCitationRecord(value: unknown): Record | n return toRecordOrNull(value) } +/** + * The entries of one tool result that may each be a source. Activity lists its entries under + * `items`; a saved result, once compacted, keeps them under `results` like every other tool. + */ +export function citationResults(toolName: string, data: Record): unknown[] { + if (toolName === 'list_my_activity' && Array.isArray(data.items)) return data.items + return Array.isArray(data.results) ? data.results : [data] +} + /** Only successful retrieval and web research results may supply source destinations. */ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitationBlock[]) { const evidence = new Map() @@ -68,7 +91,7 @@ export function collectRetrievalCitationEvidence(blocks: readonly RetrievalCitat const output = parseCitationRecord(call.result.output) if (!output || output.success === false) continue const data = parseCitationRecord(output.data) ?? output - const results = Array.isArray(data.results) ? data.results : [data] + const results = citationResults(call.name, data) for (const raw of results) { const record = parseCitationRecord(raw) const result = record && toCitationResult(call.name, record) diff --git a/apps/sim/lib/mothership/chat/retrieval-citations.ts b/apps/sim/lib/mothership/chat/retrieval-citations.ts index 9a7c2c0a580..fb91b4156ed 100644 --- a/apps/sim/lib/mothership/chat/retrieval-citations.ts +++ b/apps/sim/lib/mothership/chat/retrieval-citations.ts @@ -1,5 +1,6 @@ import { isRecordLike } from '@sim/utils/object' import { + citationResults, isCitationTool, isWebResearchTool, toCitationResult, @@ -21,7 +22,7 @@ export function compactRetrievalCitations(toolName: string, raw: unknown): unkno } if (!isRecordLike(output) || output.success === false) return undefined const data = isRecordLike(output.data) ? output.data : output - const results = Array.isArray(data.results) ? data.results : [data] + const results = citationResults(toolName, data) // A live document reference permits 4,000 characters, plus the document: citation prefix. const citations = results.slice(0, 50).flatMap((raw) => { const item = isRecordLike(raw) ? toCitationResult(toolName, raw) : raw diff --git a/apps/sim/lib/mothership/entitlements.ts b/apps/sim/lib/mothership/entitlements.ts index c97472d4749..f18698e0ea3 100644 --- a/apps/sim/lib/mothership/entitlements.ts +++ b/apps/sim/lib/mothership/entitlements.ts @@ -5,6 +5,7 @@ import { readDashboardAvailability } from '@/lib/dashboards/application/availabi import { isDashboardsEnabled } from '@/lib/dashboards/feature-flag' import { ENTITLEMENTS, type Entitlement } from '@/lib/mothership/generated/protocol' import { canLookUpPeople } from '@/lib/people/directory-lookup' +import { isMyActivityEnabled } from '@/lib/sim-search/live/activity' import { readWorkflowTestAvailability } from '@/lib/workflow-tests/application/availability' import { isWorkflowTestsEnabled } from '@/lib/workflow-tests/feature-flag' import { readWorkflowCodeAvailability } from '@/lib/workflows/application/code-availability' @@ -87,6 +88,11 @@ const EVALUATORS: Record = { assistant: ({ principal, organizationId }) => principal ? canLookUpPeople(principal, organizationId) : Promise.resolve(false), }, + /** `list_my_activity` in organization chats; its use case re-checks the flag. */ + [ENTITLEMENTS.myActivity]: { + assistant: ({ organizationId }) => isMyActivityEnabled(organizationId), + organization: ({ organizationId }) => isMyActivityEnabled(organizationId), + }, } function evaluate(evaluator: EntitlementEvaluator, owner: EntitlementOwner): Promise { diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 1ad8ffd3a88..eac0f02eb4b 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -149,6 +149,7 @@ export const ENTITLEMENTS = { changelog: "changelog", workflowCode: "workflow-code", people: "people", + myActivity: "my-activity", } as const; export type Entitlement = (typeof ENTITLEMENTS)[keyof typeof ENTITLEMENTS]; export const Entitlements = z.array(z.string().min(1).max(64)).max(32); diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index ab69d7932ee..5849d7b3233 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -49,6 +49,9 @@ const PROVIDER_KIND_SCHEMAS = { zoom: z.enum(['meeting']), } as const +/** A collection one GitLab search selects. */ +export type GitLabSearchKind = z.output + function hasSearchKinds( provider: LiveSearchProvider ): provider is keyof typeof PROVIDER_KIND_SCHEMAS { @@ -355,6 +358,137 @@ export const readDocumentInputSchema = z.object({ ), }) +/** Days one activity listing may span, about a quarter. */ +export const MAX_ACTIVITY_WINDOW_DAYS = 92 +/** Activity entries one page returns when the caller sets no topK. */ +export const DEFAULT_ACTIVITY_TOP_K = 25 + +/** The activity filters, shared by every surface; refine with {@link refineActivityWindow}. */ +export const listMyActivityInputFieldsSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + `Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.' + ), + source: liveSearchProviderSchema + .optional() + .describe( + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.' + ), + topK: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe(`Maximum entries on this page: ${DEFAULT_ACTIVITY_TOP_K} by default.`), + cursor: z + .string() + .min(1) + .max(40_000) + .optional() + .describe( + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.' + ), + }) + .strict() + +/** Rules shared by every activity input schema built from {@link listMyActivityInputFieldsSchema}. */ +export function refineActivityWindow( + input: { startDate?: string; endDate?: string; cursor?: string }, + context: z.RefinementCtx +) { + /** A continuation reads the window its signed cursor fixed, however long ago that was. */ + if (!input.startDate || !input.endDate || input.cursor) return + const start = Date.parse(input.startDate) + const end = Date.parse(input.endDate) + if (start >= end) + context.addIssue({ + code: 'custom', + path: ['endDate'], + message: 'endDate must be after startDate.', + }) + /** A later endDate reads up to now, so the span counts only up to now. */ else if ( + Math.min(end, Date.now()) - start > + MAX_ACTIVITY_WINDOW_DAYS * 86_400_000 + ) + context.addIssue({ + code: 'custom', + path: ['startDate'], + message: `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.`, + }) +} + +export const listMyActivityInputSchema = + listMyActivityInputFieldsSchema.superRefine(refineActivityWindow) + +/** + * How one source served a multi-source result. `not_connected` and `reconnect` carry `connect`: + * the provider to connect and the page where the caller connects it. + */ +const liveSourceStatusSchema = z.object({ + source: liveSearchProviderSchema, + accountId: z.string().optional(), + displayName: z.string().optional(), + status: z.enum(['ok', 'partial', 'not_connected', 'reconnect', 'unsupported', 'failed']), + reason: z.enum(['rate_limited', 'timeout', 'unavailable']).optional(), + retryAfterSeconds: z.number().optional(), + message: z.string().optional(), + connect: z.object({ providerId: z.string(), url: z.string() }).optional(), +}) +export type LiveSourceStatus = z.output + +/** What the person did to an item, as one activity entry reports it. */ +const activityActionSchema = z.enum([ + 'created', + 'edited', + 'commented', + 'sent', + 'replied', + 'attended', + 'assigned', + 'mentioned', +]) +export type ActivityAction = z.output + +const activityItemSchema = z.object({ + /** Reads the item with read_document. */ + documentId: z.string(), + timestamp: z.string(), + source: liveSearchProviderSchema, + accountId: z.string(), + action: activityActionSchema, + title: z.string(), + url: z.string().nullable(), + container: z.string().optional(), + collaborators: z.array(z.string()), + snippet: z.string(), + /** The timestamp is the item's last update, possibly by someone else, not the person's action. */ + approximateTime: z.literal(true).optional(), +}) + +const listMyActivityResultSchema = z.object({ + window: z.object({ startDate: z.string(), endDate: z.string() }), + items: z.array(activityItemSchema), + /** More entries remain; continue with nextCursor. */ + truncated: z.boolean(), + nextCursor: z.string().optional(), + /** `complete` when every connected source that reports activity was read in full. */ + coverage: z.enum(['complete', 'partial']), + sources: z.array(liveSourceStatusSchema.extend({ itemCount: z.number().int().min(0) })), +}) +export type ListMyActivityResult = z.output + /** * Organization directory lookups. The bounds mirror the People page's search limits * (`lib/people/validation`) as literals, so the worker's generated copy stays standalone. @@ -391,6 +525,48 @@ export const searchPeopleInputSchema = z message: 'Pass either personId or a query with its cursor, not both.', }) +/** + * The caller's own questions to Sim over a window, oldest first. The 92-day window and the page + * bounds are literals so the worker's generated copy stays standalone. + */ +export const listMyChatHistoryInputSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .describe( + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.' + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.' + ), + topK: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Questions per page, 50 by default.'), + cursor: z + .string() + .min(1) + .max(1024) + .optional() + .describe('nextCursor from the previous page of the same window.'), + includeAnswers: z + .boolean() + .optional() + .describe( + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked." + ), + }) + .strict() +export type ListMyChatHistoryInput = z.output + /** Connection requests name a provider and optionally an owned account to repair. */ export const oauthGetAuthLinkInputSchema = z.object({ providerName: z @@ -461,6 +637,20 @@ export const assistantToolContracts = [ 'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use search_workspace for customers, vendors, and other outside contacts.', inputSchema: searchPeopleInputSchema, }, + { + id: 'list_my_chat_history', + route: 'sim', + description: + 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', + inputSchema: listMyChatHistoryInputSchema, + }, + { + id: 'list_my_activity', + route: 'sim', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + inputSchema: listMyActivityInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts index 3b6fea88b16..10fdd858c49 100644 --- a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts @@ -12,6 +12,7 @@ export interface ToolCatalogEntry { | 'List accessible Projects within this conversation, with visible environments and current capabilities. Follow nextCursor for more results; discovery does not grant file write access.' | 'List currently accessible workspaces with roles and explicit capability restrictions. Bulk results report copilotAllowed and deniedCapabilities; exact workspaceId returns the full capability map. Omitted restrictions never authorize an operation.' | 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.' + | 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.' | 'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use search_workspace for customers, vendors, and other outside contacts.' | 'Publish and edit the selected workspace’s changelog. publish takes a title, a markdown body, the changes (one line each, with the workflowId, deploymentVersionId, and chatId they came from when known), and bump: major, minor, or patch for how significant the release is, with a one-line bumpReason. The server computes the version from the workspace’s highest one; never write a version number on publish. It returns the release with its revision and changelog/.md, the body file: edit the body there with the file tools, for example to add impact charts once there is data. update changes the title, bumpReason, version label, or the whole change list, and requires expectedRevision from get, list, or publish so a concurrent edit is never overwritten. A deployment ships in one release: a deploymentVersionId already in another release is rejected. list pages newest first; get returns one release with its revision and its changelog/.md path.' | 'Read and manage account, organization, and workspace settings. list finds sections; get returns current values, updateSchema and operation names; describe returns one operation’s exact input schema; update changes narrow preferences; execute performs a listed operation; open returns the existing user setup flow. When user setup is needed, put the returned setupUrl in a clickable Markdown link at the end of the reply. Workspace resources retain their CLI commands. Account is the acting user; organization is the conversation’s organization. Every operation checks current permissions and entitlements.' @@ -90,6 +91,7 @@ export interface ToolCatalogEntry { | 'knowledge' | 'list_deployment_versions' | 'list_integration_tools' + | 'list_my_activity' | 'list_my_chat_history' | 'list_user_projects' | 'list_workspace_mcp_servers' @@ -7842,6 +7844,76 @@ export const ListMyChatHistory: ToolCatalogEntry = { }, } +export const ListMyActivity: ToolCatalogEntry = { + id: 'list_my_activity', + description: + 'List what you did across your connected sources in a date window, newest first: messages and mail you sent or replied to, meetings you attended, Jira issues you created or are assigned, Confluence pages you created or edited and comments you wrote. Each item has a documentId for read_document. Follow nextCursor for more. sources reports each source: not_connected and reconnect carry the provider to connect with oauth_get_auth_link.', + route: 'sim', + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + description: + 'Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + endDate: { + description: + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + source: { + description: + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.', + type: 'string', + enum: [ + 'google_drive', + 'gmail', + 'google_meet', + 'zoom', + 'google_calendar', + 'slack', + 'jira', + 'confluence', + 'github', + 'jama', + 'flow', + 'gitlab', + 'linear', + 'lucid', + 'hex', + 'hubspot', + 'fireflies', + 'granola', + 'notion', + 'coda', + ], + }, + topK: { + description: 'Maximum entries on this page: 25 by default.', + type: 'integer', + minimum: 1, + maximum: 50, + }, + cursor: { + description: + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + type: 'string', + minLength: 1, + maxLength: 40000, + }, + }, + additionalProperties: false, + }, +} + export const Dashboards: ToolCatalogEntry = { id: 'dashboards', description: @@ -8853,6 +8925,7 @@ export const TOOL_CATALOG: Record = { [ListWorkspaces.id]: ListWorkspaces, [SearchPeople.id]: SearchPeople, [ListMyChatHistory.id]: ListMyChatHistory, + [ListMyActivity.id]: ListMyActivity, [Dashboards.id]: Dashboards, [Tests.id]: Tests, [Changelog.id]: Changelog, diff --git a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts index ac9f13088cf..f8aca3b7092 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -7916,6 +7916,72 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, + list_my_activity: { + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + description: + 'Inclusive start of the window, an ISO datetime with the user’s timezone offset. Defaults to 7 days before endDate; the window spans at most 92 days.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + endDate: { + description: + 'Exclusive end of the window, an ISO datetime with the user’s timezone offset. Defaults to now; a later time reads up to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + source: { + description: + 'One source to read, such as slack, gmail, google_calendar, jira or confluence. Omit for every connected source.', + type: 'string', + enum: [ + 'google_drive', + 'gmail', + 'google_meet', + 'zoom', + 'google_calendar', + 'slack', + 'jira', + 'confluence', + 'github', + 'jama', + 'flow', + 'gitlab', + 'linear', + 'lucid', + 'hex', + 'hubspot', + 'fireflies', + 'granola', + 'notion', + 'coda', + ], + }, + topK: { + description: 'Maximum entries on this page: 25 by default.', + type: 'integer', + minimum: 1, + maximum: 50, + }, + cursor: { + description: + 'nextCursor from the previous page, with the same startDate, endDate, source and topK. Pages continue newest first without gaps.', + type: 'string', + minLength: 1, + maxLength: 40000, + }, + }, + additionalProperties: false, + }, + resultSchema: undefined, + }, dashboards: { parameters: { $schema: 'http://json-schema.org/draft-07/schema#', diff --git a/apps/sim/lib/mothership/tool-executor/executor.ts b/apps/sim/lib/mothership/tool-executor/executor.ts index 2e40b193b48..55dbb06d3b2 100644 --- a/apps/sim/lib/mothership/tool-executor/executor.ts +++ b/apps/sim/lib/mothership/tool-executor/executor.ts @@ -89,6 +89,7 @@ export async function executeTool( 'list_workspaces', 'search_workspace', 'read_document', + 'list_my_activity', 'search_sources', ...(params.scope !== 'workspace' ? ['settings'] : []), ] diff --git a/apps/sim/lib/mothership/tools/activity.ts b/apps/sim/lib/mothership/tools/activity.ts index 527d13ba3fb..9d5b8dffe88 100644 --- a/apps/sim/lib/mothership/tools/activity.ts +++ b/apps/sim/lib/mothership/tools/activity.ts @@ -409,6 +409,7 @@ export const TOOL_ACTIVITIES: Readonly = { list_workspaces: 'Listing workspaces', read_document: 'Reading document', search_people: 'Looking up people', + list_my_activity: 'Listing your activity', open_resource: 'Opening resource', ffmpeg: 'Processing media', diff --git a/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts new file mode 100644 index 00000000000..d6431c20fd8 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/my-activity.ts @@ -0,0 +1,72 @@ +import { createLogger } from '@sim/logger' +import { z } from 'zod' +import { listMyActivityInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { getValidationErrorMessage } from '@/lib/api/server/validation' +import { activityCitationId } from '@/lib/knowledge/search/citation' +import { + executeCopilotOrganizationKnowledgeUseCase, + messageForCopilotKnowledgeError, +} from '@/lib/mothership/application/execute-knowledge-use-case' +import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' +import { listMyActivity } from '@/lib/sim-search/live/activity' + +const logger = createLogger('ListMyActivityTool') + +/** + * `list_my_activity` for the organization Assistant: the same use case and result as the Search + * MCP tool of that name, with a citation ID on each entry. + */ +export const listMyActivityServerTool: BaseServerTool = { + name: 'list_my_activity', + inputSchema: listMyActivityInputSchema, + async execute(raw, context?: ServerToolContext) { + if (!context?.organizationId) + return { + success: false, + message: 'Your activity is available only in organization conversations.', + } + try { + const input = listMyActivityInputSchema.parse(raw) + const registry = context.resolvedSecretTraceRegistry + if (!registry) throw new Error('Knowledge result provenance is unavailable') + const data = await executeCopilotOrganizationKnowledgeUseCase(context, listMyActivity, { + ...input, + organizationId: context.organizationId, + resultSecretRegistry: registry, + signal: context.abortSignal, + }) + const unconnected = data.sources.filter( + (source) => source.status === 'not_connected' || source.status === 'reconnect' + ) + return { + success: true, + message: [ + `Listed ${data.items.length} activity entries, newest first.`, + data.truncated ? 'More remain: call again with nextCursor and the same arguments.' : '', + unconnected.length + ? `Not read: ${unconnected.map((source) => source.source).join(', ')}. Offer to connect each with oauth_get_auth_link using its connect.providerId.` + : '', + 'Cite entries with a non-null citationUrl as {"id":""}.', + ] + .filter(Boolean) + .join(' '), + data: { + ...data, + items: data.items.map((item) => ({ + ...item, + citationId: activityCitationId(item.documentId, item.url), + citationUrl: item.url, + })), + }, + } + } catch (error) { + if (error instanceof z.ZodError) + return { + success: false, + message: getValidationErrorMessage(error, 'Invalid activity arguments'), + } + logger.error('Activity listing failed', { error }) + return { success: false, message: messageForCopilotKnowledgeError(error) } + } + }, +} diff --git a/apps/sim/lib/mothership/tools/server/router.ts b/apps/sim/lib/mothership/tools/server/router.ts index c62322249ab..090d48e7d52 100644 --- a/apps/sim/lib/mothership/tools/server/router.ts +++ b/apps/sim/lib/mothership/tools/server/router.ts @@ -26,6 +26,7 @@ import { workspaceFileServerTool } from '@/lib/mothership/tools/server/files/wor import { validateGeneratedToolPayload } from '@/lib/mothership/tools/server/generated-schema' import { generateImageServerTool } from '@/lib/mothership/tools/server/image/generate-image' import { listMyChatHistoryServerTool } from '@/lib/mothership/tools/server/knowledge/chat-history' +import { listMyActivityServerTool } from '@/lib/mothership/tools/server/knowledge/my-activity' import { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' import { readDocumentServerTool, @@ -83,6 +84,7 @@ const baseServerToolRegistry: Record = { [readDocumentServerTool.name]: readDocumentServerTool, [searchPeopleServerTool.name]: searchPeopleServerTool, [listMyChatHistoryServerTool.name]: listMyChatHistoryServerTool, + [listMyActivityServerTool.name]: listMyActivityServerTool, // The streamed file-writing pair: prepare opens the write (live preview), // apply continues it. The preview machinery keys off these exact names. [workspaceFileServerTool.name]: withFileTabFlag(workspaceFileServerTool), diff --git a/apps/sim/lib/sim-search/live/account-session.ts b/apps/sim/lib/sim-search/live/account-session.ts index c2396e0d1a6..de9e634b4ec 100644 --- a/apps/sim/lib/sim-search/live/account-session.ts +++ b/apps/sim/lib/sim-search/live/account-session.ts @@ -26,6 +26,7 @@ import { livePolicyFor, loadLiveSearchPolicies } from '@/lib/sim-search/live/pol import { LIVE_SEARCH_PROVIDER_CATALOG } from '@/lib/sim-search/live/provider-catalog' import { isSearchProviderEnabled } from '@/lib/sim-search/live/provider-rollout' import { + activityNativeProvider, previewNativeText, readNativeProvider, requiresEveryTerm, @@ -34,7 +35,13 @@ import { import { searchWithinPolicy } from '@/lib/sim-search/live/scoped-search' import { createLiveServiceSession } from '@/lib/sim-search/live/service-session' import { searchWithAnyTermFallback } from '@/lib/sim-search/live/term-fallback' -import type { NativeDocument, NativePage, NativeSearchInput } from '@/lib/sim-search/live/types' +import type { + NativeActivityInput, + NativeActivityPage, + NativeDocument, + NativePage, + NativeSearchInput, +} from '@/lib/sim-search/live/types' import { readZoomMcp, searchZoomMcp } from '@/lib/sim-search/live/zoom-mcp' type Reference = Pick< @@ -66,6 +73,11 @@ export interface LiveAccountSession { /** Releases the operation-owned provider transport after all reads and checks settle. */ close(): Promise search(input: NativeSearchInput): Promise + /** + * The connected person's own activity under the effective policy. Its entries are candidates: + * each is verified against the source boundary like a search result before it is returned. + */ + activity(input: Omit): Promise /** True only when the document is inside the source boundary and the member may read it. */ verify(document: Reference): Promise read(reference: Reference, filters?: WorkspaceSearchFilters): Promise @@ -263,6 +275,23 @@ export async function openLiveAccountSession( : searchOnce(request)) return connectionBinding ? { ...page, documents: page.documents.map(bind) } : page }, + async activity(request) { + if (admin || !client) + throw new NativeSearchError('unavailable', 'This source does not report activity.') + const page = await activityNativeProvider(provider, client, { + ...request, + policy: boundary.policy, + signal: request.signal ?? signal, + }) + if (!connectionBinding) return page + return { + ...page, + streams: page.streams.map((stream) => ({ + ...stream, + events: stream.events.map((event) => ({ ...event, document: bind(event.document) })), + })), + } + }, verify, async read(reference, filters) { if (admin) return admin.read(reference) diff --git a/apps/sim/lib/sim-search/live/activity-page.test.ts b/apps/sim/lib/sim-search/live/activity-page.test.ts new file mode 100644 index 00000000000..e5ae9d0de72 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-page.test.ts @@ -0,0 +1,293 @@ +/** + * @vitest-environment node + */ +import { compareStrings } from '@sim/utils/string' +import { describe, expect, it } from 'vitest' +import { + type AccountActivity, + type ActivityBound, + type ActivityEntry, + mergeActivityPage, + readActivityCursor, + writeActivityCursor, +} from '@/lib/sim-search/live/activity-page' + +const START = '2026-11-01T00:00:00.000Z' +const END = '2026-11-08T00:00:00.000Z' + +const at = (hour: number) => new Date(Date.parse(START) + hour * 3_600_000).toISOString() + +interface FakeAccount { + id: string + /** Items the provider holds, newest first, read `limit` at a time like a provider listing. */ + items: ActivityEntry[] + limit: number +} + +/** One provider read under a bound: items up to `end` (inclusive), newest first. */ +function read(account: FakeAccount, bound: ActivityBound): AccountActivity { + const inWindow = account.items.filter( + (item) => Date.parse(item.at) <= Date.parse(bound.end) && item.at >= START + ) + const page = inWindow.slice(0, account.limit) + return { + accountId: account.id, + bound, + read: true, + streams: [{ entries: page, more: inWindow.length > page.length, scannedTo: page.at(-1)?.at }], + } +} + +/** Pages through every account until no cursor remains, as a caller following nextCursor. */ +function pageThrough( + accounts: FakeAccount[], + topK: number, + fail: (accountId: string, page: number) => boolean = () => false +) { + let bounds: Record = Object.fromEntries( + accounts.map((account) => [account.id, { end: END, seen: [] }]) + ) + const pages: string[][] = [] + const stalled: string[] = [] + for (let page = 0; page < 50; page++) { + const result = mergeActivityPage( + accounts + .filter((account) => bounds[account.id]) + .map((account) => { + const bound = bounds[account.id] as ActivityBound + return fail(account.id, page) + ? { accountId: account.id, bound, read: false as const } + : read(account, bound) + }), + { start: START }, + topK + ) + pages.push(result.entries.map((entry) => `${entry.accountId}:${entry.key}`)) + stalled.push(...result.stalled) + if (!result.next) return { pages, stalled } + bounds = result.next + } + throw new Error('Paging did not end') +} + +function newestFirst(accounts: FakeAccount[]): string[] { + return accounts + .flatMap((account) => account.items.map((item) => ({ ...item, accountId: account.id }))) + .sort( + (left, right) => + Date.parse(right.at) - Date.parse(left.at) || + compareStrings(left.accountId, right.accountId) || + compareStrings(left.key, right.key) + ) + .map((entry) => `${entry.accountId}:${entry.key}`) +} + +describe('mergeActivityPage', () => { + it('returns every entry once and newest first when a listing is read a few items at a time', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 3, + items: [ + { at: at(150), key: 'c1' }, + { at: at(120), key: 'c2' }, + { at: at(120), key: 'c3' }, + { at: at(90), key: 'c4' }, + { at: at(40), key: 'c5' }, + { at: at(30), key: 'c6' }, + { at: at(2), key: 'c7' }, + ], + }, + { + id: 'mail', + limit: 50, + items: [ + { at: at(160), key: 'm1' }, + { at: at(120), key: 'm2' }, + { at: at(60), key: 'm3' }, + { at: at(35), key: 'm4' }, + { at: at(1), key: 'm5' }, + ], + }, + ] + for (const topK of [2, 10]) { + const { pages, stalled } = pageThrough(accounts, topK) + expect(pages.flat()).toEqual(newestFirst(accounts)) + expect(pages.every((page) => page.length <= topK)).toBe(true) + expect(stalled).toEqual([]) + } + }) + + it('retries an account that failed from where it stopped, losing none of its entries', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [1, 2, 3, 4, 5, 6].map((hour) => ({ at: at(170 - hour * 20), key: `c${hour}` })), + }, + { + id: 'mail', + limit: 50, + items: [1, 2, 3].map((hour) => ({ at: at(165 - hour * 30), key: `m${hour}` })), + }, + ] + const { pages } = pageThrough( + accounts, + 3, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(new Set(pages.flat())).toEqual(new Set(newestFirst(accounts))) + expect(pages.flat()).toHaveLength(newestFirst(accounts).length) + }) + + it('carries a failed account to the next page when the others finish on this one', () => { + const accounts: FakeAccount[] = [ + { id: 'chat', limit: 50, items: [{ at: at(100), key: 'c1' }] }, + { id: 'mail', limit: 50, items: [{ at: at(90), key: 'm1' }] }, + ] + const { pages } = pageThrough( + accounts, + 10, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(pages.flat()).toEqual(['chat:c1', 'mail:m1']) + }) + + it('returns no entry twice when a recovered account resumes above the others', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [ + { at: at(80), key: 'c1' }, + { at: at(70), key: 'c2' }, + { at: at(60), key: 'c3' }, + ], + }, + { + id: 'mail', + limit: 2, + items: [ + { at: at(95), key: 'm1' }, + { at: at(90), key: 'm2' }, + { at: at(50), key: 'm3' }, + ], + }, + ] + const { pages } = pageThrough( + accounts, + 1, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(pages.flat()).toHaveLength(6) + expect(new Set(pages.flat()).size).toBe(6) + }) + + it('keeps paging the others after a recovered account catches up and finishes', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [ + { at: at(80), key: 'c1' }, + { at: at(70), key: 'c2' }, + { at: at(60), key: 'c3' }, + ], + }, + { + id: 'mail', + limit: 2, + items: [ + { at: at(95), key: 'm1' }, + { at: at(90), key: 'm2' }, + ], + }, + ] + const { pages, stalled } = pageThrough( + accounts, + 1, + (accountId, page) => accountId === 'mail' && page === 0 + ) + expect(new Set(pages.flat())).toEqual(new Set(newestFirst(accounts))) + expect(stalled).toEqual([]) + }) + + it('ends without a continuation when only failed accounts would continue', () => { + const result = mergeActivityPage( + [{ accountId: 'mail', bound: { end: END, seen: [] }, read: false }], + { start: START }, + 10 + ) + expect(result.next).toBeUndefined() + }) + + it('stops an account holding more entries at one instant than a read returns, instead of looping', () => { + const accounts: FakeAccount[] = [ + { + id: 'chat', + limit: 2, + items: [1, 2, 3, 4, 5].map((index) => ({ at: at(100), key: `c${index}` })), + }, + ] + const { pages, stalled } = pageThrough(accounts, 10) + expect(new Set(pages.flat()).size).toBe(pages.flat().length) + expect(stalled).toEqual(['chat']) + }) + + it('leaves out entries outside the window and those an earlier page returned at its bound', () => { + const result = mergeActivityPage( + [ + { + accountId: 'chat', + bound: { end: at(100), seen: ['c1'] }, + read: true, + streams: [ + { + entries: [ + { at: at(110), key: 'later' }, + { at: at(100), key: 'c1' }, + { at: at(100), key: 'c2' }, + { at: '2026-10-31T23:00:00.000Z', key: 'earlier' }, + ], + more: false, + }, + ], + }, + ], + { start: START }, + 10 + ) + expect(result.entries.map((entry) => entry.key)).toEqual(['c2']) + expect(result.next).toBeUndefined() + }) +}) + +describe('activity cursors', () => { + const cursor = { + v: 1 as const, + scope: 'A'.repeat(22), + start: START, + end: END, + accounts: { chat: { end: at(50), seen: ['c1'] } }, + } + + it('reads back a cursor minted for the same caller and request', () => { + expect( + readActivityCursor(writeActivityCursor(cursor, 'secret'), cursor.scope, 'secret') + ).toEqual(cursor) + }) + + it('refuses a cursor minted for another caller or request', () => { + const value = writeActivityCursor(cursor, 'secret') + expect(readActivityCursor(value, 'B'.repeat(22), 'secret')).toBeUndefined() + }) + + it('refuses a cursor whose bounds were altered', () => { + const decoded = JSON.parse( + Buffer.from(writeActivityCursor(cursor, 'secret'), 'base64url').toString('utf8') + ) + decoded.accounts.chat.end = END + const altered = Buffer.from(JSON.stringify(decoded)).toString('base64url') + expect(readActivityCursor(altered, cursor.scope, 'secret')).toBeUndefined() + }) +}) diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts new file mode 100644 index 00000000000..89ab1d01109 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -0,0 +1,236 @@ +import { safeCompare } from '@sim/security/compare' +import { hmacSha256Hex } from '@sim/security/hmac' +import { canonicalJson } from '@sim/utils/object' +import { compareStrings } from '@sim/utils/string' +import { z } from 'zod' + +/** People named on one activity entry, besides the person whose activity it is. */ +const MAX_ACTIVITY_COLLABORATORS = 10 +/** + * Entries one account may have returned at the instant a page stopped. A continuation skips + * them; an account with more than this many entries at one instant stops there. + */ +const MAX_SEEN_AT_BOUND = 50 + +/** The distinct, nonempty names on one activity entry, at most {@link MAX_ACTIVITY_COLLABORATORS}. */ +export function collaboratorNames(names: readonly string[]): string[] { + return [...new Set(names.map((name) => name.trim()).filter(Boolean))].slice( + 0, + MAX_ACTIVITY_COLLABORATORS + ) +} + +/** The earliest of the valid instants, as ISO, or undefined when none parses. */ +export function oldestInstant(values: readonly (string | undefined)[]): string | undefined { + let oldest: number | undefined + for (const value of values) { + const time = Date.parse(value ?? '') + if (Number.isFinite(time) && (oldest === undefined || time < oldest)) oldest = time + } + return oldest === undefined ? undefined : new Date(oldest).toISOString() +} + +/** + * Where one account's next page resumes: its streams are read again up to `end` (inclusive), and + * the entries at exactly `end` that an earlier page returned, named by `seen`, are skipped. + */ +export interface ActivityBound { + end: string + seen: string[] + /** The account's source, so a page can still name an account that is no longer connected. */ + source?: string +} + +/** One activity entry ready to merge: when it happened and the key naming it within its account. */ +export interface ActivityEntry { + at: string + key: string +} + +interface ActivityStreamRead { + entries: E[] + more: boolean + scannedTo?: string +} + +/** One account's part of a page: the bound it was read with and what it returned. */ +export type AccountActivity = { + accountId: string + bound: ActivityBound +} & ({ read: true; streams: ActivityStreamRead[] } | { read: false }) + +interface ActivityPageResult { + /** Newest first. */ + entries: (E & { accountId: string })[] + /** Each continuing account's bound, or undefined when no page follows. */ + next?: Record + /** Accounts that stopped without reading all their activity, for partial coverage. */ + stalled: string[] +} + +function sameBound(left: ActivityBound, right: ActivityBound): boolean { + return ( + Date.parse(left.end) === Date.parse(right.end) && + left.seen.length === right.seen.length && + left.seen.every((key) => right.seen.includes(key)) + ) +} + +/** + * Merges one page of several accounts' activity, newest first, without dropping anything a + * later page could not reach. Every stream is read newest first, so its unread items sort at or + * before the oldest instant it scanned; past the latest such instant of any stream with more, an + * entry might be preceded by one not yet read. Entries before that horizon wait for the next + * page, which reads every account again up to where this page stopped. An account that failed + * keeps its bound, so the next page retries it from there; its entries, newer than the others' + * bounds, then arrive out of order on that page rather than being lost. + */ +export function mergeActivityPage( + accounts: readonly AccountActivity[], + window: { start: string }, + topK: number +): ActivityPageResult { + const start = Date.parse(window.start) + let horizon: number | undefined + const pending: { entry: E & { accountId: string }; time: number }[] = [] + const unfinished = new Set() + for (const account of accounts) { + if (!account.read) continue + const end = Date.parse(account.bound.end) + const seen = new Set(account.bound.seen) + const keys = new Set() + for (const stream of account.streams) { + if (stream.more) { + const scanned = stream.scannedTo ? Date.parse(stream.scannedTo) : end + const floor = Number.isFinite(scanned) ? Math.min(scanned, end) : end + horizon = horizon === undefined ? floor : Math.max(horizon, floor) + unfinished.add(account.accountId) + } + for (const entry of stream.entries) { + const time = Date.parse(entry.at) + if (!Number.isFinite(time) || time < start || time > end) continue + if ((time === end && seen.has(entry.key)) || keys.has(entry.key)) continue + keys.add(entry.key) + pending.push({ entry: { ...entry, accountId: account.accountId }, time }) + } + } + } + pending.sort( + (left, right) => + right.time - left.time || + compareStrings(left.entry.accountId, right.entry.accountId) || + compareStrings(left.entry.key, right.entry.key) + ) + const ready = horizon === undefined ? pending : pending.filter(({ time }) => time >= horizon) + const returned = ready.slice(0, topK) + const cut = ready.length > topK + const last = returned.at(-1) + const resume = cut && last ? last.time : horizon + /** Accounts with an entry this page read but did not return, which the next page must reach. */ + const returnedItems = new Set(returned) + const remaining = new Set( + pending.filter((item) => !returnedItems.has(item)).map(({ entry }) => entry.accountId) + ) + const next: Record = {} + const stalled: string[] = [] + const continuing: string[] = [] + let progressed = false + for (const account of accounts) { + if (!account.read) { + next[account.accountId] = account.bound + continue + } + if ( + resume === undefined || + (!unfinished.has(account.accountId) && !remaining.has(account.accountId)) + ) + continue + /** + * A bound never moves later: an account that recovers after a failure resumes above the + * others, and moving theirs up to it would return their entries again. + */ + const ownEnd = Date.parse(account.bound.end) + const end = Math.min(resume, ownEnd) + const returnedAtEnd = returned + .filter(({ entry, time }) => entry.accountId === account.accountId && time === end) + .map(({ entry }) => entry.key) + const bound: ActivityBound = { + end: new Date(end).toISOString(), + seen: [...new Set([...(ownEnd === end ? account.bound.seen : []), ...returnedAtEnd])], + } + if (bound.seen.length > MAX_SEEN_AT_BOUND) { + stalled.push(account.accountId) + continue + } + if (!sameBound(bound, account.bound)) progressed = true + next[account.accountId] = bound + continuing.push(account.accountId) + } + const entries = returned.map(({ entry }) => entry) + /** + * A page that returned nothing and moved no bound would be read again unchanged, so it ends + * here. Returning entries is progress even when the remaining bounds stay put, as when a + * recovered account catches up above the others. + */ + if (continuing.length && !progressed && !entries.length) + return { entries, stalled: [...stalled, ...continuing] } + /** + * An account that failed is retried on the next page while this one made progress; a page + * where only failed accounts were left, and failed again, ends the listing. + */ + const retrying = accounts.some((account) => !account.read) + return { + entries, + ...(continuing.length || (retrying && entries.length) ? { next } : {}), + stalled, + } +} + +const boundSchema = z.object({ + end: z.string().datetime({ offset: true }), + seen: z.array(z.string().max(32)).max(MAX_SEEN_AT_BOUND), + source: z.string().max(64).optional(), +}) +const cursorSchema = z + .object({ + v: z.literal(1), + /** Fingerprint of the caller and the request the cursor continues. */ + scope: z.string().regex(/^[A-Za-z0-9_-]{22}$/), + start: z.string().datetime({ offset: true }), + end: z.string().datetime({ offset: true }), + accounts: z.record(z.string().max(200), boundSchema), + }) + .strict() +type ActivityCursor = z.output +const signedCursorSchema = cursorSchema.extend({ signature: z.string().regex(/^[a-f0-9]{64}$/) }) + +function cursorSignature(cursor: ActivityCursor, secret: string): string { + return hmacSha256Hex(`live-activity-cursor:${canonicalJson(cursor)}`, secret) +} + +/** A signed, opaque continuation of one activity listing. */ +export function writeActivityCursor(cursor: ActivityCursor, secret: string): string { + return Buffer.from( + JSON.stringify({ ...cursor, signature: cursorSignature(cursor, secret) }) + ).toString('base64url') +} + +/** + * The continuation a cursor names, or undefined when it is malformed, altered, or minted for + * another caller or request than `scope`. + */ +export function readActivityCursor( + value: string, + scope: string, + secret: string +): ActivityCursor | undefined { + try { + const { signature, ...cursor } = signedCursorSchema.parse( + JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) + ) + if (!safeCompare(signature, cursorSignature(cursor, secret))) return undefined + return cursor.scope === scope ? cursor : undefined + } catch { + return undefined + } +} diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts new file mode 100644 index 00000000000..5a49e8740af --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -0,0 +1,316 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it, vi } from 'vitest' +import { atlassianActivity } from '@/lib/sim-search/live/atlassian' +import { calendarActivity, gmailActivity } from '@/lib/sim-search/live/google' +import { slackActivity } from '@/lib/sim-search/live/slack' +import type { NativeActivityInput, NativeClient } from '@/lib/sim-search/live/types' + +const WINDOW: NativeActivityInput = { + start: '2026-11-01T00:00:00.000Z', + end: '2026-11-08T00:00:00.000Z', + limit: 20, + scopes: ['search:read.public'], +} + +/** Answers the paths a test names; any other request fails the test. */ +function client(answer: (path: string, options?: { query?: Record }) => unknown) { + return { + json: vi.fn(async (path: string, options?: { query?: Record }) => { + const value = answer(path, options) + if (value === undefined) throw new Error(`Unexpected request: ${path}`) + return value + }), + text: vi.fn(), + bytes: vi.fn(), + } satisfies NativeClient +} + +describe('Slack activity', () => { + it('names a message inside a thread it did not start a reply, and leaves out file hits', async () => { + const api = client((path) => + path === '/api/assistant.search.context' + ? { + ok: true, + results: { + messages: [ + { + message_ts: '1762300000.000200', + thread_ts: '1762290000.000100', + channel_id: 'C1', + channel_name: 'eng', + permalink: 'https://acme.slack.com/archives/C1/p1', + content: 'Looks good', + }, + { + message_ts: '1762200000.000100', + thread_ts: '1762200000.000100', + channel_id: 'C1', + channel_name: 'eng', + permalink: 'https://acme.slack.com/archives/C1/p2', + content: 'Starting the deploy', + }, + ], + files: [{ file_id: 'F1', title: 'notes', date_updated: 1762400000 }], + }, + response_metadata: { next_cursor: 'next' }, + } + : undefined + ) + const page = await slackActivity(api, WINDOW) + const [stream] = page.streams + expect(stream?.events.map((event) => [event.document.id, event.action])).toEqual([ + ['1762300000.000200', 'replied'], + ['1762200000.000100', 'sent'], + ]) + expect(stream).toMatchObject({ more: true, scannedTo: new Date(1762200000000).toISOString() }) + }) +}) + +describe('Gmail activity', () => { + it('names mail answering another a reply and lists its recipients', async () => { + const message = (id: string, headers: Record, internalDate: number) => ({ + id, + internalDate: String(internalDate), + snippet: 'Hi', + payload: { headers: Object.entries(headers).map(([name, value]) => ({ name, value })) }, + }) + const api = client((path) => { + if (path === '/gmail/v1/users/me/messages') return { messages: [{ id: 'a' }, { id: 'b' }] } + if (path === '/gmail/v1/users/me/messages/a') + return message( + 'a', + { + Subject: 'Re: plan', + To: 'Ann Lee , "Park, Bo" ', + Cc: 'cy@example.com', + 'In-Reply-To': '', + }, + 1762300000000 + ) + if (path === '/gmail/v1/users/me/messages/b') + return message('b', { Subject: 'Plan', To: 'ann@example.com' }, 1762200000000) + return undefined + }) + const [stream] = (await gmailActivity(api, WINDOW)).streams + expect( + stream?.events.map((event) => [event.document.id, event.action, event.collaborators]) + ).toEqual([ + ['a', 'replied', ['Ann Lee', 'Park, Bo', 'cy@example.com']], + ['b', 'sent', ['ann@example.com']], + ]) + }) +}) + +describe('Calendar activity', () => { + it('counts only meetings the member organized or accepted with someone else, newest first', async () => { + const self = (responseStatus: string) => ({ email: 'me@x.com', self: true, responseStatus }) + const other = { email: 'ann@x.com', displayName: 'Ann' } + const event = (id: string, day: number, extra: Record) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + ...extra, + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { + items: [ + event('accepted', 2, { attendees: [self('accepted'), other] }), + event('declined', 3, { attendees: [self('declined'), other] }), + event('unanswered', 3, { attendees: [self('needsAction'), other] }), + event('alone', 4, { organizer: { self: true }, attendees: [self('accepted')] }), + event('room', 4, { + organizer: { self: true }, + attendees: [self('accepted'), { email: 'room@x.com', resource: true }], + }), + event('focus', 4, { + eventType: 'focusTime', + organizer: { self: true }, + attendees: [self('accepted'), other], + }), + event('organized', 5, { organizer: { self: true }, attendees: [other] }), + ], + } + : undefined + ) + const [stream] = (await calendarActivity(api, WINDOW)).streams + expect(stream?.events.map((entry) => [entry.document.id, entry.collaborators])).toEqual([ + ['organized', ['Ann']], + ['accepted', ['Ann']], + ]) + expect(stream?.events.every((entry) => entry.action === 'attended')).toBe(true) + }) +}) + +describe('Calendar activity paging', () => { + it('returns only the newest meetings a page needs and resumes below them', async () => { + const meeting = (id: string, day: number) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + organizer: { self: true }, + attendees: [{ email: 'ann@x.com' }], + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { items: [meeting('first', 2), meeting('second', 4), meeting('third', 6)] } + : undefined + ) + const [stream] = (await calendarActivity(api, { ...WINDOW, limit: 2 })).streams + expect(stream?.events.map((event) => event.document.id)).toEqual(['third', 'second']) + expect(stream).toMatchObject({ more: true, scannedTo: '2026-11-04T15:00:00.000Z' }) + }) + + it('reads past meetings at the bound an earlier page may have returned', async () => { + const meeting = (id: string, day: number) => ({ + id, + summary: id, + start: { dateTime: `2026-11-0${day}T15:00:00Z` }, + end: { dateTime: `2026-11-0${day}T16:00:00Z` }, + organizer: { self: true }, + attendees: [{ email: 'ann@x.com' }], + }) + const api = client((path) => + path === '/calendar/v3/calendars/primary/events' + ? { items: [meeting('older', 2), meeting('tied-a', 6), meeting('tied-b', 6)] } + : undefined + ) + const [stream] = ( + await calendarActivity(api, { ...WINDOW, end: '2026-11-06T15:00:00.000Z', limit: 2 }) + ).streams + expect(stream?.events.map((event) => event.document.id)).toEqual( + expect.arrayContaining(['tied-a', 'tied-b', 'older']) + ) + }) +}) + +describe('Atlassian activity', () => { + const site = { id: 'cloud', url: 'https://acme.atlassian.net' } + + it('marks a page whose last edit is someone else’s approximate, and reads a comment’s page', async () => { + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path === '/ex/confluence/cloud/wiki/rest/api/user/current') return { accountId: 'me' } + if (path !== '/ex/confluence/cloud/wiki/rest/api/search') return undefined + const cql = String(options?.query?.cql) + return cql.startsWith('type = comment') + ? { + results: [ + { + content: { + id: 'c1', + type: 'comment', + container: { id: '42', type: 'page', title: 'Runbook' }, + history: { createdDate: '2026-11-05T10:00:00.000Z' }, + _links: { webui: '/spaces/ENG/pages/42?focusedCommentId=c1' }, + }, + excerpt: 'Agreed', + }, + ], + _links: {}, + } + : { + results: [ + { + content: { + id: '7', + type: 'page', + title: 'Plan', + version: { + when: '2026-11-06T10:00:00.000Z', + number: 3, + by: { accountId: 'ann', displayName: 'Ann' }, + }, + }, + }, + { + content: { + id: '8', + type: 'page', + title: 'Notes', + version: { + when: '2026-11-04T10:00:00.000Z', + number: 1, + by: { accountId: 'me', displayName: 'Me' }, + }, + }, + }, + ], + _links: { next: '/wiki/rest/api/search?cursor=abc' }, + } + }) + const [pages, comments] = (await atlassianActivity(api, 'confluence', WINDOW)).streams + expect( + pages?.events.map((event) => [event.document.id, event.action, event.approximateTime]) + ).toEqual([ + ['7', 'edited', true], + ['8', 'created', undefined], + ]) + expect(pages).toMatchObject({ more: true, scannedTo: '2026-11-04T10:00:00.000Z' }) + expect(comments?.events).toEqual([ + expect.objectContaining({ + action: 'commented', + document: expect.objectContaining({ id: '42', kind: 'page', title: 'Runbook' }), + }), + ]) + }) + + it('reads past a page of issues newer than the bound instead of stopping on it', async () => { + const issue = (key: string, created: string) => ({ + key, + fields: { summary: key, created, creator: { accountId: 'me' } }, + }) + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined + const body = (options as { body?: { jql?: string; nextPageToken?: string } } | undefined) + ?.body + if (!body?.jql?.includes('creator = currentUser()')) return { issues: [] } + return body.nextPageToken + ? { issues: [issue('ENG-1', '2026-11-07T10:00:00.000Z')] } + : { issues: [issue('ENG-3', '2026-11-08T10:00:00.000Z')], nextPageToken: 'p2' } + }) + const streams = (await atlassianActivity(api, 'jira', WINDOW)).streams + expect(streams.flatMap((stream) => stream.events.map((event) => event.document.id))).toEqual([ + 'ENG-3', + 'ENG-1', + ]) + expect(streams[0]).toMatchObject({ more: false, scannedTo: '2026-11-07T10:00:00.000Z' }) + }) + + it('reports an assigned Jira issue at its last update, marked approximate', async () => { + const api = client((path, options) => { + if (path === '/oauth/token/accessible-resources') return [site] + if (path !== '/ex/jira/cloud/rest/api/3/search/jql') return undefined + const jql = String((options as { body?: { jql?: string } } | undefined)?.body?.jql) + return jql.includes('assignee = currentUser()') + ? { + issues: [ + { + key: 'ENG-2', + fields: { + summary: 'Fix login', + updated: '2026-11-06T09:00:00.000+0000', + assignee: { accountId: 'me', displayName: 'Me' }, + reporter: { accountId: 'ann', displayName: 'Ann' }, + }, + }, + ], + } + : { issues: [] } + }) + const streams = (await atlassianActivity(api, 'jira', WINDOW)).streams + expect(streams.flatMap((stream) => stream.events)).toEqual([ + expect.objectContaining({ + action: 'assigned', + at: '2026-11-06T09:00:00.000Z', + approximateTime: true, + collaborators: ['Ann'], + }), + ]) + }) +}) diff --git a/apps/sim/lib/sim-search/live/activity.integration.ts b/apps/sim/lib/sim-search/live/activity.integration.ts new file mode 100644 index 00000000000..169b4fac221 --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity.integration.ts @@ -0,0 +1,111 @@ +/** + * `list_my_activity` for the organization Assistant against real Postgres: the copilot delegation + * bound to the member's own chat, the organization's source approvals and the member's own + * connections decide which sources are read and which the member is asked to connect. + */ +import { db } from '@sim/db' +import { + copilotChats, + member, + organization, + organizationSearchIntegration, + user, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' +import { listMyActivityServerTool } from '@/lib/mothership/tools/server/knowledge/my-activity' +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +vi.hoisted(() => vi.stubEnv('MY_ACTIVITY', 'true')) + +const org = generateId() +const readerId = generateId() +const otherId = generateId() +const readerChat = generateId() +const otherChat = generateId() + +function turn(userId: string, chatId: string) { + return { + userId, + organizationId: org, + chatId, + toolCallId: generateId(), + copilotToolExecution: true, + requestMode: 'assistant', + resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), + } +} + +beforeAll(async () => { + await db.insert(organization).values({ + id: org, + slug: org, + name: 'Assistant activity fixture', + createdAt: new Date(), + }) + await db.insert(user).values( + [readerId, otherId].map((id) => ({ + id, + name: 'Activity reader', + email: `${id}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + })) + ) + await db.insert(member).values([ + { id: generateId(), organizationId: org, userId: readerId, role: 'member' }, + { id: generateId(), organizationId: org, userId: otherId, role: 'member' }, + ]) + await db.insert(copilotChats).values([ + { id: readerChat, userId: readerId, organizationId: org, type: 'mothership' }, + { id: otherChat, userId: otherId, organizationId: org, type: 'mothership' }, + ]) + await db.insert(organizationSearchIntegration).values([ + { organizationId: org, connectorType: 'slack', approved: true }, + { organizationId: org, connectorType: 'gmail', approved: true }, + { organizationId: org, connectorType: 'jira', approved: false }, + { organizationId: org, connectorType: 'notion', approved: true }, + ]) +}) + +afterAll(async () => { + await db.delete(organization).where(eq(organization.id, org)) + await db.delete(user).where(inArray(user.id, [readerId, otherId])) + vi.unstubAllEnvs() +}) + +it('asks the member to connect each approved source that reports activity, and only those', async () => { + const result = await listMyActivityServerTool.execute({}, turn(readerId, readerChat)) + expect(result).toMatchObject({ + success: true, + data: { items: [], truncated: false, coverage: 'complete' }, + }) + const data = (result as { data: { sources: Record[] } }).data + expect(data.sources.map((source) => [source.source, source.status])).toEqual([ + ['gmail', 'not_connected'], + ['slack', 'not_connected'], + ]) + expect(data.sources[0]).toMatchObject({ + connect: { providerId: 'google-email', url: expect.stringContaining(`/${org}/`) }, + }) + expect((result as { message: string }).message).toContain('oauth_get_auth_link') +}) + +it('refuses a delegation naming another member’s chat', async () => { + const result = await listMyActivityServerTool.execute({}, turn(readerId, otherChat)) + expect(result).toMatchObject({ success: false, message: 'Conversation not found' }) +}) + +it('refuses a window longer than a quarter and a cursor it did not mint', async () => { + expect( + await listMyActivityServerTool.execute( + { startDate: '2026-01-01T00:00:00Z', endDate: '2026-06-01T00:00:00Z' }, + turn(readerId, readerChat) + ) + ).toMatchObject({ success: false, message: expect.stringContaining('92 days') }) + expect( + await listMyActivityServerTool.execute({ cursor: 'not-a-cursor' }, turn(readerId, readerChat)) + ).toMatchObject({ success: false, message: expect.stringContaining('Invalid cursor') }) +}) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts new file mode 100644 index 00000000000..0350235259e --- /dev/null +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -0,0 +1,496 @@ +import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { createLogger } from '@sim/logger' +import { canonicalJson } from '@sim/utils/object' +import { truncateAtCodePoint } from '@sim/utils/string' +import { + DEFAULT_ACTIVITY_TOP_K, + type ListMyActivityResult, + type LiveSearchProvider, + type LiveSourceStatus, + listMyActivityInputSchema, + MAX_ACTIVITY_WINDOW_DAYS, +} from '@/lib/api/contracts/mothership-assistant-tools' +import { fingerprint, instantScopePart } from '@/lib/api/cursor-binding' +import { admitContent } from '@/lib/core/application' +import { env } from '@/lib/core/config/env' +import { isFeatureEnabled } from '@/lib/core/config/feature-flags' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { resourceScopeFromOwner, resourceScopeKey } from '@/lib/core/resource-scope' +import { createPinnedConnectionPool } from '@/lib/core/security/input-validation.server' +import { createConcurrencyLimit, waitWithAbort } from '@/lib/core/utils/concurrency' +import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' +import { defineAuthorizedKnowledgeUseCase } from '@/lib/knowledge/application/authorized-knowledge-use-case' +import { resolveKnowledgeOrganizationContext } from '@/lib/knowledge/application/contexts' +import { knowledgeOperations } from '@/lib/knowledge/application/operations' +import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy' +import { isKnowledgeSourceUrl } from '@/lib/knowledge/search/source-url' +import { openLiveAccountSession } from '@/lib/sim-search/live/account-session' +import { listLiveAccounts, resolveListedLiveAccount } from '@/lib/sim-search/live/accounts' +import { + type AccountActivity, + type ActivityBound, + type ActivityEntry, + mergeActivityPage, + readActivityCursor, + writeActivityCursor, +} from '@/lib/sim-search/live/activity-page' +import { liveIntegrationsUrl } from '@/lib/sim-search/live/application' +import { + candidateFor, + compareAccounts, + safeContent, + verifyCandidates, +} from '@/lib/sim-search/live/candidates' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' +import { + LIVE_SEARCH_PROVIDER_CATALOG, + LIVE_SEARCH_PROVIDER_IDS, +} from '@/lib/sim-search/live/provider-catalog' +import { supportsActivity } from '@/lib/sim-search/live/providers' +import { liveReferenceOwner } from '@/lib/sim-search/live/reference' +import type { LiveAccount, NativeActivityEvent } from '@/lib/sim-search/live/types' +import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +const logger = createLogger('LiveActivity') + +const DAY_MS = 86_400_000 +const DEFAULT_WINDOW_DAYS = 7 +/** Accounts one call reads, as one search does. */ +const MAX_ACTIVITY_ACCOUNTS = 20 +/** Accounts resolving their credential and opening their session at once, as for search. */ +const ACCOUNT_OPEN_CONCURRENCY = 6 +/** Milliseconds a whole call may take, and one account once it gets a slot, as for search. */ +const ACTIVITY_DEADLINE_MS = 20_000 +const ACCOUNT_DEADLINE_MS = 12_000 +/** Characters of each entry's text the caller sees; read_document returns the rest. */ +const SNIPPET_CHARACTERS = 300 +/** Raw items each provider listing reads per page; at least a page's worth of entries. */ +const MIN_STREAM_ITEMS = 20 + +/** One activity page request: the caller's organization, the window and the page to read. */ +export interface ListMyActivityInput { + organizationId: string + startDate?: string + endDate?: string + source?: LiveSearchProvider + topK?: number + cursor?: string + signal?: AbortSignal + resultSecretRegistry?: ResolvedSecretTraceRegistry +} + +/** Whether `list_my_activity` is rolled out to this organization (the `my-activity` flag). */ +export function isMyActivityEnabled(organizationId: string): Promise { + return isFeatureEnabled('my-activity', { orgId: organizationId }) +} + +const INVALID_CURSOR_MESSAGE = + 'Invalid cursor. Continue with the same startDate, endDate, source and topK, or start again without a cursor.' + +/** The window a first page reads: the requested bounds, defaulted and clamped to now. */ +function resolveWindow(input: { startDate?: string; endDate?: string }, now: number) { + const requestedEnd = input.endDate ? Date.parse(input.endDate) : now + const end = Math.min(requestedEnd, now) + const start = input.startDate ? Date.parse(input.startDate) : end - DEFAULT_WINDOW_DAYS * DAY_MS + if (!Number.isFinite(start) || !Number.isFinite(end)) + throw new OrchestrationError('validation', 'startDate and endDate must be ISO datetimes') + if (start >= end) + throw new OrchestrationError( + 'validation', + input.startDate && start >= now + ? 'startDate is in the future; activity covers only what already happened.' + : 'endDate must be after startDate.' + ) + if (end - start > MAX_ACTIVITY_WINDOW_DAYS * DAY_MS) + throw new OrchestrationError( + 'validation', + `The window spans at most ${MAX_ACTIVITY_WINDOW_DAYS} days.` + ) + return { start: new Date(start).toISOString(), end: new Date(end).toISOString() } +} + +/** The connection a source's status asks the caller to make. */ +function connectHint(provider: LiveSearchProvider, organizationId: string) { + return { + providerId: LIVE_SEARCH_PROVIDER_CATALOG[provider].credentialProviderIds[0] ?? provider, + url: liveIntegrationsUrl({ organizationId }), + } +} + +/** An account's own activity as entries ready to merge, keyed within the account. */ +interface Entry extends ActivityEntry { + event: NativeActivityEvent + documentId: string +} + +/** The seen-key of an entry: short and opaque, since a cursor carries it. */ +function entryKey(event: NativeActivityEvent): string { + return fingerprint( + JSON.stringify([ + event.action, + event.document.container, + event.document.dedupeKey ?? event.document.id, + ]) + ).slice(0, 16) +} + +/** One account's page: what it read for the merge, or why it could not be read. */ +type AccountRead = AccountActivity & + ({ read: true; partial: boolean; message?: string } | { read: false; error: NativeSearchError }) + +type SourceStatus = LiveSourceStatus & { itemCount: number } + +function accountStatus(account: LiveAccount, status: Omit): SourceStatus { + return { + source: account.provider, + accountId: account.id, + displayName: account.displayName, + ...status, + } +} + +function failureStatus( + account: LiveAccount, + error: NativeSearchError, + organizationId: string +): SourceStatus { + if (error.status === 'reconnect') + return accountStatus(account, { + status: 'reconnect', + message: error.message, + connect: connectHint(account.provider, organizationId), + itemCount: 0, + }) + return accountStatus(account, { + status: 'failed', + reason: error.status, + message: error.message, + ...(error.retryAfterSeconds === undefined + ? {} + : { retryAfterSeconds: error.retryAfterSeconds }), + itemCount: 0, + }) +} + +/** + * The caller's own activity across the sources they connected in this organization, newest + * first, read live from each provider with the caller's own connection. Always the person the + * principal represents; a principal without one is refused. + */ +export const listMyActivity = defineAuthorizedKnowledgeUseCase({ + operation: knowledgeOperations.listActivity, + resolveContext: ({ input }: { input: ListMyActivityInput }) => + resolveKnowledgeOrganizationContext({ organizationId: input.organizationId }), + async execute({ principal, input }): Promise { + const userId = requirePrincipalSubjectUserId(principal) + const { organizationId } = input + const [, , enabled] = await Promise.all([ + /** Live provider results carry no stored provenance; they are projected through `safeContent`. */ + admitContent(principal, []), + requireOrganizationSearchAvailable(organizationId), + isMyActivityEnabled(organizationId), + ]) + if (!enabled) + throw new OrchestrationError( + 'forbidden', + 'Activity listing is not enabled for this organization' + ) + const parsed = listMyActivityInputSchema.parse({ + startDate: input.startDate, + endDate: input.endDate, + source: input.source, + topK: input.topK, + cursor: input.cursor, + }) + const topK = parsed.topK ?? DEFAULT_ACTIVITY_TOP_K + const owner = { organizationId } + const referenceOwner = liveReferenceOwner( + userId, + resourceScopeKey(resourceScopeFromOwner(owner)) + ) + const scope = fingerprint( + canonicalJson({ + user: userId, + organizationId, + startDate: instantScopePart(parsed.startDate), + endDate: instantScopePart(parsed.endDate), + source: parsed.source, + topK, + }) + ) + const cursor = parsed.cursor + ? readActivityCursor(parsed.cursor, scope, env.BETTER_AUTH_SECRET) + : undefined + if (parsed.cursor && !cursor) throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE) + const window = cursor ?? resolveWindow(parsed, Date.now()) + input.signal?.throwIfAborted() + + const [policies, connected, approvals] = await Promise.all([ + loadLiveSearchPolicies(owner), + listLiveAccounts(owner, userId), + /** Later pages continue the accounts their cursor names, so only the first reports the rest. */ + cursor ? undefined : listOrganizationSearchApprovals(organizationId), + ]) + const accounts = connected + .filter((account) => !parsed.source || account.provider === parsed.source) + .sort(compareAccounts) + const readable = (account: LiveAccount) => + supportsActivity(account.provider) && + account.type !== 'managed_mcp' && + account.type !== 'admin_source' + const eligible = accounts.filter(readable) + const selected = cursor + ? eligible.filter((account) => cursor.accounts[account.id]) + : eligible.slice(0, MAX_ACTIVITY_ACCOUNTS) + const statuses: SourceStatus[] = approvals + ? [ + ...LIVE_SEARCH_PROVIDER_IDS.filter( + (provider) => + (!parsed.source || provider === parsed.source) && + supportsActivity(provider) && + approvals.get(provider) === true && + !accounts.some((account) => account.provider === provider) + ).map( + (provider): SourceStatus => ({ + source: provider, + status: 'not_connected', + message: `Connect your ${provider} account to include it.`, + connect: connectHint(provider, organizationId), + itemCount: 0, + }) + ), + ...accounts + .filter((account) => !readable(account)) + .map((account) => + accountStatus(account, { + status: 'unsupported', + message: 'This source does not report activity yet.', + itemCount: 0, + }) + ), + ] + : [] + if ( + approvals && + parsed.source && + !supportsActivity(parsed.source) && + !accounts.some((account) => account.provider === parsed.source) + ) + statuses.push({ + source: parsed.source, + status: 'unsupported', + message: 'This source does not report activity yet.', + itemCount: 0, + }) + /** An account a cursor continues that is no longer connected leaves its activity unread. */ + for (const [accountId, bound] of Object.entries(cursor?.accounts ?? {})) { + const source = LIVE_SEARCH_PROVIDER_IDS.find((provider) => provider === bound.source) + if (source && !eligible.some((account) => account.id === accountId)) + statuses.push({ + source, + accountId, + status: 'failed', + reason: 'unavailable', + message: 'This account is no longer connected; its remaining activity was not read.', + itemCount: 0, + }) + } + /** Every page reports the accounts no page reads, so its coverage never reads complete. */ + for (const account of eligible.slice(MAX_ACTIVITY_ACCOUNTS)) + statuses.push( + accountStatus(account, { + status: 'failed', + reason: 'unavailable', + message: `One call reads at most ${MAX_ACTIVITY_ACCOUNTS} accounts. Pass source to read this one.`, + itemCount: 0, + }) + ) + /** The window's end is exclusive; a continuation's bound is the inclusive instant it resumes at. */ + const boundOf = (account: LiveAccount): ActivityBound => + cursor?.accounts[account.id] ?? { + end: new Date(Date.parse(window.end) - 1).toISOString(), + seen: [], + } + + const deadline = AbortSignal.timeout(ACTIVITY_DEADLINE_MS) + const callSignal = input.signal ? AbortSignal.any([input.signal, deadline]) : deadline + const opening = createConcurrencyLimit(ACCOUNT_OPEN_CONCURRENCY) + const pool = createPinnedConnectionPool() + const streamItems = Math.max(MIN_STREAM_ITEMS, topK) + const readAccount = async (account: LiveAccount): Promise => { + const settled = new AbortController() + /** Aborts at the account's own deadline, which starts once it gets a slot to open. */ + const deadline = new AbortController() + const signal = AbortSignal.any([callSignal, settled.signal, deadline.signal]) + let session: Awaited> | undefined + try { + session = await opening(async () => { + const expiry = AbortSignal.timeout(ACCOUNT_DEADLINE_MS) + expiry.addEventListener('abort', () => deadline.abort(expiry.reason), { + once: true, + signal: settled.signal, + }) + const resolved = await waitWithAbort( + resolveListedLiveAccount(owner, userId, account, signal), + signal + ) + return waitWithAbort( + openLiveAccountSession({ owner, userId, resolved, policies, signal, pool }), + signal + ) + }) + const bound = boundOf(account) + const page = await session.activity({ + start: window.start, + end: bound.end, + limit: streamItems, + scopes: account.scopes, + signal, + }) + const events = page.streams.flatMap((stream) => stream.events) + const candidates = events.map((event) => + candidateFor(event.document, account, referenceOwner) + ) + const verification = await verifyCandidates(session, candidates) + const permitted = new Set(verification.permitted) + const documentIds = new Map( + candidates.flatMap((candidate, index) => { + const event = events[index] + return event && permitted.has(candidate) ? [[event, candidate.documentId] as const] : [] + }) + ) + return { + accountId: account.id, + bound, + read: true, + partial: Boolean(page.partial || verification.unverified || session.servicePartial), + message: page.message, + streams: page.streams.map((stream) => ({ + more: stream.more, + scannedTo: stream.scannedTo, + entries: stream.events.flatMap((event): Entry[] => { + const documentId = documentIds.get(event) + return documentId ? [{ at: event.at, key: entryKey(event), event, documentId }] : [] + }), + })), + } + } catch (error) { + input.signal?.throwIfAborted() + if (!(error instanceof NativeSearchError)) + logger.warn('Activity listing failed for an account', { + provider: account.provider, + error: 'unexpected_error', + }) + return { + accountId: account.id, + bound: boundOf(account), + read: false, + error: + error instanceof NativeSearchError + ? error + : signal.aborted + ? new NativeSearchError('timeout', 'This source did not answer in time. Try again.') + : new NativeSearchError( + 'unavailable', + 'This source could not be read. Check the connection and try again.' + ), + } + } finally { + settled.abort() + await session?.close() + } + } + let reads: AccountRead[] + try { + reads = await Promise.all(selected.map(readAccount)) + } finally { + pool.destroy() + } + input.signal?.throwIfAborted() + + const merged = mergeActivityPage(reads, window, topK) + const registry = input.resultSecretRegistry + const byId = new Map(selected.map((account) => [account.id, account])) + const itemCounts = new Map() + const items = merged.entries.flatMap(({ event, documentId, accountId }) => { + const account = byId.get(accountId) + if (!account) return [] + itemCounts.set(accountId, (itemCounts.get(accountId) ?? 0) + 1) + const { document } = event + return [ + { + documentId, + timestamp: new Date(event.at).toISOString(), + source: account.provider, + accountId, + action: event.action, + title: safeContent(document.title, registry), + url: isKnowledgeSourceUrl(document.url) ? document.url : null, + ...(document.containerName && document.containerName !== document.title + ? { container: safeContent(document.containerName, registry) } + : {}), + collaborators: event.collaborators.map((name) => safeContent(name, registry)), + snippet: truncateAtCodePoint( + safeContent(document.content, registry).trim(), + SNIPPET_CHARACTERS + ), + ...(event.approximateTime ? { approximateTime: true as const } : {}), + }, + ] + }) + const stalled = new Set(merged.stalled) + for (const read of reads) { + const account = byId.get(read.accountId) + if (!account) continue + if (!read.read) { + statuses.push(failureStatus(account, read.error, organizationId)) + continue + } + const stopped = stalled.has(account.id) + statuses.push( + accountStatus(account, { + status: read.partial || stopped ? 'partial' : 'ok', + ...(stopped + ? { + message: + 'More activity at one instant than a page can return; later pages skip it.', + } + : read.partial && read.message + ? { message: read.message } + : {}), + itemCount: itemCounts.get(account.id) ?? 0, + }) + ) + } + const nextCursor = merged.next + ? writeActivityCursor( + { + v: 1, + scope, + start: window.start, + end: window.end, + accounts: Object.fromEntries( + Object.entries(merged.next).map(([accountId, bound]) => [ + accountId, + { ...bound, source: byId.get(accountId)?.provider ?? bound.source }, + ]) + ), + }, + env.BETTER_AUTH_SECRET + ) + : undefined + return { + window: { startDate: window.start, endDate: window.end }, + items, + truncated: Boolean(nextCursor), + ...(nextCursor ? { nextCursor } : {}), + coverage: statuses.some((status) => + ['partial', 'reconnect', 'failed'].includes(status.status) + ) + ? 'partial' + : 'complete', + sources: statuses, + } + }, +}) diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 6198f8365a0..cbdfebf49f8 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -2,7 +2,6 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js' import { requirePrincipalSubjectUserId } from '@sim/auth/principal' import { safeCompare } from '@sim/security/compare' import { hmacSha256Hex } from '@sim/security/hmac' -import { mapWithConcurrency } from '@sim/utils/concurrency' import { canonicalJson } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' import { z } from 'zod' @@ -66,6 +65,13 @@ import { resolveListedLiveAccount, resolveLiveAccount, } from '@/lib/sim-search/live/accounts' +import { + candidateFor, + compareAccounts, + type LiveCandidate, + safeContent, + verifyCandidates, +} from '@/lib/sim-search/live/candidates' import { dateSortDirection, hasDateBounds, @@ -83,7 +89,6 @@ import { import { isManagedSearchMcpProvider } from '@/lib/sim-search/live/managed-mcp-config' import { joinMessages } from '@/lib/sim-search/live/pages' import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' -import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog' import { filtersByPerson, liveSearchGuidance } from '@/lib/sim-search/live/providers' import { LiveReadError } from '@/lib/sim-search/live/read-error' import { encodedWindowEnd, READ_WINDOW_CHARACTERS } from '@/lib/sim-search/live/read-window' @@ -96,7 +101,6 @@ import { } from '@/lib/sim-search/live/reference' import { queryRelevance } from '@/lib/sim-search/live/text-match' import type { LiveAccount, NativeDocument } from '@/lib/sim-search/live/types' -import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' const boundContinuationSchema = z @@ -171,13 +175,6 @@ interface LiveSearchOptions { } export type LiveSearchInput = ResourceOwner & LiveSearchOptions -function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { - if (!registry) return content - const projected = projectResolvedSecretModelContent(content, registry) - if (!projected.safe || typeof projected.value !== 'string') - throw new Error('Search content projection is unavailable') - return projected.value -} export function matchesLiveFilters( document: NativeDocument, documentId: string, @@ -205,35 +202,6 @@ export function matchesLiveFilters( } return true } -/** A provider result with the ID that locates it within its account. */ -interface LiveCandidate { - document: NativeDocument - documentId: string -} - -function candidateFor( - document: NativeDocument, - account: LiveAccount, - owner: string -): LiveCandidate { - return { - document, - documentId: encodeLiveReference( - { - account: account.id, - provider: account.provider, - id: document.id, - ...(document.container ? { container: document.container } : {}), - ...(document.kind ? { kind: document.kind } : {}), - ...(document.revision ? { revision: document.revision } : {}), - ...(document.connectionBinding ? { connectionBinding: document.connectionBinding } : {}), - ...(document.threadId ? { threadId: document.threadId } : {}), - }, - owner - ), - } -} - function resultFor( { document, documentId }: LiveCandidate, account: LiveAccount, @@ -284,8 +252,6 @@ const SEARCH_DEADLINE_MS = 20_000 const ACCOUNT_DEADLINE_MS = 12_000 /** An account reaching its turn with less than this left before its deadline is not searched. */ const ACCOUNT_START_FLOOR_MS = 1500 -/** Candidates verified at once; each verification is one or more provider requests. */ -const VERIFY_CONCURRENCY = 5 const MAX_ACCOUNTS = 20 /** Account status when a merge cut results that its cursor would skip. */ @@ -325,35 +291,6 @@ function readWindowEnd(content: string, start: number, scaledWindow: boolean | u : standardEnd } -/** - * Verifies candidates in rank order. A revoked grant fails the whole account; any other - * verification failure only omits that candidate, and is reported as incomplete coverage. - */ -async function verifyCandidates( - session: LiveAccountSession, - candidates: LiveCandidate[], - onVerified?: (candidate: LiveCandidate, permitted: boolean) => void -) { - const outcomes = await mapWithConcurrency(candidates, VERIFY_CONCURRENCY, async (candidate) => { - const outcome = await session.verify(candidate.document).then( - (permitted) => (permitted ? ('permitted' as const) : ('denied' as const)), - (error: unknown) => { - if (error instanceof NativeSearchError && error.status === 'reconnect') throw error - return error instanceof NativeSearchError && error.status === 'rate_limited' - ? ('rate_limited' as const) - : ('unverified' as const) - } - ) - onVerified?.(candidate, outcome === 'permitted') - return outcome - }) - return { - permitted: candidates.filter((_, index) => outcomes[index] === 'permitted'), - unverified: outcomes.some((outcome) => outcome === 'unverified' || outcome === 'rate_limited'), - rateLimited: outcomes.includes('rate_limited'), - } -} - /** Top results per account read for a passage when their provider returns only an excerpt. */ const PREVIEW_READS = 3 /** A slow preview read keeps the provider's excerpt rather than delaying the search. */ @@ -449,14 +386,12 @@ function targetsAccount(query: NativeSearchQuery, account: LiveAccount): boolean return query.provider === account.provider && (!query.accountId || query.accountId === account.id) } -/** Stable account order so equal-rank results from different accounts always merge the same way. */ -function compareAccounts(left: LiveAccount, right: LiveAccount): number { - return ( - LIVE_SEARCH_PROVIDER_IDS.indexOf(left.provider) - - LIVE_SEARCH_PROVIDER_IDS.indexOf(right.provider) || - compareStrings(left.displayName, right.displayName) || - compareStrings(left.id, right.id) - ) +/** The page where the caller connects their own accounts in this scope. */ +export function liveIntegrationsUrl(owner: ResourceOwner): string { + const path = owner.organizationId + ? organizationRoutes(owner.organizationId).integrations + : `/workspace/${owner.workspaceId}/integrations` + return new URL(path, getBaseUrl()).href } /** @@ -468,10 +403,7 @@ function nothingSearchedGuidance( source: string | undefined, hasOtherAccounts: boolean ): string { - const path = owner.organizationId - ? organizationRoutes(owner.organizationId).integrations - : `/workspace/${owner.workspaceId}/integrations` - const connect = new URL(path, getBaseUrl()).href + const connect = liveIntegrationsUrl(owner) return source && hasOtherAccounts ? `Nothing was searched: you have no connected ${source} account here. Connect one at ${connect}, or search without the source filter.` : `Nothing was searched: you have no connected sources here. Connect your accounts at ${connect}, then search again.` diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index 3077bda4986..1f0b7a2fd69 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -1,3 +1,4 @@ +import { collaboratorNames, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { array, @@ -8,6 +9,7 @@ import { textContent, } from '@/lib/sim-search/live/http' import { interleaveByRank } from '@/lib/sim-search/live/pages' +import type { LiveSearchPolicy } from '@/lib/sim-search/live/policy-schema' import { providerText } from '@/lib/sim-search/live/text' import { confluenceTextClause, @@ -15,6 +17,10 @@ import { jiraTextClause, } from '@/lib/sim-search/live/text-match' import type { + NativeActivityEvent, + NativeActivityInput, + NativeActivityPage, + NativeActivityStream, NativeClient, NativeDocument, NativePage, @@ -209,6 +215,24 @@ async function atlassianPersonClause( return `(assignee = ${user} OR reporter = ${user})` } +/** The sites a grant can reach that the source settings allow. */ +async function policySites(client: NativeClient, policy: LiveSearchPolicy | undefined) { + return (await sites(client)).filter( + (site) => + !policy?.sites.length || policy.sites.includes(new URL(string(site.url)).host.toLowerCase()) + ) +} + +/** The JQL or CQL clause keeping a query to the projects or spaces the source settings select. */ +function policyClause( + provider: 'jira' | 'confluence', + policy: LiveSearchPolicy | undefined +): string | undefined { + return policy?.mode === 'selected' + ? `(${policy.included.map((id) => `${provider === 'jira' ? 'project' : 'space'} = ${JSON.stringify(id)}`).join(' OR ')})` + : undefined +} + export async function searchAtlassian( client: NativeClient, provider: 'jira' | 'confluence', @@ -220,11 +244,7 @@ export async function searchAtlassian( ? confluenceTextClause(text, input.textMatch) : '' if (confluenceClause === undefined) return { documents: [] } - const allSites = (await sites(client)).filter( - (site) => - !input.policy?.sites.length || - input.policy.sites.includes(new URL(string(site.url)).host.toLowerCase()) - ) + const allSites = await policySites(client, input.policy) const selected = input.native?.project ? allSites.filter((site) => string(site.id) === input.native?.project) : allSites.slice(0, 4) @@ -234,24 +254,12 @@ export async function searchAtlassian( 'No accessible Atlassian site matches this account or site ID.' ) const single = selected.length === 1 - const policyScope = - input.policy?.mode === 'selected' - ? `(${input.policy.included.map((id) => `${provider === 'jira' ? 'project' : 'space'} = ${JSON.stringify(id)}`).join(' OR ')})` - : undefined + const policyScope = policyClause(provider, input.policy) const dates = nativeDateBounds(input) const field = provider === 'jira' ? 'updated' : 'lastmodified' const person = await atlassianPersonClause(client, provider, input.involving, selected) const scope = - [ - policyScope, - person, - dates.start - ? `${field} >= "${new Date(Date.parse(dates.start) - 86400000).toISOString().slice(0, 10)}"` - : '', - dates.end - ? `${field} <= "${new Date(Date.parse(dates.end) + 86400000).toISOString().slice(0, 10)}"` - : '', - ] + [policyScope, person, ...atlassianDateClauses(field, dates.start, dates.end)] .filter(Boolean) .join(' AND ') || undefined const direction = dateSortDirection(input.filters) @@ -364,6 +372,324 @@ export async function searchAtlassian( } } +/** Sites one activity call reads, as for search. */ +const MAX_ACTIVITY_SITES = 4 + +/** + * JQL and CQL compare dates in the member's profile time zone at day precision, so each bound is + * widened by a day; returned instants are checked exactly. + */ +function atlassianDateClauses(field: string, start?: string, end?: string): string[] { + const day = (instant: string, offsetDays: number) => + new Date(Date.parse(instant) + offsetDays * 86_400_000).toISOString().slice(0, 10) + return [ + start ? `${field} >= "${day(start, -1)}"` : '', + end ? `${field} <= "${day(end, 1)}"` : '', + ].filter(Boolean) +} + +/** A JQL or CQL query of every clause given, newest first by `field`. */ +function activityQuery(clauses: (string | undefined)[], field: string): string { + return `${clauses.filter(Boolean).join(' AND ')} ORDER BY ${field} DESC` +} + +function displayNames(people: unknown[], except?: string): string[] { + return collaboratorNames( + people + .map(object) + .filter((person) => string(person.accountId) && string(person.accountId) !== except) + .map((person) => string(person.displayName)) + ) +} + +/** Provider pages one listing may read to get past items newer than its end. */ +const MAX_ACTIVITY_PAGES = 3 + +/** + * Reads a newest-first listing until a page reaches items at or before `end`. The widened date + * range returns items newer than `end` first, which a continuation has already returned, so + * stopping at the first page would leave a busy day's older items unreachable. + */ +async function readPastEnd( + readPage: (cursor?: string) => Promise<{ rows: Record[]; next?: string }>, + sortKey: (row: Record) => string, + end: string +) { + const rows: Record[] = [] + let next: string | undefined + for (let page = 0; page < MAX_ACTIVITY_PAGES; page++) { + const result = await readPage(next) + rows.push(...result.rows) + next = result.next + if (!next || result.rows.some((row) => Date.parse(sortKey(row)) <= Date.parse(end))) break + } + return { rows, more: Boolean(next) } +} + +/** The base URL of a site's pages, without a trailing slash. */ +function siteOrigin(site: Record): string { + return string(site.url).replace(/\/$/, '') +} + +/** + * The two Jira listings: issues the member created, by creation, and issues assigned to them, by + * last update. Jira's `updatedBy()` cannot be bounded reliably by date, so an assigned issue's + * time is its last update, by anyone. + */ +const JIRA_ACTIVITY = { + created: { field: 'created', self: 'creator', other: 'assignee' }, + assigned: { field: 'updated', self: 'assignee', other: 'reporter' }, +} as const + +async function jiraActivityStream( + client: NativeClient, + site: Record, + input: NativeActivityInput, + kind: keyof typeof JIRA_ACTIVITY +): Promise { + const cloudId = string(site.id) + const { field, self, other } = JIRA_ACTIVITY[kind] + const sortKey = (row: Record) => string(object(row.fields)[field]) + const { rows, more } = await readPastEnd( + async (cursor) => { + const data = object( + await client.json(`/ex/jira/${segment(cloudId)}/rest/api/3/search/jql`, { + body: { + jql: activityQuery( + [ + policyClause('jira', input.policy), + `${self} = currentUser()`, + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ), + maxResults: input.limit, + fields: [ + 'summary', + 'description', + 'status', + 'created', + 'updated', + 'creator', + 'reporter', + 'assignee', + ], + ...(cursor ? { nextPageToken: cursor } : {}), + }, + signal: input.signal, + }) + ) + return { rows: array(data.issues), next: string(data.nextPageToken) || undefined } + }, + sortKey, + input.end + ) + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const fields = object(row.fields) + const at = string(fields[field]) + if (!Number.isFinite(Date.parse(at))) return [] + return [ + { + document: issue(row, cloudId, siteOrigin(site)), + at: new Date(at).toISOString(), + action: kind, + collaborators: displayNames([fields[other]], string(object(fields[self]).accountId)), + ...(kind === 'assigned' ? { approximateTime: true as const } : {}), + }, + ] + }), + more, + scannedTo: oldestInstant(rows.map(sortKey)), + } +} + +/** One Confluence CQL listing for activity: its rows and whether more follow. */ +async function confluenceActivitySearch( + client: NativeClient, + site: Record, + input: NativeActivityInput, + clauses: string[], + field: string, + expand: string, + sortKey: (row: Record) => string +) { + const cql = activityQuery( + [ + clauses[0], + policyClause('confluence', input.policy), + ...clauses.slice(1), + ...atlassianDateClauses(field, input.start, input.end), + ], + field + ) + return readPastEnd( + async (cursor) => { + const data = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/search`, { + query: { cql, limit: String(input.limit), expand, ...(cursor ? { cursor } : {}) }, + signal: input.signal, + }) + ) + const next = string(object(data._links).next) + return { + rows: array(data.results), + next: next + ? (new URL(next, 'https://api.atlassian.com').searchParams.get('cursor') ?? undefined) + : undefined, + } + }, + sortKey, + input.end + ) +} + +/** + * Pages and blog posts the member contributed to, newest first by last modification. When the + * last version is the member's, its time is their edit; otherwise the time is someone else's + * later edit and is marked approximate. + */ +async function confluencePageStream( + client: NativeClient, + site: Record, + input: NativeActivityInput, + accountId: string +): Promise { + const modifiedAt = (row: Record) => + string(object(object(row.content).version).when) || string(row.lastModified) + const { rows, more } = await confluenceActivitySearch( + client, + site, + input, + ['type IN (page, blogpost)', 'contributor = currentUser()'], + 'lastmodified', + 'content.version,content.space,content.history', + modifiedAt + ) + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const document = page(row, string(site.id), siteOrigin(site)) + const content = object(row.content) + const version = object(content.version) + if (!document?.modifiedAt || !Number.isFinite(Date.parse(document.modifiedAt))) return [] + const mine = Boolean(accountId) && string(object(version.by).accountId) === accountId + return [ + { + document, + at: new Date(document.modifiedAt).toISOString(), + action: mine && version.number === 1 ? 'created' : 'edited', + collaborators: displayNames( + [object(content.history).createdBy, version.by], + accountId || undefined + ), + ...(mine ? {} : { approximateTime: true as const }), + }, + ] + }), + more, + scannedTo: oldestInstant(rows.map(modifiedAt)), + } +} + +/** + * Comments the member wrote, newest first. A comment is not readable on its own, so its entry + * reads the page or blog post it belongs to and links to the comment itself. + */ +async function confluenceCommentStream( + client: NativeClient, + site: Record, + input: NativeActivityInput +): Promise { + const cloudId = string(site.id) + const createdAt = (row: Record) => + string(object(object(row.content).history).createdDate) + const { rows, more } = await confluenceActivitySearch( + client, + site, + input, + ['type = comment', 'creator = currentUser()'], + 'created', + 'content.container,content.history,content.space', + createdAt + ) + return { + events: rows.flatMap((row): NativeActivityEvent[] => { + const content = object(row.content) + const container = object(content.container) + const kind = string(container.type) + const at = createdAt(row) + if ((kind !== 'page' && kind !== 'blogpost') || !string(container.id)) return [] + if (!Number.isFinite(Date.parse(at))) return [] + const spaceKey = string(object(content.space).key) + return [ + { + document: { + id: string(container.id), + /** Each comment is its own entry, though several read the same page. */ + dedupeKey: `comment:${string(content.id)}`, + kind, + ...(spaceKey ? { accessMetadata: { spaceKey } } : {}), + container: cloudId, + title: string(container.title) || string(row.title), + url: `${siteOrigin(site)}/wiki${string(object(content._links).webui) || string(row.url)}`, + content: providerText(string(row.excerpt).replace(/@@@(?:end)?hl@@@/g, ''), 'html'), + modifiedAt: at, + }, + at: new Date(at).toISOString(), + action: 'commented', + collaborators: [], + }, + ] + }), + more, + scannedTo: oldestInstant(rows.map(createdAt)), + } +} + +/** + * The member's Jira or Confluence activity on each site the grant reaches (up to four), one + * newest-first listing per kind and site. + */ +export async function atlassianActivity( + client: NativeClient, + provider: 'jira' | 'confluence', + input: NativeActivityInput +): Promise { + const allSites = await policySites(client, input.policy) + if (!allSites.length) + throw new NativeSearchError('reconnect', 'No accessible Atlassian site matches this account.') + const selected = allSites.slice(0, MAX_ACTIVITY_SITES) + const streams = await Promise.all( + selected.map(async (site) => { + if (provider === 'jira') + return Promise.all([ + jiraActivityStream(client, site, input, 'created'), + jiraActivityStream(client, site, input, 'assigned'), + ]) + const current = object( + await client.json(`/ex/confluence/${segment(string(site.id))}/wiki/rest/api/user/current`, { + memo: true, + signal: input.signal, + }) + ) + return Promise.all([ + confluencePageStream(client, site, input, string(current.accountId)), + confluenceCommentStream(client, site, input), + ]) + }) + ) + const skipped = allSites.length > selected.length + return { + streams: streams.flat(), + ...(skipped + ? { + partial: true, + message: `Activity covers the first ${MAX_ACTIVITY_SITES} accessible Atlassian sites.`, + } + : {}), + } +} + export async function readAtlassian( client: NativeClient, provider: 'jira' | 'confluence', diff --git a/apps/sim/lib/sim-search/live/candidates.ts b/apps/sim/lib/sim-search/live/candidates.ts new file mode 100644 index 00000000000..ef0971a3156 --- /dev/null +++ b/apps/sim/lib/sim-search/live/candidates.ts @@ -0,0 +1,90 @@ +import { mapWithConcurrency } from '@sim/utils/concurrency' +import { compareStrings } from '@sim/utils/string' +import type { LiveAccountSession } from '@/lib/sim-search/live/account-session' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import { LIVE_SEARCH_PROVIDER_IDS } from '@/lib/sim-search/live/provider-catalog' +import { encodeLiveReference } from '@/lib/sim-search/live/reference' +import type { LiveAccount, NativeDocument } from '@/lib/sim-search/live/types' +import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' +import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +/** Candidates verified at once; each verification is one or more provider requests. */ +const VERIFY_CONCURRENCY = 5 + +/** Provider text as the caller may see it: resolved secrets the run supplied are projected out. */ +export function safeContent(content: string, registry?: ResolvedSecretTraceRegistry): string { + if (!registry) return content + const projected = projectResolvedSecretModelContent(content, registry) + if (!projected.safe || typeof projected.value !== 'string') + throw new Error('Search content projection is unavailable') + return projected.value +} + +/** A provider result with the ID that locates it within its account. */ +export interface LiveCandidate { + document: NativeDocument + documentId: string +} + +/** A provider result with its document ID: a reference bound to this account and `owner`. */ +export function candidateFor( + document: NativeDocument, + account: LiveAccount, + owner: string +): LiveCandidate { + return { + document, + documentId: encodeLiveReference( + { + account: account.id, + provider: account.provider, + id: document.id, + ...(document.container ? { container: document.container } : {}), + ...(document.kind ? { kind: document.kind } : {}), + ...(document.revision ? { revision: document.revision } : {}), + ...(document.connectionBinding ? { connectionBinding: document.connectionBinding } : {}), + ...(document.threadId ? { threadId: document.threadId } : {}), + }, + owner + ), + } +} + +/** + * Verifies candidates in rank order. A revoked grant fails the whole account; any other + * verification failure only omits that candidate, and is reported as incomplete coverage. + */ +export async function verifyCandidates( + session: LiveAccountSession, + candidates: LiveCandidate[], + onVerified?: (candidate: LiveCandidate, permitted: boolean) => void +) { + const outcomes = await mapWithConcurrency(candidates, VERIFY_CONCURRENCY, async (candidate) => { + const outcome = await session.verify(candidate.document).then( + (permitted) => (permitted ? ('permitted' as const) : ('denied' as const)), + (error: unknown) => { + if (error instanceof NativeSearchError && error.status === 'reconnect') throw error + return error instanceof NativeSearchError && error.status === 'rate_limited' + ? ('rate_limited' as const) + : ('unverified' as const) + } + ) + onVerified?.(candidate, outcome === 'permitted') + return outcome + }) + return { + permitted: candidates.filter((_, index) => outcomes[index] === 'permitted'), + unverified: outcomes.some((outcome) => outcome === 'unverified' || outcome === 'rate_limited'), + rateLimited: outcomes.includes('rate_limited'), + } +} + +/** Stable account order so equal-rank results from different accounts always merge the same way. */ +export function compareAccounts(left: LiveAccount, right: LiveAccount): number { + return ( + LIVE_SEARCH_PROVIDER_IDS.indexOf(left.provider) - + LIVE_SEARCH_PROVIDER_IDS.indexOf(right.provider) || + compareStrings(left.displayName, right.displayName) || + compareStrings(left.id, right.id) + ) +} diff --git a/apps/sim/lib/sim-search/live/google.ts b/apps/sim/lib/sim-search/live/google.ts index 1942c5ec9df..bce030e3cdb 100644 --- a/apps/sim/lib/sim-search/live/google.ts +++ b/apps/sim/lib/sim-search/live/google.ts @@ -2,6 +2,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency' import { toArray } from '@sim/utils/object' import { compareStrings, truncate } from '@sim/utils/string' import { zonedWallClockToUtc } from '@sim/utils/timezone' +import { collaboratorNames, oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, hasDateBounds, @@ -15,6 +16,9 @@ import { interleaveByRank } from '@/lib/sim-search/live/pages' import { permitsResources } from '@/lib/sim-search/live/policy' import { providerText } from '@/lib/sim-search/live/text' import type { + NativeActivityEvent, + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -231,11 +235,26 @@ const GMAIL_METADATA_CONCURRENCY = 10 /** Only the fields a result uses; labels double as member-policy evidence. */ const GMAIL_METADATA_FIELDS = 'id,labelIds,snippet,internalDate,payload/headers' +/** A message header's value by its lowercase name, or empty when the message has none. */ +function gmailHeader(row: Record, name: string): string { + return string( + array(object(row.payload).headers).find((h) => string(h.name).toLowerCase() === name)?.value + ) +} + +/** + * Gmail `after:`/`before:` take whole seconds and compare exclusively, so each bound widens by a + * second; results are checked against the exact instants. + */ +function gmailDateClauses(start?: string, end?: string): string[] { + return [ + start ? `after:${Math.floor(Date.parse(start) / 1000) - 1}` : '', + end ? `before:${Math.ceil(Date.parse(end) / 1000) + 1}` : '', + ].filter(Boolean) +} + function gmailDocument(row: Record): NativeDocument { - const payload = object(row.payload) - const headers = array(payload.headers) - const header = (name: string) => - string(headers.find((h) => string(h.name).toLowerCase() === name)?.value) + const header = (name: string) => gmailHeader(row, name) const timestamp = Number(row.internalDate) return { ...(Array.isArray(row.labelIds) @@ -273,8 +292,7 @@ export async function searchGmail( const query = [ text ? (dates.start || dates.end || person ? `(${text})` : text) : '', person, - dates.start ? `after:${Math.floor(Date.parse(dates.start) / 1000) - 1}` : '', - dates.end ? `before:${Math.ceil(Date.parse(dates.end) / 1000) + 1}` : '', + ...gmailDateClauses(dates.start, dates.end), ] .filter(Boolean) .join(' ') @@ -311,6 +329,86 @@ export async function searchGmail( } } +/** Gmail lists at most this many sent messages per activity page; each costs a metadata read. */ +const GMAIL_ACTIVITY_PAGE_SIZE = 20 + +/** The display name, or else the address, of each mailbox in an address-list header. */ +function mailParticipants(value: string): string[] { + return (value.match(/(?:"[^"]*"|[^,])+/g) ?? []).flatMap((entry) => { + const named = entry.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/) + const label = named ? named[1].trim() || named[2].trim() : entry.trim() + return label ? [label] : [] + }) +} + +/** + * Mail the connected member sent, newest first. A message answering another (it carries + * In-Reply-To) is a reply; its recipients are its collaborators. + */ +export async function gmailActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + const data = object( + await client.json('/gmail/v1/users/me/messages', { + query: { + /** + * The inclusive end widens only to its own whole second, so a continuation rereads at most + * that second's messages rather than a page of newer ones. + */ + q: [ + 'in:sent', + ...gmailDateClauses(input.start), + `before:${Math.floor(Date.parse(input.end) / 1000) + 1}`, + ].join(' '), + maxResults: String(Math.min(input.limit, GMAIL_ACTIVITY_PAGE_SIZE)), + }, + }) + ) + const rows = await mapWithConcurrency( + array(data.messages), + GMAIL_METADATA_CONCURRENCY, + async (message) => + object( + await client.json(`/gmail/v1/users/me/messages/${segment(string(message.id))}`, { + query: { + format: 'metadata', + metadataHeaders: ['Subject', 'From', 'To', 'Cc', 'In-Reply-To'], + fields: GMAIL_METADATA_FIELDS, + }, + }) + ) + ) + const documents = rows.map((row) => ({ + document: gmailDocument(row), + replied: Boolean(gmailHeader(row, 'in-reply-to')), + recipients: [ + ...mailParticipants(gmailHeader(row, 'to')), + ...mailParticipants(gmailHeader(row, 'cc')), + ], + })) + return { + streams: [ + { + events: documents.flatMap(({ document, replied, recipients }) => + document.modifiedAt + ? [ + { + document, + at: document.modifiedAt, + action: replied ? ('replied' as const) : ('sent' as const), + collaborators: collaboratorNames(recipients), + }, + ] + : [] + ), + more: Boolean(string(data.nextPageToken)), + scannedTo: oldestInstant(documents.map(({ document }) => document.modifiedAt)), + }, + ], + } +} + /** The response byte cap does not bound recursive MIME depth or per-part processing work. */ const GMAIL_MIME_DEPTH_LIMIT = 32 const GMAIL_MIME_PART_LIMIT = 256 @@ -696,6 +794,135 @@ export async function searchCalendar( } } +/** + * Calendar lists a range oldest first, so activity reads the window newest first in slices of + * this length, each read whole before the next older one. + */ +const CALENDAR_ACTIVITY_SLICE_MS = 7 * 86_400_000 +/** Calendar requests one activity call makes across its slices. */ +const CALENDAR_ACTIVITY_REQUESTS = 6 +/** Personal blocks Calendar records as events, which nobody attends. */ +const NON_MEETING_EVENT_TYPES = new Set(['focusTime', 'outOfOffice', 'workingLocation', 'birthday']) + +/** + * Whether the connected member took part in a meeting: they organize it or accepted it, and + * another person (not a room) was invited. Declined and unanswered invitations are not attendance. + */ +function attendedMeeting(event: Record): boolean { + if (event.status === 'cancelled' || NON_MEETING_EVENT_TYPES.has(string(event.eventType))) + return false + const attendees = array(event.attendees) + if (!attendees.some((attendee) => attendee.self !== true && attendee.resource !== true)) + return false + const self = attendees.find((attendee) => attendee.self === true) + return ( + object(event.organizer).self === true || + (self !== undefined && ['accepted', 'tentative'].includes(string(self.responseStatus))) + ) +} + +/** + * Meetings on the member's primary calendar that started in the window, newest first. Slices + * of the window are read from its end backwards, each in full, until enough meetings are found; + * the start of the last slice read bounds what remains. A slice too full to read in the request + * budget yields nothing and reports partial coverage, since its newest meetings are the unread ones. + */ +export async function calendarActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + const start = Date.parse(input.start) + /** Calendar ignores milliseconds, so the inclusive end rounds up to the next whole second. */ + let sliceEnd = (Math.floor(Date.parse(input.end) / 1000) + 1) * 1000 + const includeAttendees = input.policy?.includeAttendees !== false + const events: NativeActivityEvent[] = [] + let requests = 0 + let overfull = false + while (sliceEnd > start && requests < CALENDAR_ACTIVITY_REQUESTS && events.length < input.limit) { + const sliceStart = Math.max(start, sliceEnd - CALENDAR_ACTIVITY_SLICE_MS) + const slice: Record[] = [] + let timeZone = '' + let pageToken: string | undefined + do { + const data = object( + await client.json('/calendar/v3/calendars/primary/events', { + query: { + timeMin: new Date(sliceStart).toISOString(), + timeMax: new Date(sliceEnd).toISOString(), + singleEvents: 'true', + orderBy: 'startTime', + maxResults: '250', + showDeleted: 'false', + ...(pageToken ? { pageToken } : {}), + }, + signal: input.signal, + }) + ) + requests++ + timeZone ||= string(data.timeZone) + slice.push(...array(data.items)) + pageToken = string(data.nextPageToken) || undefined + } while (pageToken && requests < CALENDAR_ACTIVITY_REQUESTS) + if (pageToken) { + overfull = true + break + } + for (const event of slice.filter(attendedMeeting)) { + const document = { + ...eventDocument(event, 'primary', includeAttendees, timeZone || undefined), + dedupeKey: calendarOccurrenceKey(event), + } + const startedAt = Date.parse(document.eventStartAt ?? '') + /** timeMin bounds an event's end, so a meeting already under way is left to its own slice. */ + if (!document.eventStartAt || startedAt < sliceStart || startedAt >= sliceEnd) continue + events.push({ + document, + at: new Date(startedAt).toISOString(), + action: 'attended', + collaborators: includeAttendees + ? collaboratorNames( + array(event.attendees) + .filter((attendee) => attendee.self !== true && attendee.resource !== true) + .map((attendee) => string(attendee.displayName) || string(attendee.email)) + ) + : [], + }) + } + sliceEnd = sliceStart + } + events.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)) + /** + * Whole slices can hold more meetings than a page needs: keep the newest `limit`, plus any + * sharing the last kept start, and resume below them. Meetings at the inclusive end may be ones + * an earlier page returned, so they never count toward the limit. + */ + const lastKept = events.filter((event) => Date.parse(event.at) < Date.parse(input.end))[ + input.limit - 1 + ] + const kept = lastKept + ? events.filter((event) => Date.parse(event.at) >= Date.parse(lastKept.at)) + : events + const trimmed = kept.length < events.length + const scannedTo = trimmed && lastKept ? lastKept.at : new Date(sliceEnd).toISOString() + const more = trimmed || sliceEnd > start + return { + streams: [ + { + events: kept, + more, + ...(more ? { scannedTo } : {}), + }, + ], + ...(overfull + ? { + partial: true, + message: + 'A week in this window holds more meetings than one call reads. Narrow the dates.', + } + : {}), + } +} + export async function readCalendar( client: NativeClient, id: string, diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 3012ae37103..efb52e33af5 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -1,10 +1,17 @@ import { MAX_NATIVE_QUERIES_PER_ACCOUNT } from '@/lib/api/contracts/mothership-assistant-tools' -import { previewConfluence, readAtlassian, searchAtlassian } from '@/lib/sim-search/live/atlassian' +import { + atlassianActivity, + previewConfluence, + readAtlassian, + searchAtlassian, +} from '@/lib/sim-search/live/atlassian' import { readCoda, searchCoda } from '@/lib/sim-search/live/coda' import { readFlow, searchFlow } from '@/lib/sim-search/live/flow' import { readGitHub, searchGitHub } from '@/lib/sim-search/live/github' import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' import { + calendarActivity, + gmailActivity, previewDrive, readCalendar, readDrive, @@ -21,8 +28,10 @@ import { LIVE_SEARCH_PROVIDER_IDS, type LiveSearchProviderId, } from '@/lib/sim-search/live/provider-catalog' -import { readSlack, searchSlack } from '@/lib/sim-search/live/slack' +import { readSlack, searchSlack, slackActivity } from '@/lib/sim-search/live/slack' import type { + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -62,6 +71,8 @@ interface NativeProvider { */ previewText?(client: NativeClient, document: NativeDocument): Promise search(client: NativeClient, input: NativeSearchInput, origin?: string): Promise + /** The connected person's own activity, newest first; providers without it report unsupported. */ + activity?(client: NativeClient, input: NativeActivityInput): Promise read( client: NativeClient, reference: Pick, @@ -127,6 +138,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'listing alternatives with spaces, which requires all of them, or lowercase or; join alternatives with uppercase OR. Search matches individual messages, and a result shows only the opening of its message, not a passage around the match: read it before concluding what the rest of the message says. Reading a match includes up to eight independently authorized messages from its conversation, with per-message dates and URLs. Context can fall outside the search dates or keywords; use the message timestamps and incomplete notices, and never claim the entire thread was searched.', }, search: searchGmail, + activity: gmailActivity, read: (client, reference, options) => readGmail(client, reference.id, options), }, google_meet: { @@ -166,6 +178,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'OR, quotes or field operators, which q does not support; run alternatives as separate native queries.', }, search: searchCalendar, + activity: calendarActivity, read: (client, reference, options) => readCalendar( client, @@ -188,6 +201,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'joining alternatives with OR or spaces in one query, which keyword retrieval treats as all required; send them as separate native queries.', }, search: searchSlack, + activity: slackActivity, read: (client, reference, options) => readSlack( client, @@ -211,6 +225,7 @@ export const LIVE_SEARCH_PROVIDERS = { }, requiresEveryTerm: true, search: (client, input) => searchAtlassian(client, 'jira', input), + activity: (client, input) => atlassianActivity(client, 'jira', input), read: (client, reference) => readAtlassian(client, 'jira', reference.id, reference.container), }, confluence: { @@ -228,6 +243,7 @@ export const LIVE_SEARCH_PROVIDERS = { requiresEveryTerm: true, previewText: previewConfluence, search: (client, input) => searchAtlassian(client, 'confluence', input), + activity: (client, input) => atlassianActivity(client, 'confluence', input), read: (client, reference) => readAtlassian(client, 'confluence', reference.id, reference.container, reference.kind), }, @@ -379,6 +395,23 @@ export function searchNativeProvider( return adapter.search(client, input, origin) } +/** True when the provider reports the connected person's own activity. */ +export function supportsActivity(provider: LiveSearchProviderId): boolean { + return 'activity' in LIVE_SEARCH_PROVIDERS[provider] +} + +/** Lists the connected person's own activity from a native provider that supports it. */ +export function activityNativeProvider( + provider: LiveSearchProviderId, + client: NativeClient, + input: NativeActivityInput +): Promise { + const adapter: NativeProvider | ManagedMcpProvider = LIVE_SEARCH_PROVIDERS[provider] + if (!('activity' in adapter) || !adapter.activity) + throw new NativeSearchError('unavailable', `${provider} does not report activity`) + return adapter.activity(client, input) +} + /** * True when the account can limit a search to the items this person (`me` or an email) took part * in: the provider supports the filter and, for an email, the account holds the scope finding diff --git a/apps/sim/lib/sim-search/live/slack.ts b/apps/sim/lib/sim-search/live/slack.ts index 53e2366153f..961ef4503ed 100644 --- a/apps/sim/lib/sim-search/live/slack.ts +++ b/apps/sim/lib/sim-search/live/slack.ts @@ -1,5 +1,6 @@ import { slackFileDownloadUrl } from '@/lib/internal/slack/file-download' import { recordSearchProviderSignal } from '@/lib/knowledge/search/diagnostics' +import { oldestInstant } from '@/lib/sim-search/live/activity-page' import { dateSortDirection, nativeDateBounds, nativeText } from '@/lib/sim-search/live/dates' import { documentExtension, @@ -22,6 +23,8 @@ import { } from '@/lib/sim-search/live/slack-format' import { providerText } from '@/lib/sim-search/live/text' import type { + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -247,12 +250,75 @@ async function slackPersonModifier( return `from:<@${id}>` } +/** + * Messages the connected member posted, newest first: one Real-time Search page of `from:me`, + * sorted by timestamp. A message inside a thread it did not start is a reply. File hits come from + * a separately ordered collection, so they are left out; a shared file also posts a message. + */ +export async function slackActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + if (!input.scopes.includes('search:read.public')) + throw new NativeSearchError( + 'reconnect', + 'Reconnect your Slack account to grant permission to search.' + ) + const page = await searchSlackPage( + client, + { + query: '', + filters: { + startDate: input.start, + /** Inclusive end: Real-time Search's exclusive whole-second bound covers only its second. */ + endDate: new Date(Date.parse(input.end) + 1).toISOString(), + sortBy: 'newest', + }, + policy: input.policy, + limit: SLACK_PAGE_SIZE, + /** File hits come from a separately ordered collection, so none are requested. */ + scopes: input.scopes.filter((scope) => scope !== 'search:read.files'), + signal: input.signal, + }, + undefined, + Math.min(input.limit, SLACK_PAGE_SIZE), + 'from:me', + false + ) + const messages = page.documents.filter((document) => document.kind !== 'file') + return { + streams: [ + { + events: messages.flatMap((document) => + document.modifiedAt + ? [ + { + document, + at: document.modifiedAt, + action: + document.threadId && document.threadId !== document.id + ? ('replied' as const) + : ('sent' as const), + collaborators: [], + }, + ] + : [] + ), + more: Boolean(page.nextCursor), + scannedTo: oldestInstant(messages.map((document) => document.modifiedAt)), + }, + ], + } +} + async function searchSlackPage( client: NativeClient, input: NativeSearchInput, cursor: string | undefined, limit: number, - person: string | undefined + person: string | undefined, + /** Surrounding messages in each result's text; activity wants only the member's own words. */ + context = true ): Promise { const channels = [ ['public_channel', 'search:read.public'], @@ -292,7 +358,7 @@ async function searchSlackPage( ...(input.scopes.includes('search:read.files') ? ['files'] : []), ...(listChannels ? ['channels'] : []), ], - include_context_messages: true, + include_context_messages: context, limit: Math.min(limit, SLACK_PAGE_SIZE), ...(dates.start ? { after: Math.floor(Date.parse(dates.start) / 1000) - 1 } : {}), ...(dates.end ? { before: Math.ceil(Date.parse(dates.end) / 1000) } : {}), diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index 6a5b382be3c..eb8b4408f9f 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -1,5 +1,6 @@ import type { WorkspaceSearchFilters } from '@/lib/api/contracts/knowledge' import type { + ActivityAction, LiveSearchProvider, NativeSearchQuery, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -128,3 +129,46 @@ export interface NativeSearchInput { */ signal?: AbortSignal } + +/** + * One account's activity request. `end` is inclusive so a continuation can resume at the instant + * an earlier page stopped; the caller drops entries it already returned at that instant. + */ +export interface NativeActivityInput { + start: string + end: string + /** Raw provider items one stream reads per call. */ + limit: number + scopes: readonly string[] + policy?: LiveSearchPolicy + signal?: AbortSignal +} + +/** One thing the connected person did, at the time of the provider order the stream reads in. */ +export interface NativeActivityEvent { + document: NativeDocument + /** The instant this entry sorts by: never earlier than its stream's `scannedTo` when more remain. */ + at: string + action: ActivityAction + collaborators: string[] + /** `at` is the item's last update, which may be someone else's, not the person's own action. */ + approximateTime?: true +} + +/** + * One provider listing read newest first. Every unread item of the stream sorts at or before + * `scannedTo`, so the events at or after it are complete for this stream. + */ +export interface NativeActivityStream { + events: NativeActivityEvent[] + /** Older items remain in the window; requires `scannedTo`. */ + more: boolean + /** The sort instant of the oldest item read, including items that produced no event. */ + scannedTo?: string +} + +export interface NativeActivityPage { + streams: NativeActivityStream[] + partial?: boolean + message?: string +}