diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 3c3e5b9d99b..2c587b832ed 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -368,6 +368,48 @@ export const searchPeopleInputSchema = z message: 'Pass either personId or a query with its cursor, not both.', }) +/** + * The caller's own questions to Sim over a window, oldest first. The 92-day window and the page + * bounds are literals so the worker's generated copy stays standalone. + */ +export const listMyChatHistoryInputSchema = z + .object({ + startDate: z + .string() + .datetime({ offset: true }) + .describe( + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.' + ), + endDate: z + .string() + .datetime({ offset: true }) + .optional() + .describe( + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.' + ), + topK: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Questions per page, 50 by default.'), + cursor: z + .string() + .min(1) + .max(1024) + .optional() + .describe('nextCursor from the previous page of the same window.'), + includeAnswers: z + .boolean() + .optional() + .describe( + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked." + ), + }) + .strict() +export type ListMyChatHistoryInput = z.output + /** Connection requests name a provider and optionally an owned account to repair. */ export const oauthGetAuthLinkInputSchema = z.object({ providerName: z @@ -438,6 +480,13 @@ export const assistantToolContracts = [ 'Look up people in this organization’s directory by name, email, title, department, or location. Returns each person’s title, department, location, email, and manager. When exactly one person matches, or with a personId, returns that person with managerChain (direct manager first) and directReports. Covers only this organization’s people; use search_workspace for customers, vendors, and other outside contacts.', inputSchema: searchPeopleInputSchema, }, + { + id: 'list_my_chat_history', + route: 'sim', + description: + 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', + inputSchema: listMyChatHistoryInputSchema, + }, { id: 'oauth_get_auth_link', route: 'sim', diff --git a/apps/sim/lib/knowledge/application/chat-history.integration.ts b/apps/sim/lib/knowledge/application/chat-history.integration.ts new file mode 100644 index 00000000000..3ab0f95a4d9 --- /dev/null +++ b/apps/sim/lib/knowledge/application/chat-history.integration.ts @@ -0,0 +1,420 @@ +/** + * `list_my_chat_history` against real PostgreSQL: whose questions it returns, which conversations + * and turns it leaves out, its window bounds, keyset paging across identical timestamps, answer + * excerpts, and the principals it refuses. + */ +import type { SessionPrincipal, WorkspaceApiKeyPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { + copilotChats, + copilotMessages, + member, + organization, + permissions, + project, + user, + workspace, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { inArray } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +/** What the caller may open now: chat reads decide it from Build and Plan mode, stood in here. */ +const access = vi.hoisted(() => ({ canBuild: true, planEnabled: false })) +vi.mock('@/lib/mothership/chat/organization-chats', async (importOriginal) => { + const { OrchestrationError } = await import('@/lib/core/orchestration/types') + return { + ...(await importOriginal()), + requireOrganizationBuildPermission: async () => { + if (!access.canBuild) throw new OrchestrationError('forbidden', 'Build requires permission') + }, + } +}) +vi.mock('@/lib/mothership/feature-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isPlanModeEnabled: async () => access.planEnabled, +})) + +import { OrganizationMembershipNotFoundError } from '@/lib/core/application/organization-authorization' +import { PrincipalKindAuthorizationError } from '@/lib/core/application/workspace-authorization' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' + +const organizationId = generateId() +const otherOrganizationId = generateId() +const callerId = generateId() +const colleagueId = generateId() +const outsiderId = generateId() +const users = [callerId, colleagueId, outsiderId] +const organizationProjectId = generateId() +const otherProjectId = generateId() +const openWorkspaceId = generateId() +const closedWorkspaceId = generateId() +const otherOrganizationWorkspaceId = generateId() + +const WINDOW = { startDate: '2026-11-01T00:00:00Z', endDate: '2026-11-08T00:00:00Z' } + +function session(userId: string): SessionPrincipal { + return { kind: 'session', userId, sessionId: generateId() } +} + +function list(input: Record = {}, userId = callerId) { + return listMyChatHistory.execute({ + principal: session(userId), + input: { ...WINDOW, organizationId, ...input }, + }) +} + +async function chat(values: Partial = {}): Promise { + const id = generateId() + await db.insert(copilotChats).values({ + id, + userId: callerId, + organizationId, + type: 'mothership', + ...values, + }) + return id +} + +async function ask( + chatId: string, + content: string, + createdAt: string, + extra: Partial = {} +): Promise { + await db.insert(copilotMessages).values({ + chatId, + messageId: generateId(), + role: 'user', + content: { content }, + createdAt: new Date(createdAt), + ...extra, + }) +} + +describe('list_my_chat_history', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + users.map((id) => ({ + id, + name: 'History fixture', + email: `${id}@chat-history.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values( + [organizationId, otherOrganizationId].map((id) => ({ + id, + name: 'History fixture', + slug: `history-${id}`, + })) + ) + await db.insert(member).values([ + { id: generateId(), userId: callerId, organizationId, role: 'member' }, + { id: generateId(), userId: colleagueId, organizationId, role: 'member' }, + { + id: generateId(), + userId: outsiderId, + organizationId: otherOrganizationId, + role: 'member', + }, + ]) + await db.insert(project).values([ + { id: organizationProjectId, name: 'History', ownerId: colleagueId, organizationId }, + { + id: otherProjectId, + name: 'History', + ownerId: outsiderId, + organizationId: otherOrganizationId, + }, + ]) + await db.insert(workspace).values( + [ + [openWorkspaceId, organizationProjectId, organizationId], + [closedWorkspaceId, organizationProjectId, organizationId], + [otherOrganizationWorkspaceId, otherProjectId, otherOrganizationId], + ].map(([id, projectId, orgId]) => ({ + id, + projectId, + name: 'History workspace', + ownerId: orgId === organizationId ? colleagueId : outsiderId, + billedAccountUserId: orgId === organizationId ? colleagueId : outsiderId, + organizationId: orgId, + workspaceMode: 'organization' as const, + })) + ) + await db.insert(permissions).values( + [openWorkspaceId, otherOrganizationWorkspaceId].map((entityId) => ({ + id: generateId(), + userId: callerId, + entityType: 'workspace', + entityId, + permissionType: 'write' as const, + })) + ) + }) + + beforeEach(async () => { + await db.delete(copilotChats).where(inArray(copilotChats.userId, users)) + }) + + afterAll(async () => { + await db.delete(copilotChats).where(inArray(copilotChats.userId, users)) + await db + .delete(workspace) + .where( + inArray(workspace.id, [openWorkspaceId, closedWorkspaceId, otherOrganizationWorkspaceId]) + ) + await db.delete(project).where(inArray(project.id, [organizationProjectId, otherProjectId])) + await db + .delete(organization) + .where(inArray(organization.id, [organizationId, otherOrganizationId])) + await db.delete(user).where(inArray(user.id, users)) + }) + + it("returns only the caller's own questions, oldest first, with their surface and link", async () => { + const assistant = await chat() + const slack = await chat({ externalConversationKey: 'slack:["i","D1","t"]' }) + const agent = await chat({ config: { conversationMode: 'agent' } }) + await ask(assistant, 'second', '2026-11-02T10:00:00Z') + await ask(slack, 'first', '2026-11-01T09:00:00Z') + await ask(agent, 'third', '2026-11-03T08:00:00Z') + await ask(await chat({ userId: colleagueId }), 'colleague question', '2026-11-02T11:00:00Z') + + const { questions, nextCursor } = await list() + + expect( + questions.map(({ question, surface, timestamp }) => [question, surface, timestamp]) + ).toEqual([ + ['first', 'slack', '2026-11-01T09:00:00.000Z'], + ['second', 'assistant', '2026-11-02T10:00:00.000Z'], + ['third', 'agent', '2026-11-03T08:00:00.000Z'], + ]) + expect(questions[1]?.conversationUrl).toMatch( + new RegExp(`/o/${organizationId}/search/chat/${assistant}$`) + ) + expect(nextCursor).toBeUndefined() + }) + + it('leaves out deleted conversations and messages, automated turns, workflow copilot and benchmark chats', async () => { + const kept = await chat() + await ask(kept, 'kept', '2026-11-02T10:00:00Z') + await ask(kept, 'deleted message', '2026-11-02T10:01:00Z', { deletedAt: new Date() }) + await ask(kept, 'scheduled job brief', '2026-11-02T10:02:00Z', { + content: { content: 'Job: brief', origin: 'job' }, + }) + await ask(await chat({ deletedAt: new Date() }), 'deleted chat', '2026-11-02T11:00:00Z') + await ask( + await chat({ config: { benchmark: { id: 'b' } } }), + 'benchmark', + '2026-11-02T12:00:00Z' + ) + await ask( + await chat({ type: 'copilot', organizationId: null, workspaceId: openWorkspaceId }), + 'workflow copilot', + '2026-11-02T13:00:00Z' + ) + + expect((await list()).questions.map((q) => q.question)).toEqual(['kept']) + }) + + it("includes home chats only in the organization's workspaces the caller can open", async () => { + await ask( + await chat({ organizationId: null, workspaceId: openWorkspaceId }), + 'open workspace', + '2026-11-02T10:00:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: closedWorkspaceId }), + 'closed workspace', + '2026-11-02T11:00:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: otherOrganizationWorkspaceId }), + 'other organization', + '2026-11-02T12:00:00Z' + ) + + const { questions } = await list() + expect(questions.map((q) => [q.question, q.surface])).toEqual([['open workspace', 'agent']]) + expect(questions[0]?.conversationUrl).toMatch(new RegExp(`/workspace/${openWorkspaceId}/chat/`)) + }) + + it('leaves out conversations the caller can no longer open', async () => { + await ask(await chat(), 'assistant', '2026-11-02T10:00:00Z') + await ask( + await chat({ config: { conversationMode: 'agent' } }), + 'org agent', + '2026-11-02T10:01:00Z' + ) + await ask( + await chat({ config: { conversationMode: 'plan' } }), + 'org plan', + '2026-11-02T10:02:00Z' + ) + await ask( + await chat({ organizationId: null, workspaceId: openWorkspaceId }), + 'workspace agent', + '2026-11-02T10:03:00Z' + ) + const questions = async () => (await list()).questions.map((q) => q.question) + + try { + expect(await questions()).toEqual(['assistant', 'org agent', 'workspace agent']) + access.planEnabled = true + expect(await questions()).toEqual(['assistant', 'org agent', 'org plan', 'workspace agent']) + access.canBuild = false + expect(await questions()).toEqual(['assistant', 'workspace agent']) + } finally { + access.canBuild = true + access.planEnabled = false + } + }) + + it('includes startDate and excludes endDate, and refuses a window over 92 days', async () => { + const id = await chat() + await ask(id, 'at start', WINDOW.startDate) + await ask(id, 'at end', WINDOW.endDate) + + expect((await list()).questions.map((q) => q.question)).toEqual(['at start']) + await expect( + list({ startDate: '2026-01-01T00:00:00Z', endDate: '2026-04-04T00:00:00Z' }) + ).rejects.toThrow(/at most 92 days/) + await expect(list({ endDate: WINDOW.startDate })).rejects.toThrow(/after startDate/) + }) + + it('pages through questions asked at the same instant without repeating or skipping one', async () => { + const id = await chat() + for (let index = 0; index < 5; index++) await ask(id, `q${index}`, '2026-11-02T10:00:00Z') + + const seen: string[] = [] + let cursor: string | undefined + do { + const page = await list({ topK: 2, ...(cursor ? { cursor } : {}) }) + seen.push(...page.questions.map((q) => q.question)) + cursor = page.nextCursor + } while (cursor) + + expect(seen.sort()).toEqual(['q0', 'q1', 'q2', 'q3', 'q4']) + await expect(list({ cursor: 'not-a-cursor' })).rejects.toThrow(/nextCursor/) + }) + + it('adds the start of the next answer, without citation tags, only when asked', async () => { + const id = await chat() + await ask(id, 'what shipped?', '2026-11-02T10:00:00Z') + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { + content: `Two releases shipped {"id":"c1"}. ${'x'.repeat(900)}`, + }, + createdAt: new Date('2026-11-02T10:00:30Z'), + }) + + const withAnswers = (await list({ includeAnswers: true })).questions[0] + expect(withAnswers?.answerExcerpt?.startsWith('Two releases shipped . x')).toBe(true) + expect(withAnswers?.answerExcerpt?.length).toBeLessThan(700) + expect((await list()).questions[0]?.answerExcerpt).toBeUndefined() + }) + + it("gives an unanswered question no answer, rather than the next question's", async () => { + const id = await chat() + await ask(id, 'stopped question', '2026-11-02T10:00:00Z') + await ask(id, 'deleted question', '2026-11-02T10:00:20Z', { deletedAt: new Date() }) + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'The answer to the deleted question' }, + createdAt: new Date('2026-11-02T10:00:30Z'), + }) + await ask(id, 'answered question', '2026-11-02T10:01:00Z') + await db.insert(copilotMessages).values({ + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'The answer to the second question' }, + createdAt: new Date('2026-11-02T10:01:30Z'), + }) + + const { questions } = await list({ includeAnswers: true }) + expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([ + ['stopped question', undefined], + ['answered question', 'The answer to the second question'], + ]) + }) + + it("finds a reply that shares its question's timestamp, in transcript order", async () => { + const id = await chat() + const at = new Date('2026-11-02T10:00:00Z') + await db.insert(copilotMessages).values([ + { + id: 'ffffffff-ffff-4fff-bfff-ffffffffffff', + chatId: id, + messageId: generateId(), + role: 'user', + content: { content: 'same instant' }, + seq: 1, + createdAt: at, + }, + { + id: '00000000-0000-4000-8000-000000000000', + chatId: id, + messageId: generateId(), + role: 'assistant', + content: { content: 'Saved reply' }, + seq: 2, + createdAt: at, + }, + ]) + + const { questions } = await list({ includeAnswers: true }) + expect(questions.map((q) => [q.question, q.answerExcerpt])).toEqual([ + ['same instant', 'Saved reply'], + ]) + }) + + it('reads bounds in their own offset and runs to now without an endDate', async () => { + const id = await chat() + await ask(id, 'late on the 1st in Los Angeles', '2026-11-02T07:30:00Z') + await ask(id, 'recent', new Date(Date.now() - 60_000).toISOString()) + + const losAngeles = await list({ + startDate: '2026-11-01T00:00:00-08:00', + endDate: '2026-11-02T00:00:00-08:00', + }) + expect(losAngeles.questions.map((q) => q.question)).toEqual(['late on the 1st in Los Angeles']) + const sinceYesterday = await list({ + startDate: new Date(Date.now() - 86_400_000).toISOString(), + endDate: undefined, + }) + expect(sinceYesterday.questions.map((q) => q.question)).toEqual(['recent']) + const futureEnd = await list({ + startDate: new Date(Date.now() - 91 * 86_400_000).toISOString(), + endDate: new Date(Date.now() + 30 * 86_400_000).toISOString(), + }) + expect(futureEnd.questions.map((q) => q.question)).toContain('recent') + }) + + it('refuses a caller outside the organization and a principal that is not a person', async () => { + await ask(await chat(), 'private', '2026-11-02T10:00:00Z') + + await expect(list({}, outsiderId)).rejects.toBeInstanceOf(OrganizationMembershipNotFoundError) + const workspaceKey: WorkspaceApiKeyPrincipal = { + kind: 'workspace_api_key', + workspaceId: openWorkspaceId, + keyId: generateId(), + access: 'read', + } + await expect( + listMyChatHistory.execute({ + principal: workspaceKey, + input: { ...WINDOW, organizationId }, + }) + ).rejects.toBeInstanceOf(PrincipalKindAuthorizationError) + }) +}) diff --git a/apps/sim/lib/knowledge/application/chat-history.ts b/apps/sim/lib/knowledge/application/chat-history.ts new file mode 100644 index 00000000000..2e1ceebe87f --- /dev/null +++ b/apps/sim/lib/knowledge/application/chat-history.ts @@ -0,0 +1,258 @@ +import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { db } from '@sim/db' +import { copilotChats, copilotMessages } from '@sim/db/schema' +import { truncateAtCodePoint } from '@sim/utils/string' +import { and, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm' +import { z } from 'zod' +import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' +import { classifyTimestampCursor, preciseTimestampText } from '@/lib/api/list-query' +import { + defineAuthorizedOrganizationUseCase, + type OrganizationUseCaseContext, +} from '@/lib/core/application/authorized-organization-use-case' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { getBaseUrl } from '@/lib/core/utils/urls' +import { requireOrganizationSearchAvailable } from '@/lib/knowledge/access/availability' +import { stripInteractiveCards } from '@/lib/knowledge/application/chat-citations' +import { listMyChatHistoryOperation } from '@/lib/knowledge/application/chat-operations' +import { type ConversationMode, conversationModeSelection } from '@/lib/mothership/chat/intent' +import { requireOrganizationBuildPermission } from '@/lib/mothership/chat/organization-chats' +import { isPlanModeEnabled } from '@/lib/mothership/feature-flags' +import { organizationRoutes } from '@/lib/navigation/paths' +import { listAccessibleWorkspaceRowsForUser } from '@/lib/workspaces/utils' + +const DAY_MS = 86_400_000 +const MAX_WINDOW_DAYS = 92 +const DEFAULT_TOP_K = 50 +const QUESTION_MAX_CHARS = 2_000 +const ANSWER_EXCERPT_MAX_CHARS = 600 +/** Orders a message without a transcript `seq` after every numbered one, as transcripts read. */ +const LAST_SEQ = sql.raw('2147483647') + +type ChatHistorySurface = 'assistant' | 'agent' | 'slack' + +interface ChatHistoryQuestion { + /** When the question was asked, as an ISO datetime in UTC. */ + timestamp: string + question: string + chatId: string + conversationUrl: string + surface: ChatHistorySurface + /** The start of Sim's answer, when asked for and the question was answered. */ + answerExcerpt?: string +} + +interface ChatHistoryPage { + questions: ChatHistoryQuestion[] + nextCursor?: string +} + +/** A position in the caller's questions: the stored time at full precision and the message id. */ +const cursorSchema = z.tuple([ + z.string().refine((value) => classifyTimestampCursor(value) === 'precise'), + z.string().uuid(), +]) + +function encodeCursor(createdAt: string, id: string): string { + return Buffer.from(JSON.stringify([createdAt, id])).toString('base64url') +} + +function decodeCursor(cursor: string): [string, string] { + try { + const parsed = cursorSchema.safeParse(JSON.parse(Buffer.from(cursor, 'base64url').toString())) + if (parsed.success) return parsed.data + } catch {} + throw new OrchestrationError('validation', 'cursor is not a nextCursor from this tool') +} + +function resolveWindow(input: ListMyChatHistoryInput): { from: Date; to: Date } { + const from = new Date(input.startDate) + const now = new Date() + /** Nothing was asked after now, so a later end only widens the read. */ + const to = input.endDate && new Date(input.endDate) < now ? new Date(input.endDate) : now + if (to <= from) throw new OrchestrationError('validation', 'endDate must be after startDate') + if (to.getTime() - from.getTime() > MAX_WINDOW_DAYS * DAY_MS) + throw new OrchestrationError( + 'validation', + `The window is at most ${MAX_WINDOW_DAYS} days; page through a longer period in parts` + ) + return { from, to } +} + +/** Answer text as a reader sees it: no interactive cards, citation tags or runs of whitespace. */ +function answerExcerpt(content: string | null): string | undefined { + if (!content) return undefined + const text = stripInteractiveCards(content) + .replace(/[\s\S]*?<\/source>/g, '') + .replace(/\s+/g, ' ') + .trim() + return text ? truncateAtCodePoint(text, ANSWER_EXCERPT_MAX_CHARS) : undefined +} + +/** + * The caller's own questions to Sim in this organization, oldest first: Assistant and agent chats + * in the organization (including those asked through the Slack app and Search MCP `chat`), and + * home chats in the organization's workspaces the caller can still open. Deleted conversations and + * messages, automated task and job turns, workflow copilot chats and benchmark runs are left out. + * The caller is always the authenticated person; no input names anyone else. + */ +export const listMyChatHistory = defineAuthorizedOrganizationUseCase({ + operation: listMyChatHistoryOperation, + async execute({ + principal, + input, + context, + }: OrganizationUseCaseContext< + ListMyChatHistoryInput & { organizationId: string } + >): Promise { + const userId = requirePrincipalSubjectUserId(principal) + const { organizationId } = context + await requireOrganizationSearchAvailable(organizationId) + const { from, to } = resolveWindow(input) + const topK = input.topK ?? DEFAULT_TOP_K + const after = input.cursor ? decodeCursor(input.cursor) : undefined + + const workspaceIds = ( + await listAccessibleWorkspaceRowsForUser(userId, 'active', organizationId) + ) + .filter(({ workspace }) => workspace.organizationId === organizationId) + .map(({ workspace }) => workspace.id) + /** + * Only conversations the caller may open now, as chat reads decide it: agent and plan chats + * in the organization need Build, plan chats need Plan mode, and Assistant chats need neither. + */ + const [canBuild, planEnabled] = await Promise.all([ + requireOrganizationBuildPermission(context).then( + () => true, + (error: unknown) => { + if (error instanceof OrchestrationError && error.code === 'forbidden') return false + throw error + } + ), + isPlanModeEnabled(userId), + ]) + const organizationModes: ConversationMode[] = [ + 'assistant', + ...(canBuild ? (['agent'] as const) : []), + ...(canBuild && planEnabled ? (['plan'] as const) : []), + ] + const workspaceModes: ConversationMode[] = [ + 'agent', + ...(planEnabled ? (['plan'] as const) : []), + ] + /** The caller's chats first: few per person, so the message read probes each chat's index. */ + const chats = await db + .select({ + id: copilotChats.id, + workspaceId: copilotChats.workspaceId, + slack: sql`coalesce(${copilotChats.externalConversationKey} LIKE 'slack:%', false)`, + mode: conversationModeSelection, + }) + .from(copilotChats) + .where( + and( + eq(copilotChats.userId, userId), + eq(copilotChats.type, 'mothership'), + or( + and( + eq(copilotChats.organizationId, organizationId), + inArray(conversationModeSelection, organizationModes) + ), + workspaceIds.length + ? and( + inArray(copilotChats.workspaceId, workspaceIds), + inArray(conversationModeSelection, workspaceModes) + ) + : undefined + ), + isNull(copilotChats.deletedAt), + sql`${copilotChats.config}->'benchmark' IS NULL` + ) + ) + if (!chats.length) return { questions: [] } + const chatById = new Map(chats.map((chat) => [chat.id, chat])) + + /** + * The first reply to this question, never one that answers a later question in the chat (a + * deleted question still ends its turn), in + * transcript order (`seq`, then time and id): a turn's question and reply can share a + * timestamp. The outer row is named in full: a single-table select leaves its own columns + * unqualified, which inside these subqueries would resolve to the inner rows. + */ + const answer = input.includeAnswers + ? sql`( + SELECT coalesce(a.display_content, a.content)->>'content' + FROM ${copilotMessages} a + WHERE a.chat_id = copilot_messages.chat_id AND a.role = 'assistant' + AND a.deleted_at IS NULL + AND (coalesce(a.seq, ${LAST_SEQ}), a.created_at, a.id) + > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) + AND NOT EXISTS ( + SELECT 1 FROM ${copilotMessages} u + WHERE u.chat_id = a.chat_id AND u.role = 'user' + AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) + > (coalesce(copilot_messages.seq, ${LAST_SEQ}), copilot_messages.created_at, copilot_messages.id) + AND (coalesce(u.seq, ${LAST_SEQ}), u.created_at, u.id) + < (coalesce(a.seq, ${LAST_SEQ}), a.created_at, a.id)) + ORDER BY a.seq ASC NULLS LAST, a.created_at, a.id + LIMIT 1)` + : sql`NULL` + + const rows = await db + .select({ + id: copilotMessages.id, + chatId: copilotMessages.chatId, + createdAt: preciseTimestampText(copilotMessages.createdAt), + question: sql`${copilotMessages.content}->>'content'`, + answer, + }) + .from(copilotMessages) + .where( + and( + inArray(copilotMessages.chatId, [...chatById.keys()]), + eq(copilotMessages.role, 'user'), + isNull(copilotMessages.deletedAt), + sql`${copilotMessages.content}->>'origin' IS NULL`, + gte(copilotMessages.createdAt, from), + lt(copilotMessages.createdAt, to), + after + ? sql`(${copilotMessages.createdAt}, ${copilotMessages.id}) > (cast(${after[0]} as timestamp), ${after[1]}::uuid)` + : undefined + ) + ) + .orderBy(copilotMessages.createdAt, copilotMessages.id) + .limit(topK + 1) + + const routes = organizationRoutes(organizationId) + const page = rows.slice(0, topK) + const last = page[page.length - 1] + return { + questions: page.flatMap((row) => { + const chat = chatById.get(row.chatId) + if (!chat) return [] + const surface: ChatHistorySurface = chat.slack + ? 'slack' + : chat.workspaceId || chat.mode !== 'assistant' + ? 'agent' + : 'assistant' + const path = chat.workspaceId + ? `/workspace/${chat.workspaceId}/chat/${chat.id}` + : surface === 'assistant' + ? routes.searchChat(chat.id) + : routes.chat(chat.id) + const excerpt = answerExcerpt(row.answer) + return [ + { + timestamp: new Date(row.createdAt).toISOString(), + question: truncateAtCodePoint(row.question ?? '', QUESTION_MAX_CHARS), + chatId: chat.id, + conversationUrl: new URL(path, getBaseUrl()).href, + surface, + ...(excerpt ? { answerExcerpt: excerpt } : {}), + }, + ] + }), + ...(rows.length > topK && last ? { nextCursor: encodeCursor(last.createdAt, last.id) } : {}), + } + }, +}) diff --git a/apps/sim/lib/knowledge/application/chat-operations.ts b/apps/sim/lib/knowledge/application/chat-operations.ts index e255ceb845f..8c3788e3b35 100644 --- a/apps/sim/lib/knowledge/application/chat-operations.ts +++ b/apps/sim/lib/knowledge/application/chat-operations.ts @@ -7,3 +7,19 @@ export const organizationSearchChatOperation = defineOrganizationOperation({ principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], capability: 'copilot.use', }) + +/** + * A member reading back their own questions to Sim: in the app, through Search MCP clients under + * the scope that admits Search, from the organization Assistant under its Search delegation, and + * from a workflow run as its person. + */ +export const listMyChatHistoryOperation = defineOrganizationOperation({ + id: 'knowledge.chat_history.list', + oauthScope: 'search:read', + minimumRole: 'member', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'organization_delegated'], + delegationAudience: 'sim:knowledge', + delegatedServices: ['copilot', 'executor'], + contentDelivery: 'none', + capability: 'copilot.use', +}) diff --git a/apps/sim/lib/knowledge/mcp/chat-history.ts b/apps/sim/lib/knowledge/mcp/chat-history.ts new file mode 100644 index 00000000000..07dd334ef85 --- /dev/null +++ b/apps/sim/lib/knowledge/mcp/chat-history.ts @@ -0,0 +1,42 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import type { Principal } from '@sim/auth/principal' +import { listMyChatHistoryInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' +import { + KNOWLEDGE_MCP_READ_ONLY, + type KnowledgeMcpToolRunner, + projectResult, +} from '@/lib/knowledge/mcp/tool-runner' + +interface ChatHistoryToolContext { + execute: KnowledgeMcpToolRunner + principal: Principal + organizationId: string +} + +/** Registers `list_my_chat_history`: the caller's own questions to Sim, oldest first. */ +export function registerListMyChatHistoryTool( + server: McpServer, + { execute, principal, organizationId }: ChatHistoryToolContext +) { + server.registerTool( + 'list_my_chat_history', + { + title: 'List my chat history', + description: + 'List the questions you asked Sim between startDate (inclusive) and endDate (exclusive, at most 92 days later), oldest first: the Assistant, agent chats, the Slack app and this server’s chat tool. Each carries its time, a link to the conversation and, with includeAnswers, the start of the answer. Only your own conversations that still exist are listed. Follow nextCursor for the next page.', + inputSchema: listMyChatHistoryInputSchema, + annotations: KNOWLEDGE_MCP_READ_ONLY, + }, + async (input: unknown, extra: { signal: AbortSignal }) => + execute('list_my_chat_history', listMyChatHistory.operation, extra.signal, async (registry) => + projectResult( + await listMyChatHistory.execute({ + principal, + input: { ...listMyChatHistoryInputSchema.parse(input), organizationId }, + }), + registry + ) + ) + ) +} diff --git a/apps/sim/lib/knowledge/mcp/server.protocol.test.ts b/apps/sim/lib/knowledge/mcp/server.protocol.test.ts index 2e1dee80297..75372873bcb 100644 --- a/apps/sim/lib/knowledge/mcp/server.protocol.test.ts +++ b/apps/sim/lib/knowledge/mcp/server.protocol.test.ts @@ -72,7 +72,12 @@ describe('Search MCP protocol', () => { await server.connect(serverTransport) await client.connect(clientTransport) const { tools } = await client.listTools() - expect(tools.map((tool) => tool.name)).toEqual(['search', 'read_document', 'chat']) + expect(tools.map((tool) => tool.name)).toEqual([ + 'search', + 'read_document', + 'chat', + 'list_my_chat_history', + ]) const searchSchema = tools.find((tool) => tool.name === 'search')?.inputSchema const readSchema = tools.find((tool) => tool.name === 'read_document')?.inputSchema expect(searchSchema?.properties).toHaveProperty('nativeQueries') diff --git a/apps/sim/lib/knowledge/mcp/server.test.ts b/apps/sim/lib/knowledge/mcp/server.test.ts index 45ec7d82513..09c90ec596f 100644 --- a/apps/sim/lib/knowledge/mcp/server.test.ts +++ b/apps/sim/lib/knowledge/mcp/server.test.ts @@ -1,5 +1,8 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js' -import { createPersonalApiKeyPrincipal } from '@sim/testing/factories/principal.factory' +import { + createPersonalApiKeyPrincipal, + createWorkspaceApiKeyPrincipal, +} from '@sim/testing/factories/principal.factory' import { apiServerRoutesMock } from '@sim/testing/mocks/api-server-routes.mock' import { getMockLogger } from '@sim/testing/mocks/logger.mock' import { urlsMockFns } from '@sim/testing/mocks/urls.mock' @@ -500,9 +503,22 @@ describe('organization Search MCP tools', () => { }) describe('organization chat', () => { - it('exposes only the three organization Search tools', () => { + it('exposes the organization Search tools and the chat history of the caller', () => { create() - expect([...mocks.tools.keys()]).toEqual(['search', 'read_document', 'chat']) + expect([...mocks.tools.keys()]).toEqual([ + 'search', + 'read_document', + 'chat', + 'list_my_chat_history', + ]) + }) + it('offers no chat history to a workspace API key, which acts for no person', () => { + createKnowledgeMcpServer({ + organizationId: 'org-1', + request, + auth: { ...auth, principal: createWorkspaceApiKeyPrincipal(), keyType: 'workspace' }, + }) + expect(mocks.tools.has('list_my_chat_history')).toBe(false) }) it('does not run when rate limited', async () => { create() diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 1dccc6a7fb7..319dfbbbb55 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -18,6 +18,7 @@ import { recordOrganizationSearchMcpActivity, type SearchMcpActivityInput, } from '@/lib/knowledge/mcp/activity' +import { registerListMyChatHistoryTool } from '@/lib/knowledge/mcp/chat-history' import { callerErrorMessage, readOrganizationDocuments, @@ -202,6 +203,9 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe if (context.searchPeople) registerSearchPeopleTool(server, { execute, principal, organizationId, request }) + // Only a person has a chat history; a workspace API key acts for no one. + if (resolvePrincipalSubjectUserId(principal)) + registerListMyChatHistoryTool(server, { execute, principal, organizationId }) return server } diff --git a/apps/sim/lib/knowledge/mcp/tool-arguments.ts b/apps/sim/lib/knowledge/mcp/tool-arguments.ts index 8a7f50c62a1..c2f740b13bc 100644 --- a/apps/sim/lib/knowledge/mcp/tool-arguments.ts +++ b/apps/sim/lib/knowledge/mcp/tool-arguments.ts @@ -7,6 +7,7 @@ import { } from '@/lib/api/contracts/knowledge/mcp' import { mcpToolCallParamsSchema } from '@/lib/api/contracts/mcp' import { + listMyChatHistoryInputSchema, liveSearchProviderSchema, searchPeopleInputSchema, } from '@/lib/api/contracts/mothership-assistant-tools' @@ -27,6 +28,7 @@ const TOOL_INPUT_SCHEMAS = new Map([ ['read_document', readLiveDocumentMcpSchema], ['chat', chatSearchMcpSchema], ['search_people', searchPeopleInputSchema], + ['list_my_chat_history', listMyChatHistoryInputSchema], ]) function readToolCall(message: Record) { diff --git a/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts b/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts new file mode 100644 index 00000000000..99278a20732 --- /dev/null +++ b/apps/sim/lib/mothership/application/execute-chat-history-use-case.ts @@ -0,0 +1,39 @@ +import type { ListMyChatHistoryInput } from '@/lib/api/contracts/mothership-assistant-tools' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { listMyChatHistory } from '@/lib/knowledge/application/chat-history' +import { + COPILOT_APPLICATION_DELEGATION_TTL_MS, + type CopilotExecutionContext, + createTrustedOrganizationCopilotPrincipal, + requireTrustedOrganizationCopilotContext, +} from '@/lib/mothership/auth/application-delegation' +import { authorizeOrganizationChatDelegation } from '@/lib/mothership/chat/organization-chats' + +/** + * Lists the conversation owner's own questions for the organization Assistant. The person and + * organization come from the trusted turn and the delegation is bound to the member's private + * chat, so a model argument can never name another member's history. + */ +export async function executeCopilotChatHistoryRead( + context: CopilotExecutionContext | undefined, + input: ListMyChatHistoryInput +) { + const trusted = requireTrustedOrganizationCopilotContext(context) + if (context?.requestMode !== 'assistant') + throw new OrchestrationError( + 'forbidden', + 'Chat history is available only in organization Assistant conversations' + ) + const principal = createTrustedOrganizationCopilotPrincipal( + { ...trusted, delegationId: trusted.toolCallId }, + { + audience: listMyChatHistory.operation.delegationAudience, + ttlMs: COPILOT_APPLICATION_DELEGATION_TTL_MS, + } + ) + await authorizeOrganizationChatDelegation.execute({ principal }) + return listMyChatHistory.execute({ + principal, + input: { ...input, organizationId: trusted.organizationId }, + }) +} diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index e04059e1888..675d1417191 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -6,6 +6,7 @@ export const ASSISTANT_TOOLS = new Set([ 'search_workspace', 'read_document', 'search_people', + 'list_my_chat_history', 'oauth_get_auth_link', 'run_function', ]) diff --git a/apps/sim/lib/mothership/generated/tool-catalog-v1.ts b/apps/sim/lib/mothership/generated/tool-catalog-v1.ts index dc17ad3c564..3b6fea88b16 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.' + | 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.' | '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.' @@ -89,6 +90,7 @@ export interface ToolCatalogEntry { | 'knowledge' | 'list_deployment_versions' | 'list_integration_tools' + | 'list_my_chat_history' | 'list_user_projects' | 'list_workspace_mcp_servers' | 'list_workspaces' @@ -7792,6 +7794,54 @@ export const SearchPeople: ToolCatalogEntry = { }, } +export const ListMyChatHistory: ToolCatalogEntry = { + id: 'list_my_chat_history', + description: + 'List the questions you asked Sim (the Assistant, agent chats, the Slack app and Search MCP chat) in a time window, oldest first, each with a link to its conversation. Covers only your own conversations that still exist.', + route: 'sim', + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + description: + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.', + }, + endDate: { + description: + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + topK: { + description: 'Questions per page, 50 by default.', + type: 'integer', + minimum: 1, + maximum: 100, + }, + cursor: { + description: 'nextCursor from the previous page of the same window.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + includeAnswers: { + description: + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked.", + type: 'boolean', + }, + }, + required: ['startDate'], + additionalProperties: false, + }, +} + export const Dashboards: ToolCatalogEntry = { id: 'dashboards', description: @@ -8802,6 +8852,7 @@ export const TOOL_CATALOG: Record = { [ListUserProjects.id]: ListUserProjects, [ListWorkspaces.id]: ListWorkspaces, [SearchPeople.id]: SearchPeople, + [ListMyChatHistory.id]: ListMyChatHistory, [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 2c5250f21e4..ac9f13088cf 100644 --- a/apps/sim/lib/mothership/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/mothership/generated/tool-schemas-v1.ts @@ -7872,6 +7872,50 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, + list_my_chat_history: { + parameters: { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + properties: { + startDate: { + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + description: + 'Inclusive lower bound on when you asked, as an ISO datetime with your timezone offset. For whole days, use local midnight on the first day.', + }, + endDate: { + description: + 'Exclusive upper bound, at most 92 days after startDate; defaults to now. For whole days, use local midnight after the final day.', + type: 'string', + format: 'date-time', + pattern: + '^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$', + }, + topK: { + description: 'Questions per page, 50 by default.', + type: 'integer', + minimum: 1, + maximum: 100, + }, + cursor: { + description: 'nextCursor from the previous page of the same window.', + type: 'string', + minLength: 1, + maxLength: 1024, + }, + includeAnswers: { + description: + "Adds the start of Sim's answer to each question. Answers reflect the sources as they were when asked.", + type: 'boolean', + }, + }, + required: ['startDate'], + additionalProperties: false, + }, + resultSchema: undefined, + }, dashboards: { parameters: { $schema: 'http://json-schema.org/draft-07/schema#', diff --git a/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts b/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts new file mode 100644 index 00000000000..1a2635cec38 --- /dev/null +++ b/apps/sim/lib/mothership/tools/server/knowledge/chat-history.ts @@ -0,0 +1,40 @@ +import { createLogger } from '@sim/logger' +import { z } from 'zod' +import { listMyChatHistoryInputSchema } from '@/lib/api/contracts/mothership-assistant-tools' +import { getValidationErrorMessage } from '@/lib/api/server/validation' +import { messageForCopilotApplicationError } from '@/lib/mothership/application/errors' +import { executeCopilotChatHistoryRead } from '@/lib/mothership/application/execute-chat-history-use-case' +import type { BaseServerTool, ServerToolContext } from '@/lib/mothership/tools/server/base-tool' + +const logger = createLogger('ListMyChatHistoryTool') + +/** `list_my_chat_history` for the organization Assistant: the Search MCP tool of that name. */ +export const listMyChatHistoryServerTool: BaseServerTool = { + name: 'list_my_chat_history', + inputSchema: listMyChatHistoryInputSchema, + async execute(raw, context?: ServerToolContext) { + if (!context?.organizationId) + return { + success: false, + message: 'Chat history is available only in organization conversations.', + } + try { + const data = await executeCopilotChatHistoryRead( + context, + listMyChatHistoryInputSchema.parse(raw) + ) + return { success: true, data } + } catch (error) { + if (error instanceof z.ZodError) + return { + success: false, + message: getValidationErrorMessage(error, 'Invalid chat history arguments'), + } + logger.error('Chat history lookup failed', { error }) + return { + success: false, + message: messageForCopilotApplicationError(error, 'Chat history lookup failed'), + } + } + }, +} diff --git a/apps/sim/lib/mothership/tools/server/router.ts b/apps/sim/lib/mothership/tools/server/router.ts index dadf6835809..c62322249ab 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 { listMyChatHistoryServerTool } from '@/lib/mothership/tools/server/knowledge/chat-history' import { searchPeopleServerTool } from '@/lib/mothership/tools/server/knowledge/people' import { readDocumentServerTool, @@ -81,6 +82,7 @@ const baseServerToolRegistry: Record = { [openResourceServerTool.name]: openResourceServerTool, [readDocumentServerTool.name]: readDocumentServerTool, [searchPeopleServerTool.name]: searchPeopleServerTool, + [listMyChatHistoryServerTool.name]: listMyChatHistoryServerTool, // 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),