Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion apps/sim/app/api/cron/people-directory-sync/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { sweepPeopleDirectoriesContract } from '@/lib/api/contracts/people-sync-
import { parseRequest } from '@/lib/api/server'
import { verifyCronAuth } from '@/lib/auth/internal'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { refreshDueSlackIdentities } from '@/lib/people/slack-identities'
import { syncDueDirectories } from '@/lib/people/sync/runner'

export const maxDuration = 300
Expand All @@ -12,5 +13,14 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
if (authError) return authError
const parsed = await parseRequest(sweepPeopleDirectoriesContract, request, {})
if (!parsed.success) return parsed.response
return NextResponse.json(await syncDueDirectories())
const [directories, slack] = await Promise.allSettled([
syncDueDirectories(),
refreshDueSlackIdentities(),
])
if (directories.status === 'rejected') throw directories.reason
if (slack.status === 'rejected') throw slack.reason
return NextResponse.json({
...directories.value,
slackIdentitiesRefreshed: slack.value.refreshed,
})
})
54 changes: 54 additions & 0 deletions apps/sim/blocks/blocks/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,54 @@ export const OrganizationBlock: BlockConfig = {
condition: { field: 'operation', value: 'read_document' },
mode: 'advanced',
},
{
id: 'name',
title: 'Name',
type: 'short-input',
placeholder: 'Part of a name',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'email',
title: 'Email',
type: 'short-input',
placeholder: 'An exact email address',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'title',
title: 'Title',
type: 'short-input',
placeholder: 'Part of a job title',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'department',
title: 'Department',
type: 'short-input',
placeholder: 'Part of a department',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'location',
title: 'Location',
type: 'short-input',
placeholder: 'Part of a location',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'managerPersonId',
title: 'Manager Person ID',
type: 'short-input',
placeholder: 'A personId, to list their direct reports',
condition: { field: 'operation', value: 'search_people' },
mode: 'advanced',
},
{
id: 'personId',
title: 'Person ID',
Expand Down Expand Up @@ -296,6 +344,12 @@ export const OrganizationBlock: BlockConfig = {
documentIds: { type: 'string', description: 'Documents to read together' },
startChunkIndex: { type: 'number', description: 'Chunk to continue reading from' },
startOffset: { type: 'number', description: 'Where to continue reading' },
name: { type: 'string', description: 'Search People: part of a name' },
email: { type: 'string', description: 'Search People: an exact email address' },
title: { type: 'string', description: 'Search People: part of a job title' },
department: { type: 'string', description: 'Search People: part of a department' },
location: { type: 'string', description: 'Search People: part of a location' },
managerPersonId: { type: 'string', description: 'Search People: list this person’s reports' },
personId: { type: 'string', description: 'Person to show with their reporting line' },
cursor: { type: 'string', description: 'Next page of a people search or activity listing' },
historyCursor: { type: 'string', description: 'Chat history: next page of the same window' },
Expand Down
18 changes: 12 additions & 6 deletions apps/sim/ee/scim/lib/repository/people-profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ import { isScimEntitledForOrganization } from '@/ee/scim/lib/entitlement'
/** One character beyond a valid SCIM resource ID keeps oversized PATCH values unresolved. */
const UNRESOLVED_MANAGER_LENGTH = 257

/** A string core attribute SCIM keeps in `extra`, matched by name ignoring case, trimmed and cut to `max`. */
function extraAttribute(name: string, max: number) {
return sql<string | null>`(select nullif(left(trim(entry.value #>> '{}'),${max}),'')
from jsonb_each(${scimUser.attributes}->'extra') entry
where lower(entry.key)=${name} and jsonb_typeof(entry.value)='string' order by entry.key limit 1)`
}

function projectedPeople(
tx: DbTransaction,
organizationId: string,
Expand All @@ -38,9 +45,8 @@ function projectedPeople(
from jsonb_array_elements(case when jsonb_typeof(${scimUser.attributes} #> '{extra,addresses}')='array'
then ${scimUser.attributes} #> '{extra,addresses}' else '[]'::jsonb end) with ordinality as a(address,idx)
where lower(address->>'type')='work' order by case when address->>'primary'='true' then 0 else 1 end, idx limit 1)`,
title: sql<string | null>`(select left(trim(entry.value #>> '{}'),${max})
from jsonb_each(${scimUser.attributes}->'extra') entry
where lower(entry.key)='title' and jsonb_typeof(entry.value)='string' order by entry.key limit 1)`,
title: extraAttribute('title', max),
timezone: memberOnly ? sql<null>`null` : extraAttribute('timezone', 64),
department: sql<
string | null
>`left(trim(${scimUser.attributes} #>> '{enterprise,department}'),${memberOnly ? max : DIRECTORY_TEXT_MAX_LENGTH + 1})`,
Expand Down Expand Up @@ -139,11 +145,11 @@ export async function stageScimDirectory(
oversized: boolean
total: string
}>(sql`
WITH source(external_id,email,name,location,title,department,manager_external_id) AS (${source}),
WITH source(external_id,email,name,location,title,timezone,department,manager_external_id) AS (${source}),
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
staged AS (
INSERT INTO ${peopleDirectoryStage} (organization_id,run_id,external_id,proposed_id,email,name,title,department,location,manager_external_id,reports_complete)
INSERT INTO ${peopleDirectoryStage} (organization_id,run_id,external_id,proposed_id,email,name,title,department,location,timezone,manager_external_id,reports_complete)
SELECT ${organizationId},${runId},external_id,gen_random_uuid()::text,email,
coalesce(nullif(btrim(name),''),email),nullif(title,''),nullif(department,''),nullif(location,''),nullif(manager_external_id,''),true
coalesce(nullif(btrim(name),''),email),nullif(title,''),nullif(department,''),nullif(location,''),timezone,nullif(manager_external_id,''),true
FROM source WHERE char_length(external_id) BETWEEN 1 AND 512 AND char_length(email) <= 320 AND email ~ ${z.regexes.email.source}
ON CONFLICT DO NOTHING RETURNING 1
), counts AS (SELECT (SELECT count(*) FROM source) AS expected,(SELECT count(*) FROM staged) AS actual)
Expand Down
37 changes: 31 additions & 6 deletions apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,10 @@ export type ListMyActivityResult = z.output<typeof listMyActivityResultSchema>
* 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.
*/
function peopleFieldFilter(description: string) {
return z.string().trim().min(1).max(200).optional().describe(description)
}

export const searchPeopleInputSchema = z
.object({
query: z
Expand All @@ -489,18 +493,39 @@ export const searchPeopleInputSchema = z
.describe(
'A personId from an earlier result, to show that person with their managers and direct reports. Used instead of query.'
),
name: peopleFieldFilter('Only people whose name contains this text.'),
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
email: z
.string()
.trim()
.min(3)
.max(320)
.optional()
.describe('Only the person with this exact email address.'),
title: peopleFieldFilter('Only people whose title contains this text.'),
department: peopleFieldFilter('Only people whose department contains this text.'),
location: peopleFieldFilter('Only people whose location contains this text.'),
managerPersonId: z
.string()
.min(1)
.max(255)
.optional()
.describe('Only the direct reports of this personId.'),
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
cursor: z
.string()
.min(1)
.max(1024)
.optional()
.describe('nextCursor from the previous page of the same query.'),
.describe('nextCursor from the previous page of the same query and filters.'),
})
.strict()
.refine((input) => !input.personId || (input.query === undefined && !input.cursor), {
path: ['personId'],
message: 'Pass either personId or a query with its cursor, not both.',
})
.refine(
({ personId, ...listing }) =>
!personId || Object.values(listing).every((value) => value === undefined),
{
path: ['personId'],
message: 'Pass either personId or a query with its filters and cursor, not both.',
}
)

/**
* The caller's own questions to Sim over a window, oldest first. The 92-day window and the page
Expand Down Expand Up @@ -611,7 +636,7 @@ export const assistantToolContracts = [
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.',
'Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. 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,
},
{
Expand Down
8 changes: 7 additions & 1 deletion apps/sim/lib/api/contracts/people-sync-cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,11 @@ import { defineRouteContract } from '@/lib/api/contracts'
export const sweepPeopleDirectoriesContract = defineRouteContract({
method: 'GET',
path: '/api/cron/people-directory-sync',
response: { mode: 'json', schema: z.object({ attempted: z.number().int().nonnegative() }) },
response: {
mode: 'json',
schema: z.object({
attempted: z.number().int().nonnegative(),
slackIdentitiesRefreshed: z.number().int().nonnegative(),
}),
},
})
8 changes: 8 additions & 0 deletions apps/sim/lib/api/contracts/people.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ const personSchema = personSummarySchema.extend({
location: z.string().nullable(),
/** `YYYY-MM-DD`. */
startDate: z.string().nullable(),
/** IANA time zone, from the directory source or the person's Slack profile. */
timezone: z.string().nullable(),
/** The person's user ID in one of the organization's Slack Search workspaces. */
slackUserId: z.string().nullable(),
/** The Slack workspace {@link slackUserId} belongs to. */
slackTeamId: z.string().nullable(),
/** People who report to this person; listed people only. */
reportCount: z.number().int().optional(),
/** The manager as shown; `null` when there is none or they are suspended. */
manager: personSummarySchema.nullable(),
/** The stored manager link, kept while that manager is suspended. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,15 @@ describe('Organization Search tools in a workflow run', () => {
expect(body.sources.map((source: { source: string }) => source.source)).toEqual(['slack'])
})

it('applies the People field filters a workflow passes', async () => {
const response = await call(
runAs(memberUserId, organizationWorkflowId, organizationWorkspaceId),
{ email: `${colleagueUserId}@organization-search.test` }
)
expect(response.status).toBe(200)
expect((await response.json()).person).toMatchObject({ name: colleagueName })
})

it('refuses a run in an organization without Search', async () => {
searchAvailable.value = false
try {
Expand Down
18 changes: 15 additions & 3 deletions apps/sim/lib/internal/organization-search/search-people.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,27 @@ import { findDirectoryPeople, readDirectoryPerson } from '@/lib/people/directory
export const searchOrganizationPeople: OrganizationSearchToolHandler = async (call) => {
const parsed = parseInternalOperationInput({ body: searchPeopleInputSchema }, call.input)
if (!parsed.success) return parsed.response
const { query, personId, cursor } = parsed.data.body
const { personId, ...listing } = parsed.data.body
const scope = {
principal: call.principal,
organizationId: call.principal.organizationId,
request: { headers: call.operation.headers },
}
return respondWithResultProvenance(call, query, async () =>
const { query, name, email, title, department, location, managerPersonId } = listing
/** Every argument a run's secret could fill is projected out of what the directory returns. */
const modelInput = [
query,
name,
email,
title,
department,
location,
managerPersonId,
personId,
].filter(Boolean)
return respondWithResultProvenance(call, modelInput, async () =>
personId
? readDirectoryPerson({ ...scope, personId })
: findDirectoryPeople({ ...scope, query, cursor })
: findDirectoryPeople({ ...scope, ...listing })
)
}
5 changes: 5 additions & 0 deletions apps/sim/lib/internal/slack/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isRecordLike } from '@sim/utils/object'
import { parseRetryAfter } from '@sim/utils/retry'
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
import { isPayloadSizeLimitError, readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'

Expand All @@ -11,6 +12,8 @@ export interface SlackApiResult {
status: number
statusText: string
grantedScopes?: string[]
/** Milliseconds Slack asked the caller to wait, from a rate-limited response's `Retry-After`. */
retryAfterMs?: number
}

export interface SlackApiRequest {
Expand Down Expand Up @@ -103,10 +106,12 @@ export async function requestSlackApi({
signal?.throwIfAborted()
if (!isRecordLike(parsed)) throw new Error('Slack API returned an invalid response')
const scopeHeader = response.headers.get('x-oauth-scopes')
const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'))
return {
data: parsed,
status: response.status,
statusText: response.statusText,
...(retryAfterMs === null ? {} : { retryAfterMs }),
...(scopeHeader !== null
? {
grantedScopes: scopeHeader
Expand Down
62 changes: 62 additions & 0 deletions apps/sim/lib/internal/slack/search-client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { isRecordLike } from '@sim/utils/object'
import { normalizeEmail } from '@sim/utils/string'
import {
requestSlackApi,
type SlackApiResult,
slackArray,
slackObject,
slackString,
} from '@/lib/internal/slack/client'
Expand Down Expand Up @@ -104,3 +106,63 @@ export async function getSlackSearchSender(
}
return { email: normalizeEmail(email) }
}

/** One human member of the bot's workspace, as Slack's member list reports them. */
export interface SlackSearchMember {
userId: string
email: string
timezone: string | null
}

/**
* One page of the active human members of the bot's own workspace, by email; bots, apps,
* deactivated accounts, guests from other workspaces and members without an email are skipped.
* `rateLimited` is a page Slack refused for its rate limit, to be retried after the pause it asked for.
*/
export async function listSlackSearchMembers(
accessToken: string,
teamId: string,
cursor: string | null,
signal?: AbortSignal
): Promise<
| { rateLimited: true; retryAfterMs: number | null }
| { rateLimited: false; members: SlackSearchMember[]; next: string | null }
> {
const result = await requestSlackApi({
accessToken,
method: 'users.list',
httpMethod: 'GET',
query: { limit: 200, ...(cursor ? { cursor } : {}) },
signal,
tolerateInvalidErrorJson: true,
})
if (result.status === 429 || result.data.error === 'ratelimited')
return { rateLimited: true, retryAfterMs: result.retryAfterMs ?? null }
const data = requireSuccess(result)
const page = slackArray(data, 'members')
/** A page without a member list is not an empty workspace; refusing it keeps the last list. */
if (!page) throw new SlackSearchProviderError()
const members: SlackSearchMember[] = []
for (const entry of page) {
if (!isRecordLike(entry)) continue
const profile = slackObject(entry, 'profile')
const email = profile && slackString(profile, 'email')
const userId = slackString(entry, 'id')
if (
!userId ||
!email?.trim() ||
entry.team_id !== teamId ||
entry.deleted !== false ||
entry.is_bot !== false ||
entry.is_app_user === true
)
continue
members.push({
userId,
email: normalizeEmail(email),
timezone: slackString(entry, 'tz') ?? null,
})
}
const next = slackString(slackObject(data, 'response_metadata') ?? {}, 'next_cursor')
return { rateLimited: false, members, next: next?.trim() ? next : null }
}
6 changes: 3 additions & 3 deletions apps/sim/lib/knowledge/mcp/people.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function registerSearchPeopleTool(
{
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.',
'Look up people in this organization’s directory by name, email, title, department, or location, with query across all of them or a filter per field; managerPersonId lists someone’s direct reports. Returns each person’s title, department, location, email, start date, time zone, Slack user ID, manager, and direct report count. 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: searchPeopleInputSchema,
annotations: KNOWLEDGE_MCP_READ_ONLY,
},
Expand All @@ -45,9 +45,9 @@ export function registerSearchPeopleTool(
)
)
return execute('search_people', listPeople.operation, extra.signal, async (registry) => {
const { query, cursor } = searchPeopleInputSchema.parse(input)
const { personId: _personId, ...filters } = searchPeopleInputSchema.parse(input)
return projectResult(
await findDirectoryPeople({ principal, organizationId, request, query, cursor }),
await findDirectoryPeople({ principal, organizationId, request, ...filters }),
registry
)
})
Expand Down
Loading
Loading