diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index a39e2bc2ef3..b74cf5df281 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -11,11 +11,6 @@ import { } from '@/lib/api/contracts/mothership-assistant-tools' import { organizationIdSchema } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' -import { - PEOPLE_ID_MAX_LENGTH, - PEOPLE_SEARCH_MAX_LENGTH, - PEOPLE_SEARCH_MAX_TERMS, -} from '@/lib/people/validation' export const organizationKnowledgeMcpContract = defineRouteContract({ method: 'POST', @@ -58,9 +53,7 @@ export const liveSearchMcpSchema = searchWorkspaceInputFieldsSchema ...mcpDateFilterFields, involving: liveSearchInvolvingSchema .optional() - .describe( - 'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.' - ), + .describe(searchWorkspaceInputFieldsSchema.shape.involving.description ?? ''), topK: searchWorkspaceInputFieldsSchema.shape.topK .unwrap() .optional() @@ -138,35 +131,3 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema .describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'), }) .strict() - -export const searchPeopleMcpSchema = z - .object({ - query: z - .string() - .trim() - .min(1) - .max(PEOPLE_SEARCH_MAX_LENGTH) - .optional() - .describe( - `Up to ${PEOPLE_SEARCH_MAX_TERMS} words from a name, email, title, department, or location; a person matches when every word appears in one of them.` - ), - personId: z - .string() - .min(1) - .max(PEOPLE_ID_MAX_LENGTH) - .optional() - .describe( - 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.' - ), - cursor: z - .string() - .min(1) - .max(1024) - .optional() - .describe('nextCursor from the previous page of the same query.'), - }) - .strict() - .refine((input) => !input.personId || (input.query === undefined && !input.cursor), { - path: ['personId'], - message: 'Pass either personId or a query with its cursor, not both.', - }) diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index f2fa99efaaf..3c3e5b9d99b 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -235,6 +235,15 @@ export const searchWorkspaceInputFieldsSchema = workspaceSearchFiltersSchema.ext .describe( 'Search terms, without dates already supplied as filters. May be empty for a live listing with a date bound or sortBy newest or oldest where supported, or use an explicit native browse mode. Notion date-only search depends on plan capabilities.' ), + involving: z + .string() + .trim() + .min(1) + .max(254) + .optional() + .describe( + 'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.' + ), topK: z .number() .int() @@ -323,6 +332,42 @@ export const readDocumentInputSchema = z.object({ ), }) +/** + * 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. + */ +export const searchPeopleInputSchema = z + .object({ + query: z + .string() + .trim() + .min(1) + .max(200) + .optional() + .describe( + 'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.' + ), + personId: z + .string() + .min(1) + .max(255) + .optional() + .describe( + 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.' + ), + cursor: z + .string() + .min(1) + .max(1024) + .optional() + .describe('nextCursor from the previous page of the same query.'), + }) + .strict() + .refine((input) => !input.personId || (input.query === undefined && !input.cursor), { + path: ['personId'], + message: 'Pass either personId or a query with its cursor, not both.', + }) + /** Connection requests name a provider and optionally an owned account to repair. */ export const oauthGetAuthLinkInputSchema = z.object({ providerName: z @@ -386,6 +431,13 @@ export const assistantToolContracts = [ description: 'Read more context from an accessible connected-source document.', inputSchema: readDocumentInputSchema, }, + { + id: 'search_people', + route: 'sim', + description: + '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: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/knowledge/mcp/people.ts b/apps/sim/lib/knowledge/mcp/people.ts index 1610948e61e..960ca9cc117 100644 --- a/apps/sim/lib/knowledge/mcp/people.ts +++ b/apps/sim/lib/knowledge/mcp/people.ts @@ -1,81 +1,14 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import type { Principal } from '@sim/auth/principal' -import { createLogger } from '@sim/logger' -import { getErrorMessage } from '@sim/utils/errors' import type { NextRequest } from 'next/server' -import { - organizationKnowledgeMcpContract, - searchPeopleMcpSchema, -} from '@/lib/api/contracts/knowledge/mcp' -import type { PersonSummary } from '@/lib/api/contracts/people' -import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' -import { OrchestrationError } from '@/lib/core/orchestration/types' +import { searchPeopleInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' import { KNOWLEDGE_MCP_READ_ONLY, type KnowledgeMcpToolRunner, projectResult, } from '@/lib/knowledge/mcp/tool-runner' import { getPerson, listPeople } from '@/lib/people/application/use-cases' -import { isPeopleEnabled } from '@/lib/people/feature-flag' -import type { PersonRecord } from '@/lib/people/repository' -import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response' - -const logger = createLogger('KnowledgeMcpPeople') - -/** Said when a query matches no one, so a client looks for people outside the organization in search. */ -export const NO_PEOPLE_MATCH_NOTE = - 'No one in this organization’s directory matches. The directory lists only people in this organization; use search for anyone else, such as customer or vendor contacts.' - -/** - * Whether `principal` may look people up in `organizationId`: People is on there and the - * directory is open to them. Asked when listing tools, so a client whose organization has no - * People directory, or who may not browse it, is never offered the tool. A lookup that fails hides - * the tool rather than failing the listing around it. - */ -export async function canSearchPeople( - principal: Principal, - organizationId: string -): Promise { - try { - if (!(await isPeopleEnabled(organizationId))) return false - await listPeople.authorize({ principal, input: { organizationId } }) - return true - } catch (error) { - if (!(error instanceof OrchestrationError)) - logger.warn('Could not resolve Search MCP people access', { - organizationId, - error: getErrorMessage(error), - }) - return false - } -} - -function summaryFacts(person: PersonSummary) { - return { - personId: person.memberId, - name: person.name, - ...(person.title ? { title: person.title } : {}), - } -} - -function reportFacts(report: PersonSummary & { department: string | null; reportCount: number }) { - return { - ...summaryFacts(report), - ...(report.department ? { department: report.department } : {}), - directReports: report.reportCount, - } -} - -function personFacts(person: PersonRecord) { - const { department, location, startDate } = person - return { - ...summaryFacts(person), - email: person.email, - ...(department ? { department } : {}), - ...(location ? { location } : {}), - ...(startDate ? { startDate } : {}), - } -} +import { findDirectoryPeople, readDirectoryPerson } from '@/lib/people/directory-lookup' interface SearchPeopleToolContext { execute: KnowledgeMcpToolRunner @@ -93,70 +26,28 @@ export function registerSearchPeopleTool( server: McpServer, { execute, principal, organizationId, request }: SearchPeopleToolContext ) { - const detail = async (memberId: string) => { - const { person, chain, reports, totalReports } = await getPerson.execute({ - principal, - input: { organizationId, memberId }, - request, - }) - return { - person: { - ...personFacts(person), - ...(chain.length ? { managerChain: chain.map(summaryFacts) } : {}), - ...(reports.length ? { directReports: reports.map(reportFacts) } : {}), - totalDirectReports: totalReports, - ...(totalReports > reports.length - ? { - note: `directReports lists the first ${reports.length} of ${totalReports}; search by department or title to find the others.`, - } - : {}), - }, - } - } - server.registerTool( 'search_people', { title: 'Search people', description: '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 for customers, vendors, and other outside contacts.', - inputSchema: searchPeopleMcpSchema, + inputSchema: searchPeopleInputSchema, annotations: KNOWLEDGE_MCP_READ_ONLY, }, async (input: unknown, extra: { signal: AbortSignal }) => { - const personId = searchPeopleMcpSchema.safeParse(input).data?.personId + const personId = searchPeopleInputSchema.safeParse(input).data?.personId if (personId) return execute('search_people', getPerson.operation, extra.signal, async (registry) => - projectResult(await detail(personId), registry) + projectResult( + await readDirectoryPerson({ principal, organizationId, request, personId }), + registry + ) ) return execute('search_people', listPeople.operation, extra.signal, async (registry) => { - const { query, cursor } = searchPeopleMcpSchema.parse(input) - const scope = cursorScopeKey( - cursorRoute(organizationKnowledgeMcpContract, { organizationId }), - { tool: 'search_people', query } - ) - const page = await listPeople.execute({ - principal, - input: { - organizationId, - search: query, - cursorKeys: readSortedCursor(cursor, 'name', 'asc', scope), - }, - request, - }) - const [only] = page.data - if (only && page.data.length === 1 && !cursor) - return projectResult(await detail(only.memberId), registry) - const nextCursor = writeSortedCursor(page.nextCursorKeys, 'name', 'asc', scope) + const { query, cursor } = searchPeopleInputSchema.parse(input) return projectResult( - { - people: page.data.map((person) => ({ - ...personFacts(person), - ...(person.manager ? { manager: person.manager.name } : {}), - })), - ...(nextCursor ? { nextCursor } : {}), - ...(page.data.length ? {} : { note: NO_PEOPLE_MATCH_NOTE }), - }, + await findDirectoryPeople({ principal, organizationId, request, query, cursor }), registry ) }) diff --git a/apps/sim/lib/knowledge/mcp/route-handler.ts b/apps/sim/lib/knowledge/mcp/route-handler.ts index 8307f04f5b7..1f6b415829d 100644 --- a/apps/sim/lib/knowledge/mcp/route-handler.ts +++ b/apps/sim/lib/knowledge/mcp/route-handler.ts @@ -15,10 +15,10 @@ import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { knowledgeOperations } from '@/lib/knowledge/application/operations' import { readSearchIndex } from '@/lib/knowledge/application/sim-search' import { withSearchMcpAuthChallenge } from '@/lib/knowledge/mcp/oauth-metadata' -import { canSearchPeople } from '@/lib/knowledge/mcp/people' 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 { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response' const logger = createLogger('KnowledgeMcp') @@ -34,7 +34,7 @@ async function offersSearchPeople( ) { if (message.method === 'tools/call') return isRecordLike(message.params) && message.params.name === 'search_people' - return message.method === 'tools/list' && canSearchPeople(principal, organizationId) + return message.method === 'tools/list' && canLookUpPeople(principal, organizationId) } function mcpAuth(resource: string) { diff --git a/apps/sim/lib/knowledge/mcp/server.test.ts b/apps/sim/lib/knowledge/mcp/server.test.ts index 42c0e26c2ad..45ec7d82513 100644 --- a/apps/sim/lib/knowledge/mcp/server.test.ts +++ b/apps/sim/lib/knowledge/mcp/server.test.ts @@ -61,8 +61,8 @@ vi.mock('@/lib/knowledge/application/chat', () => ({ })) import { OrchestrationError } from '@/lib/core/orchestration/types' -import { NO_PEOPLE_MATCH_NOTE } from '@/lib/knowledge/mcp/people' import { createKnowledgeMcpServer } from '@/lib/knowledge/mcp/server' +import { NO_PEOPLE_MATCH_NOTE } from '@/lib/people/directory-lookup' import { LIVE_DATE_ORDER_MESSAGE, LIVE_MORE_RANKED_BELOW_MESSAGE, diff --git a/apps/sim/lib/knowledge/mcp/tool-arguments.ts b/apps/sim/lib/knowledge/mcp/tool-arguments.ts index 8c8a27362b0..8a7f50c62a1 100644 --- a/apps/sim/lib/knowledge/mcp/tool-arguments.ts +++ b/apps/sim/lib/knowledge/mcp/tool-arguments.ts @@ -4,10 +4,12 @@ import { chatSearchMcpSchema, liveSearchMcpSchema, readLiveDocumentMcpSchema, - searchPeopleMcpSchema, } from '@/lib/api/contracts/knowledge/mcp' import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp' -import { liveSearchProviderSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { + liveSearchProviderSchema, + searchPeopleInputSchema, +} from '@/lib/api/contracts/mothership-assistant-tools' /** Search filters a client sometimes writes on each native query instead of on the search. */ const SEARCH_FILTERS_ON_NATIVE_QUERIES = [ @@ -24,7 +26,7 @@ const TOOL_INPUT_SCHEMAS = new Map([ ['search', liveSearchMcpSchema], ['read_document', readLiveDocumentMcpSchema], ['chat', chatSearchMcpSchema], - ['search_people', searchPeopleMcpSchema], + ['search_people', searchPeopleInputSchema], ]) function readToolCall(message: Record) { diff --git a/apps/sim/lib/mothership/application/execute-people-use-case.ts b/apps/sim/lib/mothership/application/execute-people-use-case.ts new file mode 100644 index 00000000000..61f641f42e9 --- /dev/null +++ b/apps/sim/lib/mothership/application/execute-people-use-case.ts @@ -0,0 +1,42 @@ +import type { OrganizationDelegatedPrincipal } from '@sim/auth/principal' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { + COPILOT_APPLICATION_DELEGATION_TTL_MS, + type CopilotExecutionContext, + createTrustedOrganizationCopilotPrincipal, + requireTrustedOrganizationCopilotContext, +} from '@/lib/mothership/auth/application-delegation' +import { authorizeOrganizationChatDelegation } from '@/lib/mothership/chat/organization-chats' +import { peopleOperations } from '@/lib/people/application/operations' + +interface CopilotPeopleScope { + principal: OrganizationDelegatedPrincipal + organizationId: string +} + +/** + * Runs a People directory read for the organization Assistant, the only mode Sim grants the + * `people` entitlement in. The subject and organization come from the trusted turn, the + * delegation is bound to the member's private chat, and the People use cases the read calls + * still check the feature, the membership and the directory capability. + */ +export async function executeCopilotPeopleRead( + context: CopilotExecutionContext | undefined, + read: (scope: CopilotPeopleScope) => Promise +): Promise { + const trusted = requireTrustedOrganizationCopilotContext(context) + if (context?.requestMode !== 'assistant') + throw new OrchestrationError( + 'forbidden', + 'The People directory is available only in organization Assistant conversations' + ) + const principal = createTrustedOrganizationCopilotPrincipal( + { ...trusted, delegationId: trusted.toolCallId }, + { + audience: peopleOperations.list.delegationAudience, + ttlMs: COPILOT_APPLICATION_DELEGATION_TTL_MS, + } + ) + await authorizeOrganizationChatDelegation.execute({ principal }) + return read({ principal, organizationId: trusted.organizationId }) +} diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index b8babcc8cb0..e04059e1888 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -5,6 +5,7 @@ import type { ToolMetadata } from '@/tools/metadata' export const ASSISTANT_TOOLS = new Set([ 'search_workspace', 'read_document', + 'search_people', 'oauth_get_auth_link', 'run_function', ]) diff --git a/apps/sim/lib/mothership/chat/payload.ts b/apps/sim/lib/mothership/chat/payload.ts index 94b779de87c..74129cb458d 100644 --- a/apps/sim/lib/mothership/chat/payload.ts +++ b/apps/sim/lib/mothership/chat/payload.ts @@ -510,13 +510,12 @@ export async function buildCopilotRequestPayload(params: BuildPayloadParams): Pr !isAssistant && params.principal && params.workspaceId ? await buildWorkspaceInventory(params.principal, params.workspaceId) : undefined - const entitlements = isAssistant - ? [] - : await computeEntitlements({ - principal: params.principal, - workspaceId: params.workspaceId, - organizationId: params.organizationId, - }) + const entitlements = await computeEntitlements({ + principal: params.principal, + workspaceId: params.workspaceId, + organizationId: params.organizationId, + assistant: isAssistant, + }) return { entitlements, message, diff --git a/apps/sim/lib/mothership/entitlements.ts b/apps/sim/lib/mothership/entitlements.ts index d8693d9c13a..c97472d4749 100644 --- a/apps/sim/lib/mothership/entitlements.ts +++ b/apps/sim/lib/mothership/entitlements.ts @@ -4,6 +4,7 @@ import { isChangelogEnabled } from '@/lib/changelog/feature-flag' import { readDashboardAvailability } from '@/lib/dashboards/application/availability' import { isDashboardsEnabled } from '@/lib/dashboards/feature-flag' import { ENTITLEMENTS, type Entitlement } from '@/lib/mothership/generated/protocol' +import { canLookUpPeople } from '@/lib/people/directory-lookup' import { readWorkflowTestAvailability } from '@/lib/workflow-tests/application/availability' import { isWorkflowTestsEnabled } from '@/lib/workflow-tests/feature-flag' import { readWorkflowCodeAvailability } from '@/lib/workflows/application/code-availability' @@ -14,6 +15,8 @@ export interface EntitlementOwner { principal?: Principal workspaceId?: string organizationId?: string + /** An Assistant turn, granted only the entitlements with an `assistant` evaluator. */ + assistant?: boolean } interface WorkspaceOwner { @@ -30,11 +33,13 @@ interface OrganizationOwner { * Each entitlement declares the chat scopes it exists in; a scope it does not declare is never * granted. An organization chat in Build or Plan works in the organization's workspaces, so a * workspace capability exists there whenever the organization has it rolled out. The operation - * behind it still checks the workspace it runs against. + * behind it still checks the workspace it runs against. An Assistant turn in an organization + * chat is a scope of its own: only `assistant` evaluators are asked there. */ interface EntitlementEvaluator { workspace?: (owner: WorkspaceOwner) => Promise organization?: (owner: OrganizationOwner) => Promise + assistant?: (owner: OrganizationOwner) => Promise } /** @@ -77,13 +82,23 @@ const EVALUATORS: Record = { userId: principal ? resolvePrincipalSubjectUserId(principal) : undefined, }), }, + /** The organization Assistant's `search_people`; the People use cases re-check it. */ + [ENTITLEMENTS.people]: { + assistant: ({ principal, organizationId }) => + principal ? canLookUpPeople(principal, organizationId) : Promise.resolve(false), + }, } function evaluate(evaluator: EntitlementEvaluator, owner: EntitlementOwner): Promise { - const { principal, workspaceId, organizationId } = owner + const { principal, workspaceId, organizationId, assistant } = owner if (workspaceId && organizationId) { throw new Error('Entitlement owner must be a workspace or an organization, not both') } + if (assistant) { + return organizationId && evaluator.assistant + ? evaluator.assistant({ principal, organizationId }) + : Promise.resolve(false) + } if (organizationId) { return evaluator.organization?.({ principal, organizationId }) ?? Promise.resolve(false) } diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 4cd2319d58d..1ad8ffd3a88 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -148,6 +148,7 @@ export const ENTITLEMENTS = { tests: "tests", changelog: "changelog", workflowCode: "workflow-code", + people: "people", } 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 642e9401efe..9089689412d 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -258,6 +258,15 @@ export const searchWorkspaceInputFieldsSchema = workspaceSearchFiltersSchema.ext .describe( 'Search terms, without dates already supplied as filters. May be empty for a live listing with a date bound or sortBy newest or oldest where supported, or use an explicit native browse mode. Notion date-only search depends on plan capabilities.' ), + involving: z + .string() + .trim() + .min(1) + .max(254) + .optional() + .describe( + 'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.' + ), topK: z .number() .int() @@ -346,6 +355,42 @@ export const readDocumentInputSchema = z.object({ ), }) +/** + * 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. + */ +export const searchPeopleInputSchema = z + .object({ + query: z + .string() + .trim() + .min(1) + .max(200) + .optional() + .describe( + 'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.' + ), + personId: z + .string() + .min(1) + .max(255) + .optional() + .describe( + 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.' + ), + cursor: z + .string() + .min(1) + .max(1024) + .optional() + .describe('nextCursor from the previous page of the same query.'), + }) + .strict() + .refine((input) => !input.personId || (input.query === undefined && !input.cursor), { + path: ['personId'], + message: 'Pass either personId or a query with its cursor, not both.', + }) + /** Connection requests name a provider and optionally an owned account to repair. */ export const oauthGetAuthLinkInputSchema = z.object({ providerName: z @@ -409,6 +454,13 @@ export const assistantToolContracts = [ description: 'Read more context from an accessible connected-source document.', inputSchema: readDocumentInputSchema, }, + { + id: 'search_people', + route: 'sim', + description: + '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: '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 8112c016524..dc17ad3c564 100644 --- a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts @@ -11,6 +11,7 @@ export interface ToolCatalogEntry { | 'Discover and configure organization Search sources. list/get return accessible sources and indexing status; providers returns available integration approvals; approve changes a provider approval when authorized; setup returns the existing connection UI for the user to complete. Put the returned setupUrl in a clickable Markdown link at the end of the reply. Setup does not mean connected or indexed. Use search_workspace and read_document to retrieve source content.' | '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.' + | '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.' | 'Read and save the selected workspace’s single dashboard, validated YAML over live tables. Load the create-dashboard skill for the schema. get returns content and revision, or nulls when the workspace has no dashboard yet; set with no revision creates it. Replacing an existing dashboard requires expectedRevision from get, so a concurrent edit is never overwritten. Use open_resource with type dashboard to show the result.' @@ -133,6 +134,7 @@ export interface ToolCatalogEntry { | 'search_integration_tools' | 'search_knowledge_base' | 'search_library_docs' + | 'search_people' | 'search_sources' | 'search_workspace' | 'set_block_enabled' @@ -6164,6 +6166,13 @@ export const SearchWorkspace: ToolCatalogEntry = { type: 'string', maxLength: 2000, }, + involving: { + description: + 'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.', + type: 'string', + minLength: 1, + maxLength: 254, + }, topK: { default: 20, description: @@ -7749,6 +7758,40 @@ export const ListWorkspaces: ToolCatalogEntry = { }, } +export const SearchPeople: ToolCatalogEntry = { + id: 'search_people', + description: + '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.', + route: 'sim', + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + query: { + description: + 'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.', + type: 'string', + minLength: 1, + maxLength: 200, + }, + personId: { + description: + 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.', + type: 'string', + minLength: 1, + maxLength: 255, + }, + cursor: { + description: 'nextCursor from the previous page of the same query.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + }, + additionalProperties: false, + }, +} + export const Dashboards: ToolCatalogEntry = { id: 'dashboards', description: @@ -8758,6 +8801,7 @@ export const TOOL_CATALOG: Record = { [Workflow.id]: Workflow, [ListUserProjects.id]: ListUserProjects, [ListWorkspaces.id]: ListWorkspaces, + [SearchPeople.id]: SearchPeople, [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 7aa416530de..2c5250f21e4 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -6103,6 +6103,13 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { type: 'string', maxLength: 2000, }, + involving: { + description: + 'Only items this person acted on: "me" (you) or a colleague\'s email address, never a name. Each source applies its own meaning (sent, authored, owns, assigned, attended; your own mail means mail you sent) and skips sources that cannot filter by person. Use it for what someone did or is assigned, not for your exchanges with others, which it would cut to one side; with an empty query and a date range it lists that person\'s activity.', + type: 'string', + minLength: 1, + maxLength: 254, + }, topK: { default: 20, description: @@ -7835,6 +7842,36 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, + search_people: { + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + query: { + description: + 'Up to 8 words from a name, email, title, department, or location; a person matches when every word appears in one of them.', + type: 'string', + minLength: 1, + maxLength: 200, + }, + personId: { + description: + 'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.', + type: 'string', + minLength: 1, + maxLength: 255, + }, + cursor: { + description: 'nextCursor from the previous page of the same query.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + }, + additionalProperties: false, + }, + resultSchema: undefined, + }, dashboards: { parameters: { $schema: 'http://json-schema.org/draft-07/schema#', diff --git a/apps/sim/lib/mothership/resources/search-tool-result.ts b/apps/sim/lib/mothership/resources/search-tool-result.ts index 4737d2e24db..f417d756fde 100644 --- a/apps/sim/lib/mothership/resources/search-tool-result.ts +++ b/apps/sim/lib/mothership/resources/search-tool-result.ts @@ -33,8 +33,11 @@ export function searchResourceFromToolResult( topK, query: _query, nativeQueries, + involving, ...requestedFilters } = searchWorkspaceInputSchema.parse(params) + /** A Search tab cannot repeat a person filter, so refreshing it would drop the restriction. */ + if (involving) return undefined const nativeProjection = nativeQueries ? context.resolvedSecretTraceRegistry && projectResolvedSecretModelContent(nativeQueries, context.resolvedSecretTraceRegistry) diff --git a/apps/sim/lib/mothership/resources/search.test.ts b/apps/sim/lib/mothership/resources/search.test.ts index e5c94c5a176..a3c2d48b0e6 100644 --- a/apps/sim/lib/mothership/resources/search.test.ts +++ b/apps/sim/lib/mothership/resources/search.test.ts @@ -48,6 +48,11 @@ describe('Search resource addresses', () => { expect(mothershipResourceSchema.parse(resource)).toEqual(resource) expect(sanitizeChatResources([resource])).toEqual([resource]) }) + it('publishes no Search tab for a person-filtered search it could not repeat', () => { + expect( + searchResourceFromToolResult({ query: 'roadmap', involving: 'me' }, output, context) + ).toBeUndefined() + }) it('keeps date-only and native search addresses for an exact result-panel refresh', () => { const nativeQueries = [ { provider: 'github' as const, query: 'repo:simstudioai/sim deployment' }, diff --git a/apps/sim/lib/mothership/tool-executor/executor.ts b/apps/sim/lib/mothership/tool-executor/executor.ts index 12187c8fb75..2e40b193b48 100644 --- a/apps/sim/lib/mothership/tool-executor/executor.ts +++ b/apps/sim/lib/mothership/tool-executor/executor.ts @@ -84,7 +84,7 @@ export async function executeTool( return { success: false, error: 'Invalid organization execution scope' } const organizationTools = context.requestMode === 'assistant' - ? ['search_workspace', 'read_document', 'oauth_get_auth_link'] + ? [...ASSISTANT_TOOLS].filter((id) => id !== 'run_function') : [ 'list_workspaces', 'search_workspace', diff --git a/apps/sim/lib/mothership/tools/activity.ts b/apps/sim/lib/mothership/tools/activity.ts index 5ab3f7df40c..527d13ba3fb 100644 --- a/apps/sim/lib/mothership/tools/activity.ts +++ b/apps/sim/lib/mothership/tools/activity.ts @@ -410,6 +410,7 @@ export const TOOL_ACTIVITIES: Readonly = { search_workspace: 'Searching documents', list_workspaces: 'Listing workspaces', read_document: 'Reading document', + search_people: 'Looking up people', open_resource: 'Opening resource', ffmpeg: 'Processing media', diff --git a/apps/sim/lib/mothership/tools/server/knowledge/people.integration.ts b/apps/sim/lib/mothership/tools/server/knowledge/people.integration.ts new file mode 100644 index 00000000000..ecac9beec58 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/people.integration.ts @@ -0,0 +1,134 @@ +/** + * The organization Assistant's `search_people` against real Postgres: the copilot delegation the + * People reads now admit, bound to the member's own private chat and their current membership. + */ +import { db } from '@sim/db' +import { copilotChats, member, memberProfile, organization, 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 { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' + +vi.hoisted(() => vi.stubEnv('PEOPLE', 'true')) + +const org = generateId() +const readerId = generateId() +const leadId = generateId() +const outsiderId = generateId() +const readerMember = generateId() +const leadMember = generateId() +const readerChat = generateId() +const leadChat = generateId() + +function turn(userId: string, chatId: string) { + return { + userId, + organizationId: org, + chatId, + toolCallId: generateId(), + copilotToolExecution: true, + requestMode: 'assistant', + } +} + +beforeAll(async () => { + await db.insert(organization).values({ + id: org, + slug: org, + name: 'Assistant people fixture', + createdAt: new Date(), + }) + await db.insert(user).values( + [ + [readerId, 'Reader Account'], + [leadId, 'Grace Lead'], + [outsiderId, 'Former Member'], + ].map(([id, name]) => ({ + id, + name, + email: `${id}@example.test`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + })) + ) + await db.insert(member).values([ + { id: readerMember, organizationId: org, userId: readerId, role: 'member' }, + { id: leadMember, organizationId: org, userId: leadId, role: 'member' }, + ]) + await db.insert(memberProfile).values([ + { memberId: leadMember, title: 'Director', department: 'Design' }, + { memberId: readerMember, title: 'Designer', managerMemberId: leadMember }, + ]) + await db.insert(copilotChats).values([ + { id: readerChat, userId: readerId, organizationId: org, type: 'mothership' }, + { id: leadChat, userId: leadId, organizationId: org, type: 'mothership' }, + { id: generateId(), userId: outsiderId, organizationId: org, type: 'mothership' }, + ]) +}) + +afterAll(async () => { + await db.delete(organization).where(eq(organization.id, org)) + await db.delete(user).where(inArray(user.id, [readerId, leadId, outsiderId])) + vi.unstubAllEnvs() +}) + +it('answers a member in their own chat with the matching person and reporting line', async () => { + const result = await searchPeopleServerTool.execute( + { query: 'designer' }, + turn(readerId, readerChat) + ) + expect(result).toMatchObject({ + success: true, + data: { + person: { + personId: readerMember, + name: 'Reader Account', + title: 'Designer', + managerChain: [{ personId: leadMember, name: 'Grace Lead', title: 'Director' }], + }, + }, + }) + expect( + await searchPeopleServerTool.execute({ personId: leadMember }, turn(readerId, readerChat)) + ).toMatchObject({ + success: true, + data: { person: { personId: leadMember, directReports: [{ personId: readerMember }] } }, + }) +}) + +it('refuses a delegation naming another member’s chat', async () => { + const result = await searchPeopleServerTool.execute({ query: 'grace' }, turn(readerId, leadChat)) + expect(result).toEqual({ success: false, message: 'Conversation not found' }) +}) + +it('refuses a chat owner who is no longer a member of the organization', async () => { + const [chat] = await db + .select({ id: copilotChats.id }) + .from(copilotChats) + .where(eq(copilotChats.userId, outsiderId)) + const result = await searchPeopleServerTool.execute( + { query: 'grace' }, + turn(outsiderId, chat?.id ?? '') + ) + expect(result).toMatchObject({ success: false }) + expect(JSON.stringify(result)).not.toContain('Grace Lead') +}) + +it('offers the directory only in organization Assistant conversations', async () => { + expect( + await searchPeopleServerTool.execute( + { query: 'grace' }, + { ...turn(readerId, readerChat), organizationId: undefined, workspaceId: generateId() } + ) + ).toMatchObject({ success: false }) + expect( + await searchPeopleServerTool.execute( + { query: 'grace' }, + { ...turn(readerId, readerChat), requestMode: 'agent' } + ) + ).toEqual({ + success: false, + message: 'The People directory is available only in organization Assistant conversations', + }) +}) diff --git a/apps/sim/lib/mothership/tools/server/knowledge/people.ts b/apps/sim/lib/mothership/tools/server/knowledge/people.ts new file mode 100644 index 00000000000..8d6431f5a34 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/people.ts @@ -0,0 +1,46 @@ +import { createLogger } from '@sim/logger' +import { z } from 'zod' +import { searchPeopleInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { getValidationErrorMessage } from '@/lib/api/server/validation' +import { messageForCopilotApplicationError } from '@/lib/mothership/application/errors' +import { executeCopilotPeopleRead } from '@/lib/mothership/application/execute-people-use-case' +import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' +import { findDirectoryPeople, readDirectoryPerson } from '@/lib/people/directory-lookup' + +const logger = createLogger('SearchPeopleTool') + +/** + * `search_people` for the organization Assistant: the same directory lookup, use cases and + * result shape as the Search MCP tool of that name. + */ +export const searchPeopleServerTool: BaseServerTool = { + name: 'search_people', + inputSchema: searchPeopleInputSchema, + async execute(raw, context?: ServerToolContext) { + if (!context?.organizationId) + return { + success: false, + message: 'The People directory is available only in organization conversations.', + } + try { + const { query, personId, cursor } = searchPeopleInputSchema.parse(raw) + const data = await executeCopilotPeopleRead(context, (scope) => + personId + ? readDirectoryPerson({ ...scope, personId }) + : findDirectoryPeople({ ...scope, query, cursor }) + ) + return { success: true, data } + } catch (error) { + if (error instanceof z.ZodError) + return { + success: false, + message: getValidationErrorMessage(error, 'Invalid people lookup arguments'), + } + logger.error('People lookup failed', { error }) + return { + success: false, + message: messageForCopilotApplicationError(error, 'People lookup failed'), + } + } + }, +} diff --git a/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.test.ts b/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.test.ts index ae675215799..95bfdb8466c 100644 --- a/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.test.ts +++ b/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.test.ts @@ -230,6 +230,28 @@ describe('Assistant retrieval tools', () => { }) ) }) + it('searches for the person the model names in involving', async () => { + await searchWorkspaceServerTool.execute( + { query: '', involving: 'me', sortBy: 'newest' }, + context + ) + expect(mocks.search).toHaveBeenCalledWith( + expect.objectContaining({ input: expect.objectContaining({ involving: 'me' }) }) + ) + }) + it('reads a pasted source link under the selected scope, before it resolves to a document ID', async () => { + const link = 'https://acme.slack.com/archives/C123/p1700000000000100' + const result = await readDocumentServerTool.execute( + { documentId: link }, + { ...context, assistantSearch: { source: 'slack' } } + ) + expect(result).toMatchObject({ success: true }) + expect(mocks.read).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ documentId: link, filters: { source: 'slack' } }), + }) + ) + }) it('returns only the projected query to the model', async () => { const secret = 'private-resolved-query-token' const registry = new ResolvedSecretTraceRegistry([ diff --git a/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.ts b/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.ts index 4da4825ad9d..a5bca64bc8d 100644 --- a/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.ts +++ b/apps/sim/lib/mothership/tools/server/knowledge/workspace-search.ts @@ -19,6 +19,7 @@ import { import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' import { connectorDisplayName } from '@/lib/sim-search/connectors' import { readLiveDocument, searchLiveKnowledge } from '@/lib/sim-search/live/application' +import { parseDocumentLinks } from '@/lib/sim-search/live/links' import { LiveReadError } from '@/lib/sim-search/live/read-error' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' @@ -42,7 +43,7 @@ export const searchWorkspaceServerTool: BaseServerTool = { async () => { try { const scope = requireCopilotKnowledgeScope(context) - const { query, topK, nativeQueries, ...requestedFilters } = + const { query, topK, nativeQueries, involving, ...requestedFilters } = searchWorkspaceInputSchema.parse(raw) const registry = context?.resolvedSecretTraceRegistry if (!registry) throw new Error('Knowledge result provenance is unavailable') @@ -71,6 +72,7 @@ export const searchWorkspaceServerTool: BaseServerTool = { } const liveInput = { ...input, + involving, nativeQueries: searchWorkspaceInputSchema.shape.nativeQueries.parse( nativeQueries ? nativeProjection.value : undefined ), @@ -140,10 +142,11 @@ export const readDocumentServerTool: BaseServerTool = { const input = readDocumentInputSchema.parse(raw) const registry = context?.resolvedSecretTraceRegistry if (!registry) throw new Error('Knowledge result provenance is unavailable') + /** A pasted link names no document ID until it resolves, so only the selected scope filters it. */ const liveInput = { ...input, filters: intersectWorkspaceSearchFilters( - { documentIds: [input.documentId] }, + parseDocumentLinks(input.documentId) ? {} : { documentIds: [input.documentId] }, context?.assistantSearch ), resultSecretRegistry: registry, diff --git a/apps/sim/lib/mothership/tools/server/router.ts b/apps/sim/lib/mothership/tools/server/router.ts index 59928a04dde..dadf6835809 100644 --- a/apps/sim/lib/mothership/tools/server/router.ts +++ b/apps/sim/lib/mothership/tools/server/router.ts @@ -25,6 +25,7 @@ import { editContentServerTool } from '@/lib/mothership/tools/server/files/edit- import { workspaceFileServerTool } from '@/lib/mothership/tools/server/files/workspace-file' import { validateGeneratedToolPayload } from '@/lib/mothership/tools/server/generated-schema' import { generateImageServerTool } from '@/lib/mothership/tools/server/image/generate-image' +import { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' import { readDocumentServerTool, searchWorkspaceServerTool, @@ -79,6 +80,7 @@ const baseServerToolRegistry: Record = { [settingsServerTool.name]: settingsServerTool, [openResourceServerTool.name]: openResourceServerTool, [readDocumentServerTool.name]: readDocumentServerTool, + [searchPeopleServerTool.name]: searchPeopleServerTool, // 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/people/application/operations.ts b/apps/sim/lib/people/application/operations.ts index 7b52c65ef45..179ebbabadf 100644 --- a/apps/sim/lib/people/application/operations.ts +++ b/apps/sim/lib/people/application/operations.ts @@ -1,10 +1,16 @@ import { defineOrganizationOperation } from '@/lib/core/application/organization-operation' const session = { principalKinds: ['session'] } as const -/** The People page, and Search MCP clients finding a person, under the scope that admits Search. */ +/** + * The People page, Search MCP clients finding a person under the scope that admits Search, and + * the organization Assistant under its Search delegation, bound to the member's private chat. + */ const directoryReaders = { - principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'organization_delegated'], oauthScope: 'search:read', + delegationAudience: 'sim:knowledge', + delegatedServices: ['copilot'], + contentDelivery: 'none', } as const /** diff --git a/apps/sim/lib/people/directory-lookup.ts b/apps/sim/lib/people/directory-lookup.ts new file mode 100644 index 00000000000..220dbf473a8 --- /dev/null +++ b/apps/sim/lib/people/directory-lookup.ts @@ -0,0 +1,142 @@ +import type { Principal } from '@sim/auth/principal' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { listPeopleContract, type PersonSummary } from '@/lib/api/contracts/people' +import { cursorRoute, cursorScopeKey } from '@/lib/api/cursor-binding' +import { + OrchestrationError, + type OrchestrationRequestContext, +} from '@/lib/core/orchestration/types' +import { getPerson, listPeople } from '@/lib/people/application/use-cases' +import { isPeopleEnabled } from '@/lib/people/feature-flag' +import type { PersonRecord } from '@/lib/people/repository' +import { readSortedCursor, writeSortedCursor } from '@/app/api/v2/lib/response' + +/** Said when a query matches no one, so a caller looks for people outside the organization in search. */ +export const NO_PEOPLE_MATCH_NOTE = + 'No one in this organization’s directory matches. The directory lists only people in this organization; search connected sources for anyone else, such as customer or vendor contacts.' + +const logger = createLogger('PeopleDirectoryLookup') + +/** + * Whether `principal` may look people up in `organizationId`: People is on there and the + * directory is open to them. Asked before offering a lookup tool, so a caller whose organization + * has no People directory, or who may not browse it, is never offered one. A check that fails + * hides the tool rather than failing the listing or turn around it. + */ +export async function canLookUpPeople( + principal: Principal, + organizationId: string +): Promise { + try { + if (!(await isPeopleEnabled(organizationId))) return false + await listPeople.authorize({ principal, input: { organizationId } }) + return true + } catch (error) { + if (!(error instanceof OrchestrationError)) + logger.warn('Could not resolve People directory access', { + organizationId, + error: getErrorMessage(error), + }) + return false + } +} + +interface DirectoryLookupInput { + principal: Principal + organizationId: string + request?: OrchestrationRequestContext +} + +function summaryFacts(person: PersonSummary) { + return { + personId: person.memberId, + name: person.name, + ...(person.title ? { title: person.title } : {}), + } +} + +function reportFacts(report: PersonSummary & { department: string | null; reportCount: number }) { + return { + ...summaryFacts(report), + ...(report.department ? { department: report.department } : {}), + directReports: report.reportCount, + } +} + +function personFacts(person: PersonRecord) { + const { department, location, startDate } = person + return { + ...summaryFacts(person), + email: person.email, + ...(department ? { department } : {}), + ...(location ? { location } : {}), + ...(startDate ? { startDate } : {}), + } +} + +/** One person with their reporting line: managers above them, direct manager first, and reports. */ +export async function readDirectoryPerson({ + principal, + organizationId, + request, + personId, +}: DirectoryLookupInput & { personId: string }) { + const { person, chain, reports, totalReports } = await getPerson.execute({ + principal, + input: { organizationId, memberId: personId }, + request, + }) + return { + person: { + ...personFacts(person), + ...(chain.length ? { managerChain: chain.map(summaryFacts) } : {}), + ...(reports.length ? { directReports: reports.map(reportFacts) } : {}), + totalDirectReports: totalReports, + ...(totalReports > reports.length + ? { + note: `directReports lists the first ${reports.length} of ${totalReports}; search by department or title to find the others.`, + } + : {}), + }, + } +} + +/** + * Finds people in the organization's directory through the People page's use cases. A first page + * holding exactly one person answers with that person's reporting line, so "who is X's manager" or + * "who reports to X" takes one call. The cursor resumes only the organization and query it was + * minted for. + */ +export async function findDirectoryPeople({ + principal, + organizationId, + request, + query, + cursor, +}: DirectoryLookupInput & { query?: string; cursor?: string }) { + const scope = cursorScopeKey(cursorRoute(listPeopleContract, { id: organizationId }), { + search: query, + }) + const page = await listPeople.execute({ + principal, + input: { + organizationId, + search: query, + cursorKeys: readSortedCursor(cursor, 'name', 'asc', scope), + }, + request, + }) + const [only] = page.data + if (only && page.data.length === 1 && !cursor) + return readDirectoryPerson({ principal, organizationId, request, personId: only.memberId }) + const nextCursor = writeSortedCursor(page.nextCursorKeys, 'name', 'asc', scope) + return { + people: page.data.map((person) => ({ + ...personFacts(person), + ...(person.manager ? { manager: person.manager.name } : {}), + })), + ...(nextCursor ? { nextCursor } : {}), + ...(page.data.length ? {} : { note: NO_PEOPLE_MATCH_NOTE }), + } +}