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
65 changes: 60 additions & 5 deletions apps/sim/blocks/blocks/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const OPERATIONS = [
{ label: 'Search', id: 'search' },
{ label: 'Read Document', id: 'read_document' },
{ label: 'Search People', id: 'search_people' },
{ label: 'List My Chat History', id: 'list_my_chat_history' },
] as const

const OPERATION_IDS = new Set<string>(OPERATIONS.map((operation) => operation.id))
Expand All @@ -20,9 +21,9 @@ const OPERATION_IDS = new Set<string>(OPERATIONS.map((operation) => operation.id
export const OrganizationBlock: BlockConfig = {
type: 'organization',
name: 'Organization Search',
description: 'Search your organization’s sources and people directory',
description: 'Search your organization’s sources, people directory, and your own chat history',
longDescription:
'Search the organization’s connected sources through their live APIs, read the documents they return, and look people up in the People directory. Every operation runs as the person who started the run, within their own access, so a scheduled or webhook run without a person fails instead of borrowing anyone’s access.',
'Search the organization’s connected sources through their live APIs, read the documents they return, and look people up in the People directory, and list your own questions to Sim over a date window. Every operation runs as the person who started the run, within their own access, so a scheduled or webhook run without a person fails instead of borrowing anyone’s access.',
bestPractices: `
- Use Search to find candidates, then Read Document with a returned documentId when the passage is not enough.
- Search People covers only this organization's people; use Search for customers, vendors, and other outside contacts.
Expand All @@ -41,6 +42,10 @@ export const OrganizationBlock: BlockConfig = {
],
read_document: [{ text: 'Read', field: 'documentId', core: true }],
search_people: ['Find people', { text: 'matching', field: 'query' }],
list_my_chat_history: [
'List my questions to Sim',
{ text: 'since', field: 'historyStartDate' },
],
},
},
},
Expand Down Expand Up @@ -85,6 +90,35 @@ export const OrganizationBlock: BlockConfig = {
condition: { field: 'operation', value: 'search' },
mode: 'advanced',
},
{
id: 'historyStartDate',
title: 'Start Date',
type: 'short-input',
placeholder: '2026-01-01T00:00:00-08:00 (inclusive)',
condition: { field: 'operation', value: 'list_my_chat_history' },
required: { field: 'operation', value: 'list_my_chat_history' },
},
{
id: 'historyEndDate',
title: 'End Date',
type: 'short-input',
placeholder: 'Now, or an exclusive ISO datetime',
condition: { field: 'operation', value: 'list_my_chat_history' },
},
{
id: 'historyCursor',
title: 'Cursor',
type: 'short-input',
placeholder: 'nextCursor from the previous page',
condition: { field: 'operation', value: 'list_my_chat_history' },
mode: 'advanced',
},
{
id: 'includeAnswers',
title: 'Include Answers',
type: 'switch',
condition: { field: 'operation', value: 'list_my_chat_history' },
},
{
id: 'modifiedAfter',
title: 'Modified After',
Expand Down Expand Up @@ -144,8 +178,8 @@ export const OrganizationBlock: BlockConfig = {
id: 'topK',
title: 'Max Results',
type: 'short-input',
placeholder: '20',
condition: { field: 'operation', value: 'search' },
placeholder: '20 for Search, 50 for chat history',
condition: { field: 'operation', value: ['search', 'list_my_chat_history'] },
mode: 'advanced',
},
{
Expand Down Expand Up @@ -208,6 +242,13 @@ export const OrganizationBlock: BlockConfig = {
throw new Error('Read Document needs either a Document or a list of Documents')
return {
...params,
...(operation === 'list_my_chat_history'
? {
startDate: blockFieldOrToolArg(context, params.historyStartDate, params.startDate),
endDate: blockFieldOrToolArg(context, params.historyEndDate, params.endDate),
cursor: blockFieldOrToolArg(context, params.historyCursor, params.cursor),
}
: {}),
...(operation === 'search'
? {
documentIds: blockFieldOrToolArg(
Expand Down Expand Up @@ -250,6 +291,13 @@ export const OrganizationBlock: BlockConfig = {
startOffset: { type: 'number', description: 'Where to continue reading' },
personId: { type: 'string', description: 'Person to show with their reporting line' },
cursor: { type: 'string', description: 'Next page of a people search' },
historyCursor: { type: 'string', description: 'Chat history: next page of the same window' },
historyStartDate: {
type: 'string',
description: 'Chat history: inclusive start (ISO datetime)',
},
historyEndDate: { type: 'string', description: 'Chat history: exclusive end (ISO datetime)' },
includeAnswers: { type: 'boolean', description: 'Chat history: add the start of each answer' },
},
outputs: {
results: { type: 'array', description: 'Search: matching documents with passages' },
Expand All @@ -267,7 +315,14 @@ export const OrganizationBlock: BlockConfig = {
},
people: { type: 'array', description: 'Search People: matching people' },
person: { type: 'json', description: 'Search People: the one matching person' },
nextCursor: { type: 'string', description: 'Search People: cursor for the next page' },
nextCursor: {
type: 'string',
description: 'Search People or List My Chat History: cursor for the next page',
},
questions: {
type: 'array',
description: 'List My Chat History: the person’s own questions, oldest first',
},
note: { type: 'string', description: 'Search People: guidance when no one matches' },
},
}
2 changes: 1 addition & 1 deletion apps/sim/blocks/sdk-names.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ const BLOCKS: Record<string, string> = {
openai: '{"namespace":"legacy.openai"}',
oracle_fusion_financials: '{"namespace":"oracleFusionFinancials","methods":{"oracle_fusion_financials_apply_receivables_receipt":"applyReceivablesReceipt","oracle_fusion_financials_approve_receivables_invoice":"approveReceivablesInvoice","oracle_fusion_financials_create_expense_line":"createExpenseLine","oracle_fusion_financials_create_expense_report":"createExpenseReport","oracle_fusion_financials_create_receivables_credit_memo":"createReceivablesCreditMemo","oracle_fusion_financials_create_receivables_invoice":"createReceivablesInvoice","oracle_fusion_financials_create_receivables_receipt":"createReceivablesReceipt","oracle_fusion_financials_get_expense_line":"getExpenseLine","oracle_fusion_financials_get_expense_report":"getExpenseReport","oracle_fusion_financials_get_gl_journal_batch":"getGlJournalBatch","oracle_fusion_financials_get_gl_ledger":"getGlLedger","oracle_fusion_financials_get_payables_invoice":"getPayablesInvoice","oracle_fusion_financials_get_payables_invoice_line":"getPayablesInvoiceLine","oracle_fusion_financials_get_payables_payment":"getPayablesPayment","oracle_fusion_financials_get_receivables_credit_memo":"getReceivablesCreditMemo","oracle_fusion_financials_get_receivables_invoice":"getReceivablesInvoice","oracle_fusion_financials_get_receivables_invoice_installment":"getReceivablesInvoiceInstallment","oracle_fusion_financials_get_receivables_invoice_line":"getReceivablesInvoiceLine","oracle_fusion_financials_get_receivables_receipt":"getReceivablesReceipt","oracle_fusion_financials_list_expense_lines":"listExpenseLines","oracle_fusion_financials_list_expense_reports":"listExpenseReports","oracle_fusion_financials_list_gl_balances":"listGlBalances","oracle_fusion_financials_list_gl_journal_batches":"listGlJournalBatches","oracle_fusion_financials_list_gl_ledgers":"listGlLedgers","oracle_fusion_financials_list_payables_invoice_lines":"listPayablesInvoiceLines","oracle_fusion_financials_list_payables_invoices":"listPayablesInvoices","oracle_fusion_financials_list_payables_payments":"listPayablesPayments","oracle_fusion_financials_list_receivables_credit_memos":"listReceivablesCreditMemos","oracle_fusion_financials_list_receivables_invoice_installments":"listReceivablesInvoiceInstallments","oracle_fusion_financials_list_receivables_invoice_lines":"listReceivablesInvoiceLines","oracle_fusion_financials_list_receivables_invoices":"listReceivablesInvoices","oracle_fusion_financials_list_receivables_receipts":"listReceivablesReceipts","oracle_fusion_financials_submit_expense_report":"submitExpenseReport","oracle_fusion_financials_update_expense_line":"updateExpenseLine","oracle_fusion_financials_update_expense_report":"updateExpenseReport","oracle_fusion_financials_update_receivables_invoice":"updateReceivablesInvoice"},"paramAliases":{"action":{"oauthCredential":"credential"}}}',
oracledb: '{"namespace":"oracledb","methods":{"delete":"deleteData","execute":"executeSql","insert":"insertData","introspect":"introspectSchema","query":"querySelect","update":"updateData"},"paramAliases":{"action":{"oauthCredential":"credential"}}}',
organization: '{"namespace":"organization","methods":{"read_document":"readDocument","search":"search","search_people":"searchPeople"}}',
organization: '{"namespace":"organization","methods":{"list_my_chat_history":"listMyChatHistory","read_document":"readDocument","search":"search","search_people":"searchPeople"}}',
otter: '{"namespace":"legacy.otter","methods":{"create_conversation":"importRecording","get_conversation":"getConversation","get_conversation_audio":"getConversationAudio","get_workspace":"getWorkspace","list_channel_members":"listChannelMembers","list_channels":"listChannels","list_conversations":"listConversations","list_workspace_conversations":"listWorkspaceConversations"},"triggers":{"otter_conversation_completed":"conversationCompleted","otter_conversation_shared":"conversationShared","otter_webhook":"webhook"}}',
otter_v2: '{"namespace":"otter","methods":{"create_conversation":"importRecording","get_conversation":"getConversation","get_conversation_audio":"getConversationAudio","get_workspace":"getWorkspace","list_channel_members":"listChannelMembers","list_channels":"listChannels","list_conversations":"listConversations","list_workspace_conversations":"listWorkspaceConversations"},"triggers":{"otter_conversation_completed":"conversationCompleted","otter_conversation_shared":"conversationShared","otter_webhook":"webhook"},"paramAliases":{"action":{"oauthCredential":"credential"}}}',
outlook: '{"namespace":"outlook","methods":{"copy_outlook":"copyEmail","create_event_calendar":"createEvent","create_folder_outlook":"createFolder","delete_event_calendar":"deleteEvent","delete_outlook":"deleteEmail","draft_outlook":"draftEmail","forward_outlook":"forwardEmail","get_attachment_outlook":"getAttachment","get_event_calendar":"getCalendarEvent","list_attachments_outlook":"listAttachments","list_events_calendar":"listCalendarEvents","list_folders_outlook":"listFolders","mark_read_outlook":"markAsRead","mark_unread_outlook":"markAsUnread","move_outlook":"moveEmail","read_outlook":"readEmail","reply_all_outlook":"replyAll","reply_outlook":"replyToEmail","respond_calendar":"respondToInvite","search_outlook":"searchEmail","send_outlook":"sendEmail","update_event_calendar":"updateEvent","update_message_outlook":"setCategoriesFlag"},"triggers":{"outlook_poller":"poller"},"paramAliases":{"action":{"oauthCredential":"credential"},"trigger":{"oauthCredential":"credential"}}}',
Expand Down
1 change: 1 addition & 0 deletions apps/sim/blocks/sdk-names/organization.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"namespace": "organization",
"methods": {
"list_my_chat_history": "listMyChatHistory",
"read_document": "readDocument",
"search": "search",
"search_people": "searchPeople"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@
*/
import type { ExecutorOrganizationDelegatedPrincipal } from '@sim/auth/principal'
import { db } from '@sim/db'
import { member, organization, user, workflow, workspace } from '@sim/db/schema'
import {
copilotChats,
copilotMessages,
member,
organization,
user,
workflow,
workspace,
} from '@sim/db/schema'
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
import { generateId } from '@sim/utils/id'
import { inArray } from 'drizzle-orm'
Expand Down Expand Up @@ -40,10 +48,11 @@ const users = [memberUserId, colleagueUserId, outsiderUserId]

function call(
context: Partial<InternalToolOperationContext> & { workflowId: string },
input: unknown
input: unknown,
toolId = 'organization_search_people'
) {
return executeOrganizationSearchTool({
toolId: 'organization_search_people',
toolId,
input,
headers: new Headers(),
context,
Expand Down Expand Up @@ -156,6 +165,34 @@ describe('Organization Search tools in a workflow run', () => {
})
})

it("lists the run's person's own chat history, never a colleague's", async () => {
for (const [userId, question] of [
[memberUserId, 'my question'],
[colleagueUserId, 'colleague question'],
] as const) {
const chatId = generateId()
await db
.insert(copilotChats)
.values({ id: chatId, userId, organizationId, type: 'mothership' })
await db.insert(copilotMessages).values({
chatId,
messageId: generateId(),
role: 'user',
content: { content: question },
createdAt: new Date('2026-11-02T10:00:00Z'),
})
}

const response = await call(
runAs(memberUserId, organizationWorkflowId, organizationWorkspaceId),
{ startDate: '2026-11-01T00:00:00Z', endDate: '2026-11-08T00:00:00Z' },
'organization_list_my_chat_history'
)
expect(response.status).toBe(200)
const body = await response.json()
expect(body.questions.map((q: { question: string }) => q.question)).toEqual(['my question'])
})

it('refuses a run in an organization without Search', async () => {
searchAvailable.value = false
try {
Expand All @@ -172,29 +209,36 @@ describe('Organization Search tools in a workflow run', () => {
}
})

it('refuses a scheduled run, which has no person to search as', async () => {
const response = await call(
{
workflowId: organizationWorkflowId,
workspaceId: organizationWorkspaceId,
userId: memberUserId,
executorDelegationOrigin: {
it.each([
['organization_search_people', { query: colleagueName }],
['organization_list_my_chat_history', { startDate: '2026-11-01T00:00:00Z' }],
] as const)(
'refuses a scheduled run of %s, which has no person to act as',
async (toolId, input) => {
const response = await call(
{
workflowId: organizationWorkflowId,
principal: {
kind: 'system',
serviceId: 'schedule',
workspaceId: organizationWorkspaceId,
workspaceId: organizationWorkspaceId,
userId: memberUserId,
executorDelegationOrigin: {
workflowId: organizationWorkflowId,
principal: {
kind: 'system',
serviceId: 'schedule',
workspaceId: organizationWorkspaceId,
workflowId: organizationWorkflowId,
},
},
},
},
{ query: colleagueName }
)
expect(response.status).toBe(403)
expect(await response.json()).toEqual({
error: expect.stringContaining('scheduled and webhook triggers run without a user'),
})
})
input,
toolId
)
expect(response.status).toBe(403)
expect(await response.json()).toEqual({
error: expect.stringContaining('scheduled and webhook triggers run without a user'),
})
}
)

it("refuses a person who is not a member of the workflow's organization", async () => {
const response = await call(
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/lib/internal/organization-search/execute-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger'
import { isPlainRecord } from '@sim/utils/object'
import { orchestrationFailureResponse } from '@/lib/api/server/orchestration-response'
import { RESOLVED_SECRET_PROVENANCE_FIELD } from '@/lib/execution/private-tool-metadata'
import { listOrganizationChatHistory } from '@/lib/internal/organization-search/list-my-chat-history'
import { readOrganizationDocument } from '@/lib/internal/organization-search/read-document'
import { searchOrganization } from '@/lib/internal/organization-search/search'
import { searchOrganizationPeople } from '@/lib/internal/organization-search/search-people'
Expand All @@ -25,6 +26,7 @@ const HANDLERS: Record<OrganizationSearchToolId, OrganizationSearchToolHandler>
organization_search: searchOrganization,
organization_read_document: readOrganizationDocument,
organization_search_people: searchOrganizationPeople,
organization_list_my_chat_history: listOrganizationChatHistory,
}

function failureResponse(toolId: string, error: unknown): Response {
Expand Down
17 changes: 17 additions & 0 deletions apps/sim/lib/internal/organization-search/list-my-chat-history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { listMyChatHistoryInputSchema } from '@/lib/api/contracts/mothership-assistant-tools'
import { respondWithResultProvenance } from '@/lib/internal/organization-search/provenance'
import type { OrganizationSearchToolHandler } from '@/lib/internal/organization-search/types'
import { parseInternalOperationInput } from '@/lib/internal/tool-operations/parse-contract-input'
import { listMyChatHistory } from '@/lib/knowledge/application/chat-history'

/** `list_my_chat_history`, as the Search MCP and Assistant tool of that name: the run's person's own questions. */
export const listOrganizationChatHistory: OrganizationSearchToolHandler = async (call) => {
const parsed = parseInternalOperationInput({ body: listMyChatHistoryInputSchema }, call.input)
if (!parsed.success) return parsed.response
return respondWithResultProvenance(call, undefined, () =>
listMyChatHistory.execute({
principal: call.principal,
input: { ...parsed.data.body, organizationId: call.principal.organizationId },
})
)
}
1 change: 1 addition & 0 deletions apps/sim/lib/internal/organization-search/tool-ids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const ORGANIZATION_SEARCH_TOOL_IDS = [
'organization_search',
'organization_read_document',
'organization_search_people',
'organization_list_my_chat_history',
] as const

export type OrganizationSearchToolId = (typeof ORGANIZATION_SEARCH_TOOL_IDS)[number]
2 changes: 1 addition & 1 deletion apps/sim/lib/knowledge/application/chat-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ interface ChatHistoryQuestion {
answerExcerpt?: string
}

interface ChatHistoryPage {
type ChatHistoryPage = {
questions: ChatHistoryQuestion[]
nextCursor?: string
}
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/tools/generated/tool-ids.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion apps/sim/tools/generated/tool-metadata.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion apps/sim/tools/generated/tool-outputs.ts

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions apps/sim/tools/organization/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { organizationListMyChatHistoryTool } from '@/tools/organization/list_my_chat_history'
export { organizationReadDocumentTool } from '@/tools/organization/read_document'
export { organizationSearchTool } from '@/tools/organization/search'
export { organizationSearchPeopleTool } from '@/tools/organization/search_people'
Loading
Loading