Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): new channel read tools (#2885)

teobee3a531009b
diff --git a/js/app/packages/core/component/AI/component/debug/mockData.ts b/js/app/packages/core/component/AI/component/debug/mockData.ts
index d0b5a74ec3..c193464177 100644
--- a/js/app/packages/core/component/AI/component/debug/mockData.ts
+++ b/js/app/packages/core/component/AI/component/debug/mockData.ts
@@ -96,11 +96,19 @@ export function toolCall(_delay: NetworkDelay = noDelay) {
type: 'toolCall',
tool: {
data: {
- contentType: 'channel',
- ids: ['this-is-not-a-real-id'],
- messagesSince: null,
+ channelId: '00000000-0000-0000-0000-000000000001',
+ windowType: 'latest',
+ cursor: null,
+ direction: null,
+ from: null,
+ includeThreadPreviews: true,
+ limit: 25,
+ maxCharsPerMessage: null,
+ messageId: null,
+ messageIds: [],
+ to: null,
},
- name: 'ReadThread',
+ name: 'ReadChannelMessages',
},
},
{
diff --git a/js/app/packages/core/component/AI/component/tool/ReadChannel.tsx b/js/app/packages/core/component/AI/component/tool/ReadChannel.tsx
new file mode 100644
index 0000000000..0c74cc5572
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/ReadChannel.tsx
@@ -0,0 +1,170 @@
+import { useChannelName } from '@core/context/channels';
+import EyeIcon from '@phosphor-icons/core/regular/eye.svg';
+import {
+ addDays,
+ isEqual,
+ isSameDay,
+ isSameYear,
+ isToday,
+ isValid,
+ isYesterday,
+ startOfDay,
+ subMilliseconds,
+} from 'date-fns';
+import { match, P } from 'ts-pattern';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+function parseDate(value: string | null | undefined) {
+ if (!value) return undefined;
+ const date = new Date(value);
+ return isValid(date) ? date : undefined;
+}
+
+function formatDay(date: Date) {
+ if (isToday(date)) return 'Today';
+ if (isYesterday(date)) return 'Yesterday';
+
+ const now = new Date();
+ return date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: isSameYear(date, now) ? undefined : 'numeric',
+ });
+}
+
+function formatTime(date: Date) {
+ return date.toLocaleTimeString(undefined, {
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+}
+
+function formatDateTime(date: Date) {
+ return `${formatDay(date)}, ${formatTime(date)}`;
+}
+
+function formatTimeRange(
+ fromValue: string | null | undefined,
+ toValue: string | null | undefined
+) {
+ const from = parseDate(fromValue);
+ const to = parseDate(toValue);
+
+ if (from && to) {
+ if (isEqual(from, startOfDay(from)) && isEqual(to, startOfDay(to))) {
+ if (isEqual(to, addDays(from, 1))) return formatDay(from);
+
+ const inclusiveEnd = subMilliseconds(to, 1);
+ return `${formatDay(from)} → ${formatDay(inclusiveEnd)}`;
+ }
+
+ if (isSameDay(from, to)) {
+ return `${formatDay(from)}, ${formatTime(from)}–${formatTime(to)}`;
+ }
+
+ return `${formatDateTime(from)} → ${formatDateTime(to)}`;
+ }
+
+ if (from) return `after ${formatDateTime(from)}`;
+ if (to) return `before ${formatDateTime(to)}`;
+ return 'time range';
+}
+
+function formatReadChannelWindow(args: {
+ windowType: 'latest' | 'timeRange' | 'aroundMessage' | 'page' | 'messages';
+ from?: string | null;
+ to?: string | null;
+ direction?: 'older' | 'newer' | null;
+}) {
+ return match(args)
+ .with(
+ { windowType: 'timeRange' },
+ ({ from, to }) => `filtered by activity ${formatTimeRange(from, to)}`
+ )
+ .with(
+ { windowType: 'page', direction: P.union('older', 'newer') },
+ ({ direction }) => `page ${direction}`
+ )
+ .with({ windowType: 'page' }, () => 'page')
+ .with({ windowType: 'aroundMessage' }, () => 'around message')
+ .with({ windowType: 'messages' }, () => 'specific messages')
+ .with({ windowType: 'latest' }, () => 'latest')
+ .exhaustive();
+}
+
+export const readChannelMessagesHandler = createToolRenderer({
+ name: 'ReadChannelMessages',
+ render: (ctx) => {
+ const channelName = useChannelName(ctx.tool.data.channelId, 'Channel');
+ const messageCount = () => ctx.response?.data.messages?.length ?? 0;
+ const windowLabel = () =>
+ formatReadChannelWindow({
+ windowType:
+ ctx.response?.data.window.windowType ?? ctx.tool.data.windowType,
+ from: ctx.response?.data.window.from ?? ctx.tool.data.from,
+ to: ctx.response?.data.window.to ?? ctx.tool.data.to,
+ direction:
+ ctx.response?.data.window.direction ?? ctx.tool.data.direction,
+ });
+
+ return (
+ <BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>
+ <div class="flex min-w-0 flex-1 flex-col gap-1">
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <span>
+ Read messages in <span class="text-accent">{channelName()}</span>
+ </span>
+ {ctx.response && (
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {messageCount()} messages
+ </span>
+ )}
+ </div>
+ <div class="text-xs text-ink-placeholder">{windowLabel()}</div>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const readChannelMessageContextHandler = createToolRenderer({
+ name: 'ReadChannelMessageContext',
+ render: (ctx) => {
+ const channelName = useChannelName(ctx.tool.data.channelId, 'Channel');
+
+ return (
+ <BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ Read <span class="text-accent">{channelName()}</span> message
+ context
+ </span>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const readChannelThreadHandler = createToolRenderer({
+ name: 'ReadChannelThread',
+ render: (ctx) => {
+ const channelName = useChannelName(ctx.tool.data.channelId, 'Channel');
+ const replyCount = () => ctx.response?.data.replies?.length ?? 0;
+
+ return (
+ <BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ Read <span class="text-accent">{channelName()}</span> thread
+ </span>
+ {ctx.response && (
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {replyCount()} replies
+ </span>
+ )}
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsx
index f950722a59..20a92f73bd 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -15,6 +15,11 @@ import {
setEntityPropertyHandler,
} from './Properties';
import { readCallRecordHandler } from './ReadCallRecord';
+import {
+ readChannelMessageContextHandler,
+ readChannelMessagesHandler,
+ readChannelThreadHandler,
+} from './ReadChannel';
import { readChatHandler } from './ReadChat';
import { readContentHandler } from './ReadContent';
import { readMetadataHandler } from './ReadMetadata';
@@ -44,6 +49,9 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
GetThread: getThreadHandler,
NameSearch: nameSearchHandler,
ReadCallRecord: readCallRecordHandler,
+ ReadChannelMessageContext: readChannelMessageContextHandler,
+ ReadChannelMessages: readChannelMessagesHandler,
+ ReadChannelThread: readChannelThreadHandler,
ReadChat: readChatHandler,
ReadThread: readThreadHandler,
ReadContent: readContentHandler,
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index 131765c361..3ecc1ce388 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -364,7 +364,7 @@ export const GetEntityPropertiesResponse = z.object({
summary: z.string(),
});
-export const ReadThread = z.object({
+export const GetThread = z.object({
limit: z.union([z.number().int(), z.null()]).default(null),
threadId: z.string().uuid(),
});
@@ -529,6 +529,827 @@ export const ReadCallRecordResponse = z.object({
),
});
+export const ReadChannelMessageContext = z.object({
+ channelAfter: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .default(null),
+ channelBefore: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .default(null),
+ channelId: z.string().uuid(),
+ maxCharsPerMessage: z
+ .union([z.number().int().gte(0), z.null()])
+ .default(null),
+ messageId: z.string().uuid(),
+ threadAfter: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .default(null),
+ threadBefore: z
+ .union([z.number().int().gte(0).lte(65535), z.null()])
+ .default(null),
+});
+
+export const ReadChannelMessageContextResponse = z.object({
+ anchor: z.object({
+ channelId: z.string().uuid(),
+ createdAt: z.string().datetime({ offset: true }),
+ kind: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('topLevelMessage'), z.literal('threadReply')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ messageId: z.string().uuid(),
+ threadId: z.string().uuid(),
+ }),
+ channelContext: z.object({
+ after: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ anchorOrParent: z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ }),
+ before: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ }),
+ omissions: z.array(
+ z.object({
+ count: z.union([z.number().int(), z.null()]).optional(),
+ cursor: z.union([z.string(), z.null()]).optional(),
+ kind: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('olderMessages'),
+ z.literal('newerMessages'),
+ z.literal('threadReplies'),
+ z.literal('truncatedContent'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ messageId: z.union([z.string().uuid(), z.null()]).optional(),
+ threadId: z.union([z.string().uuid(), z.null()]).optional(),
+ })
+ ),
+ threadContext: z
+ .union([
+ z.object({
+ anchorReply: z
+ .union([
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ }),
+ z.null(),
+ ])
+ .optional(),
+ omittedAfter: z.number().int().gte(0),
+ omittedBefore: z.number().int().gte(0),
+ parent: z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({
+ emoji: z.string(),
+ users: z.array(z.string()),
+ })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ }),
+ repliesAfter: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ repliesBefore: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ threadId: z.string().uuid(),
+ }),
+ z.null(),
+ ])
+ .optional(),
+});
+
+export const ReadChannelMessages = z.object({
+ channelId: z.string().uuid(),
+ cursor: z.union([z.string(), z.null()]).default(null),
+ direction: z.union([z.enum(['older', 'newer']), z.null()]).default(null),
+ from: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .default(null),
+ includeThreadPreviews: z.union([z.boolean(), z.null()]).default(null),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
+ maxCharsPerMessage: z
+ .union([z.number().int().gte(0), z.null()])
+ .default(null),
+ messageId: z.union([z.string().uuid(), z.null()]).default(null),
+ messageIds: z.array(z.string().uuid()).default([]),
+ to: z.union([z.string().datetime({ offset: true }), z.null()]).default(null),
+ windowType: z.enum([
+ 'latest',
+ 'timeRange',
+ 'aroundMessage',
+ 'page',
+ 'messages',
+ ]),
+});
+
+export const ReadChannelMessagesResponse = z.object({
+ channelId: z.string().uuid(),
+ messages: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ navigation: z.object({
+ hasMoreNewer: z.boolean(),
+ hasMoreOlder: z.boolean(),
+ newerCursor: z.union([z.string(), z.null()]).optional(),
+ olderCursor: z.union([z.string(), z.null()]).optional(),
+ }),
+ omissions: z.array(
+ z.object({
+ count: z.union([z.number().int(), z.null()]).optional(),
+ cursor: z.union([z.string(), z.null()]).optional(),
+ kind: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('olderMessages'),
+ z.literal('newerMessages'),
+ z.literal('threadReplies'),
+ z.literal('truncatedContent'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ messageId: z.union([z.string().uuid(), z.null()]).optional(),
+ threadId: z.union([z.string().uuid(), z.null()]).optional(),
+ })
+ ),
+ window: z.object({
+ direction: z.union([z.enum(['older', 'newer']), z.null()]).optional(),
+ from: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),
+ messageId: z.union([z.string().uuid(), z.null()]).optional(),
+ messageIds: z.array(z.string().uuid()),
+ to: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),
+ windowType: z.enum([
+ 'latest',
+ 'timeRange',
+ 'aroundMessage',
+ 'page',
+ 'messages',
+ ]),
+ }),
+});
+
+export const ReadChannelThread = z.object({
+ after: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
+ before: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
+ channelId: z.string().uuid(),
+ includeChannelContext: z.union([z.boolean(), z.null()]).default(null),
+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),
+ maxCharsPerMessage: z
+ .union([z.number().int().gte(0), z.null()])
+ .default(null),
+ messageId: z.string().uuid(),
+ replyId: z.union([z.string().uuid(), z.null()]).default(null),
+ windowType: z
+ .union([z.enum(['allIfSmall', 'latest', 'aroundReply']), z.null()])
+ .default(null),
+});
+
+export const ReadChannelThreadResponse = z.object({
+ anchor: z.object({
+ channelId: z.string().uuid(),
+ createdAt: z.string().datetime({ offset: true }),
+ kind: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('topLevelMessage'), z.literal('threadReply')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ messageId: z.string().uuid(),
+ threadId: z.string().uuid(),
+ }),
+ channelContext: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({
+ emoji: z.string(),
+ users: z.array(z.string()),
+ })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ omissions: z.array(
+ z.object({
+ count: z.union([z.number().int(), z.null()]).optional(),
+ cursor: z.union([z.string(), z.null()]).optional(),
+ kind: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('olderMessages'),
+ z.literal('newerMessages'),
+ z.literal('threadReplies'),
+ z.literal('truncatedContent'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ messageId: z.union([z.string().uuid(), z.null()]).optional(),
+ threadId: z.union([z.string().uuid(), z.null()]).optional(),
+ })
+ ),
+ replies: z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ thread: z.object({
+ channelId: z.string().uuid(),
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ parent: z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ channelId: z.string().uuid(),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ deletedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ thread: z.object({
+ latestReplyAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ omittedReplyCount: z.number().int(),
+ preview: z
+ .union([
+ z.array(
+ z.object({
+ attachments: z.array(
+ z.object({
+ createdAt: z.string().datetime({ offset: true }),
+ entityId: z.string(),
+ entityType: z.string(),
+ id: z.string().uuid(),
+ })
+ ),
+ content: z.string(),
+ contentTruncated: z.boolean(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ id: z.string().uuid(),
+ reactions: z.array(
+ z.object({ emoji: z.string(), users: z.array(z.string()) })
+ ),
+ senderId: z.string(),
+ threadId: z.string().uuid(),
+ updatedAt: z.string().datetime({ offset: true }),
+ })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ replyCount: z.number().int(),
+ threadId: z.string().uuid(),
+ }),
+ updatedAt: z.string().datetime({ offset: true }),
+ }),
+ replyCount: z.number().int().gte(0),
+ threadId: z.string().uuid(),
+ }),
+});
+
export const ReadChat = z.object({ chatId: z.string() });
export const ReadChatResponse = z.object({
@@ -1119,6 +1940,20 @@ export const TextEditorCodeExecutionResponse = z.object({
tool_use_id: z.string(),
});
+export const ReadThread = z.object({
+ contentType: z.enum([
+ 'channel',
+ 'channel-message',
+ 'chat-thread',
+ 'chat-message',
+ 'project',
+ ]),
+ ids: z.array(z.string()),
+ messagesSince: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .default(null),
+});
+
export const ReadResponse = z.object({
content: z.any().superRefine((x, ctx) => {
const schemas = [
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
index e6e8d3c475..7adae31046 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
@@ -23,7 +23,7 @@ type ToolParserMap = {
call: types.GetEntityProperties;
response: types.GetEntityPropertiesResponse;
};
- GetThread: { call: types.ReadThread; response: types.GetThreadResponse };
+ GetThread: { call: types.GetThread; response: types.GetThreadResponse };
ListCallRecords: {
call: types.ListCallRecords;
response: types.ListCallRecordsResponse;
@@ -37,6 +37,18 @@ type ToolParserMap = {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
};
+ ReadChannelMessageContext: {
+ call: types.ReadChannelMessageContext;
+ response: types.ReadChannelMessageContextResponse;
+ };
+ ReadChannelMessages: {
+ call: types.ReadChannelMessages;
+ response: types.ReadChannelMessagesResponse;
+ };
+ ReadChannelThread: {
+ call: types.ReadChannelThread;
+ response: types.ReadChannelThreadResponse;
+ };
ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadMetadata: {
@@ -82,7 +94,7 @@ const toolParserMap = {
call: schemas.GetEntityProperties,
response: schemas.GetEntityPropertiesResponse,
},
- GetThread: { call: schemas.ReadThread, response: schemas.GetThreadResponse },
+ GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },
ListCallRecords: {
call: schemas.ListCallRecords,
response: schemas.ListCallRecordsResponse,
@@ -99,6 +111,18 @@ const toolParserMap = {
call: schemas.ReadCallRecord,
response: schemas.ReadCallRecordResponse,
},
+ ReadChannelMessageContext: {
+ call: schemas.ReadChannelMessageContext,
+ response: schemas.ReadChannelMessageContextResponse,
+ },
+ ReadChannelMessages: {
+ call: schemas.ReadChannelMessages,
+ response: schemas.ReadChannelMessagesResponse,
+ },
+ ReadChannelThread: {
+ call: schemas.ReadChannelThread,
+ response: schemas.ReadChannelThreadResponse,
+ },
ReadChat: { call: schemas.ReadChat, response: schemas.ReadChatResponse },
ReadContent: {
call: schemas.ReadContent,
@@ -158,7 +182,7 @@ type ToolDataMap = {
call: types.GetEntityProperties;
response: types.GetEntityPropertiesResponse;
};
- GetThread: { call: types.ReadThread; response: types.GetThreadResponse };
+ GetThread: { call: types.GetThread; response: types.GetThreadResponse };
ListCallRecords: {
call: types.ListCallRecords;
response: types.ListCallRecordsResponse;
@@ -172,6 +196,18 @@ type ToolDataMap = {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
};
+ ReadChannelMessageContext: {
+ call: types.ReadChannelMessageContext;
+ response: types.ReadChannelMessageContextResponse;
+ };
+ ReadChannelMessages: {
+ call: types.ReadChannelMessages;
+ response: types.ReadChannelMessagesResponse;
+ };
+ ReadChannelThread: {
+ call: types.ReadChannelThread;
+ response: types.ReadChannelThreadResponse;
+ };
ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadMetadata: {
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 6134142b25..9eb87e2d94 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -33,6 +33,19 @@ export type CodeExecutionErrorCode =
| 'too_many_requests'
| 'file_not_found'
| 'string_not_found';
+/**
+ * Type of channel timeline window to read.
+ */
+export type ChannelMessagesWindowType =
+ | 'latest'
+ | 'timeRange'
+ | 'aroundMessage'
+ | 'page'
+ | 'messages';
+/**
+ * Which part of a thread to read.
+ */
+export type ChannelThreadWindowType = 'allIfSmall' | 'latest' | 'aroundReply';
/**
* The content of the document
*/
@@ -111,6 +124,22 @@ export type SortBy =
| 'recently_viewed'
| 'recently_updated'
| 'recently_created';
+/**
+ * Direction for reading more messages around a cursor.
+ */
+export type PageDirection = 'older' | 'newer';
+/**
+ * Position of a channel message.
+ */
+export type ToolMessageKind = 'topLevelMessage' | 'threadReply';
+/**
+ * Kind of content omitted from a bounded tool response.
+ */
+export type ToolOmissionKind =
+ | 'olderMessages'
+ | 'newerMessages'
+ | 'threadReplies'
+ | 'truncatedContent';
export type ReadThreadReadContent =
| {
channel_id: string;
@@ -985,6 +1014,19 @@ export interface ToolPropertyOption {
*/
id: string;
}
+/**
+ * Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation.
+ */
+export interface GetThread {
+ /**
+ * Maximum number of messages to return (default 10).
+ */
+ limit?: number | null;
+ /**
+ * The ID of the email thread to retrieve.
+ */
+ threadId: string;
+}
/**
* Response from the GetThread tool.
*/
@@ -1188,6 +1230,490 @@ export interface TranscriptSegment {
*/
startedAt: string;
}
+/**
+ * Read the local channel and thread context around one message id. If the id is a thread reply, this resolves the parent, returns nearby top-level channel messages, and returns nearby replies around the anchor reply.
+ */
+export interface ReadChannelMessageContext {
+ /**
+ * Approximate number of newer top-level messages to include. Defaults to 3.
+ */
+ channelAfter?: number | null;
+ /**
+ * Approximate number of older top-level messages to include. Defaults to 3.
+ */
+ channelBefore?: number | null;
+ /**
+ * Channel id containing the message.
+ */
+ channelId: string;
+ /**
+ * Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ */
+ maxCharsPerMessage?: number | null;
+ /**
+ * Message id to anchor the context. May be top-level or a thread reply.
+ */
+ messageId: string;
+ /**
+ * Number of replies after a reply anchor to include. Defaults to 10, maximum 50.
+ */
+ threadAfter?: number | null;
+ /**
+ * Number of replies before a reply anchor to include. Defaults to 10, maximum 50.
+ */
+ threadBefore?: number | null;
+}
+/**
+ * Response from `ReadChannelMessageContext`.
+ */
+export interface ReadChannelMessageContextResponse {
+ anchor: ToolResolvedMessage;
+ channelContext: ToolChannelMessageContextWindow;
+ /**
+ * Information about omitted or truncated content.
+ */
+ omissions: ToolOmission[];
+ /**
+ * Nearby thread replies when the requested message is a reply.
+ */
+ threadContext?: ToolThreadReplyContextWindow | null;
+}
+/**
+ * Resolution details for a requested message id.
+ */
+export interface ToolResolvedMessage {
+ /**
+ * Channel id.
+ */
+ channelId: string;
+ /**
+ * When the requested message was created.
+ */
+ createdAt: string;
+ kind: ToolMessageKind;
+ /**
+ * Requested message id.
+ */
+ messageId: string;
+ /**
+ * Parent thread id. Equals `message_id` for top-level messages.
+ */
+ threadId: string;
+}
+/**
+ * Top-level channel context around an anchor or thread parent.
+ */
+export interface ToolChannelMessageContextWindow {
+ /**
+ * Newer top-level messages after the anchor/parent, in chronological order.
+ */
+ after: ToolChannelMessage[];
+ anchorOrParent: ToolChannelMessage;
+ /**
+ * Older top-level messages before the anchor/parent, in chronological order.
+ */
+ before: ToolChannelMessage[];
+}
+/**
+ * A compact top-level channel message returned by channel AI tools.
+ */
+export interface ToolChannelMessage {
+ /**
+ * Attachments on this message.
+ */
+ attachments: ToolAttachment[];
+ /**
+ * Channel id.
+ */
+ channelId: string;
+ /**
+ * Message content, possibly truncated.
+ */
+ content: string;
+ /**
+ * Whether message content was truncated.
+ */
+ contentTruncated: boolean;
+ /**
+ * When the message was created.
+ */
+ createdAt: string;
+ /**
+ * When the message was deleted, if ever.
+ */
+ deletedAt?: string | null;
+ /**
+ * When the message was edited, if ever.
+ */
+ editedAt?: string | null;
+ /**
+ * Message id.
+ */
+ id: string;
+ /**
+ * Reactions on this message.
+ */
+ reactions: ToolReaction[];
+ /**
+ * Sender user id.
+ */
+ senderId: string;
+ thread: ToolThreadSummary;
+ /**
+ * When the message was last updated.
+ */
+ updatedAt: string;
+}
+/**
+ * A compact attachment reference on a message.
+ */
+export interface ToolAttachment {
+ /**
+ * When the attachment was created.
+ */
+ createdAt: string;
+ /**
+ * Attached entity id.
+ */
+ entityId: string;
+ /**
+ * Attached entity type.
+ */
+ entityType: string;
+ /**
+ * Attachment id.
+ */
+ id: string;
+}
+/**
+ * A reaction summary on a message.
+ */
+export interface ToolReaction {
+ /**
+ * Emoji that was reacted with.
+ */
+ emoji: string;
+ /**
+ * User ids that reacted with this emoji.
+ */
+ users: string[];
+}
+/**
+ * Thread metadata attached to a top-level message.
+ */
+export interface ToolThreadSummary {
+ /**
+ * Timestamp of the latest reply, if any.
+ */
+ latestReplyAt?: string | null;
+ /**
+ * Reply count not included in `preview`.
+ */
+ omittedReplyCount: number;
+ /**
+ * Preview replies, when requested.
+ */
+ preview?: ToolThreadReply[] | null;
+ /**
+ * Total number of replies in the thread.
+ */
+ replyCount: number;
+ /**
+ * Parent thread id. This equals the top-level message id.
+ */
+ threadId: string;
+}
+/**
+ * A compact thread reply returned by channel AI tools.
+ */
+export interface ToolThreadReply {
+ /**
+ * Attachments on this reply.
+ */
+ attachments: ToolAttachment[];
+ /**
+ * Reply content, possibly truncated.
+ */
+ content: string;
+ /**
+ * Whether the reply content was truncated.
+ */
+ contentTruncated: boolean;
+ /**
+ * When the reply was created.
+ */
+ createdAt: string;
+ /**
+ * When the reply was edited, if ever.
+ */
+ editedAt?: string | null;
+ /**
+ * Reply message id.
+ */
+ id: string;
+ /**
+ * Reactions on this reply.
+ */
+ reactions: ToolReaction[];
+ /**
+ * Sender user id.
+ */
+ senderId: string;
+ /**
+ * Parent thread id.
+ */
+ threadId: string;
+ /**
+ * When the reply was last updated.
+ */
+ updatedAt: string;
+}
+/**
+ * Information about content omitted from a tool response.
+ */
+export interface ToolOmission {
+ /**
+ * Number of omitted items, when known.
+ */
+ count?: number | null;
+ /**
+ * Cursor that can be used to continue reading, when available.
+ */
+ cursor?: string | null;
+ kind: ToolOmissionKind;
+ /**
+ * Message id associated with the omission, when applicable.
+ */
+ messageId?: string | null;
+ /**
+ * Thread id associated with the omission, when applicable.
+ */
+ threadId?: string | null;
+}
+/**
+ * Thread reply context around a reply anchor.
+ */
+export interface ToolThreadReplyContextWindow {
+ /**
+ * Anchor reply, when the requested message was a thread reply.
+ */
+ anchorReply?: ToolThreadReply | null;
+ /**
+ * Number of later replies omitted from this context window.
+ */
+ omittedAfter: number;
+ /**
+ * Number of earlier replies omitted from this context window.
+ */
+ omittedBefore: number;
+ parent: ToolChannelMessage;
+ /**
+ * Replies after the anchor reply, in chronological order.
+ */
+ repliesAfter: ToolThreadReply[];
+ /**
+ * Replies before the anchor reply, in chronological order.
+ */
+ repliesBefore: ToolThreadReply[];
+ /**
+ * Parent thread id.
+ */
+ threadId: string;
+}
+/**
+ * Read a small structured window of top-level messages from a channel. Use this for latest messages, bounded time ranges, cursor continuation, or a window around a message. For full thread replies, use ReadChannelThread.
+ */
+export interface ReadChannelMessages {
+ /**
+ * Channel id to read.
+ */
+ channelId: string;
+ /**
+ * Opaque cursor returned by this tool. Required when windowType is page.
+ */
+ cursor?: string | null;
+ /**
+ * Direction to read from the cursor. Required when windowType is page.
+ */
+ direction?: PageDirection | null;
+ /**
+ * Inclusive lower bound for activity timestamps. Required when windowType is timeRange.
+ */
+ from?: string | null;
+ /**
+ * Whether to include thread preview replies on returned top-level messages. Defaults to true.
+ */
+ includeThreadPreviews?: boolean | null;
+ /**
+ * Maximum number of top-level messages to return. Defaults to 25, maximum 100.
+ */
+ limit?: number | null;
+ /**
+ * Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ */
+ maxCharsPerMessage?: number | null;
+ /**
+ * Anchor message id. Required when windowType is aroundMessage.
+ */
+ messageId?: string | null;
+ /**
+ * Top-level message ids to read. Required when windowType is messages.
+ */
+ messageIds?: string[];
+ /**
+ * Exclusive upper bound for activity timestamps. Required when windowType is timeRange.
+ */
+ to?: string | null;
+ windowType: ChannelMessagesWindowType;
+}
+/**
+ * Response from `ReadChannelMessages`.
+ */
+export interface ReadChannelMessagesResponse {
+ /**
+ * Channel id that was read.
+ */
+ channelId: string;
+ /**
+ * Top-level channel messages in chronological order.
+ */
+ messages: ToolChannelMessage[];
+ navigation: ToolNavigation;
+ /**
+ * Information about omitted or truncated content.
+ */
+ omissions: ToolOmission[];
+ window: ResolvedChannelMessagesWindow;
+}
+/**
+ * Navigation cursors and continuation hints for a bounded result.
+ */
+export interface ToolNavigation {
+ /**
+ * Whether newer messages are known to exist.
+ */
+ hasMoreNewer: boolean;
+ /**
+ * Whether an older cursor was returned.
+ */
+ hasMoreOlder: boolean;
+ /**
+ * Cursor for reading newer items, if available.
+ */
+ newerCursor?: string | null;
+ /**
+ * Cursor for reading older items, if available.
+ */
+ olderCursor?: string | null;
+}
+/**
+ * Resolved window metadata echoed in the response.
+ */
+export interface ResolvedChannelMessagesWindow {
+ /**
+ * Cursor direction for page windows.
+ */
+ direction?: PageDirection | null;
+ /**
+ * Inclusive lower bound for activity timestamps, for time range windows.
+ */
+ from?: string | null;
+ /**
+ * Anchor message id for around-message windows.
+ */
+ messageId?: string | null;
+ /**
+ * Requested message ids for messages windows.
+ */
+ messageIds: string[];
+ /**
+ * Exclusive upper bound for activity timestamps, for time range windows.
+ */
+ to?: string | null;
+ windowType: ChannelMessagesWindowType;
+}
+/**
+ * Read replies from a channel message thread. The messageId may be either the top-level parent message id or any reply id in the thread. Use this after ReadChannelMessages or ContentSearch finds a relevant threaded discussion.
+ */
+export interface ReadChannelThread {
+ /**
+ * Number of replies after replyId for aroundReply windows. Defaults to 10, maximum 50.
+ */
+ after?: number | null;
+ /**
+ * Number of replies before replyId for aroundReply windows. Defaults to 10, maximum 50.
+ */
+ before?: number | null;
+ /**
+ * Channel id containing the thread.
+ */
+ channelId: string;
+ /**
+ * Whether to include nearby top-level channel messages around the parent. Defaults to false.
+ */
+ includeChannelContext?: boolean | null;
+ /**
+ * Maximum number of replies to return for latest/all-if-small windows. Defaults to 25, maximum 100.
+ */
+ limit?: number | null;
+ /**
+ * Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ */
+ maxCharsPerMessage?: number | null;
+ /**
+ * Parent message id or any reply id in the thread.
+ */
+ messageId: string;
+ /**
+ * Reply id to center around. Required when windowType is aroundReply.
+ */
+ replyId?: string | null;
+ /**
+ * Thread window to read: latest, allIfSmall, or aroundReply. Defaults to latest.
+ */
+ windowType?: ChannelThreadWindowType | null;
+}
+/**
+ * Metadata about the thread being read.
+ */
+export interface ReadChannelThreadInfo {
+ /**
+ * Channel id containing the thread.
+ */
+ channelId: string;
+ /**
+ * Timestamp of the latest reply, if any.
+ */
+ latestReplyAt?: string | null;
+ parent: ToolChannelMessage;
+ /**
+ * Total number of replies in this thread.
+ */
+ replyCount: number;
+ /**
+ * Thread id, equal to the top-level parent message id.
+ */
+ threadId: string;
+}
+/**
+ * Response from `ReadChannelThread`.
+ */
+export interface ReadChannelThreadResponse {
+ anchor: ToolResolvedMessage;
+ /**
+ * Nearby top-level channel messages around the parent, when requested.
+ */
+ channelContext?: ToolChannelMessage[] | null;
+ /**
+ * Information about omitted or truncated content.
+ */
+ omissions: ToolOmission[];
+ /**
+ * Replies returned for the requested window, in chronological order.
+ */
+ replies: ToolThreadReply[];
+ thread: ReadChannelThreadInfo;
+}
/**
* Retrieve a chat thread's message history by its ID. Returns the conversation title and messages with their roles, content, and attachment references.
*/
@@ -1330,19 +1856,6 @@ export interface ReadMetadataResponse {
export interface ReadResponse {
content: ReadThreadReadContent;
}
-/**
- * Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation.
- */
-export interface GetThread {
- /**
- * Maximum number of messages to return (default 10).
- */
- limit?: number | null;
- /**
- * The ID of the email thread to retrieve.
- */
- threadId: string;
-}
/**
* Read threaded content by ID(s). Supports reading channels, chats, and projects by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s). For documents, use ReadContent or ReadMetadata instead.
* Channel transcripts only include the latest 150 messages. Use 'messages_since' to see messages in a different time window.
@@ -1471,7 +1984,7 @@ export interface SetEntityPropertyResponse {
success: boolean;
}
/**
- * Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, and call tools. Use this for tasks that require multiple tool calls or independent research.
+ * Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, calls, and channel tools. Use this for tasks that require multiple tool calls or independent research.
*/
export interface Subagent {
/**
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageKind.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageKind.ts
new file mode 100644
index 0000000000..e80c3b4774
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageKind.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Position of a message in the channel/thread model.
+ */
+export type ApiChannelMessageKind =
+ (typeof ApiChannelMessageKind)[keyof typeof ApiChannelMessageKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ApiChannelMessageKind = {
+ topLevelMessage: 'topLevelMessage',
+ threadReply: 'threadReply',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiResolvedChannelMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiResolvedChannelMessage.ts
new file mode 100644
index 0000000000..699bd8d957
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiResolvedChannelMessage.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiChannelMessageKind } from './apiChannelMessageKind';
+
+/**
+ * Resolution metadata for any channel message id.
+ */
+export interface ApiResolvedChannelMessage {
+ /** Channel this message belongs to. */
+ channel_id: string;
+ /** When the requested message was created. */
+ created_at: string;
+ /** Whether the message is top-level or a thread reply. */
+ kind: ApiChannelMessageKind;
+ /** The requested message id. */
+ message_id: string;
+ /** The top-level parent/thread id. Equals message_id for top-level messages. */
+ thread_id: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
index 6de86c5d5e..f676e53bb4 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts
@@ -4,17 +4,30 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { ChannelMessageFiltersLastActivity } from './channelMessageFiltersLastActivity';
+import type { ChannelMessageFiltersActivityAfter } from './channelMessageFiltersActivityAfter';
+import type { ChannelMessageFiltersActivityBefore } from './channelMessageFiltersActivityBefore';
+import type { ChannelMessageFiltersCreatedAfter } from './channelMessageFiltersCreatedAfter';
+import type { ChannelMessageFiltersCreatedBefore } from './channelMessageFiltersCreatedBefore';
import type { NotificationFilters } from './notificationFilters';
/**
* Filters for channel message queries.
*/
export interface ChannelMessageFilters {
- /** When set, only return top-level messages that have activity after this
-timestamp. Activity means either the message itself was created after
-this time, or a thread reply was created after this time. */
- last_activity?: ChannelMessageFiltersLastActivity;
+ /** When set, only return top-level messages with channel activity at or after
+this timestamp. Activity means either the message itself was created after
+this time, or a thread reply was created after this time.
+
+Accepts the legacy JSON field `last_activity` for backwards compatibility. */
+ activity_after?: ChannelMessageFiltersActivityAfter;
+ /** When set, only return top-level messages with channel activity before this
+timestamp. Activity means either the parent message or at least one thread
+reply falls in the requested activity window. */
+ activity_before?: ChannelMessageFiltersActivityBefore;
+ /** When set, only return top-level messages created at or after this timestamp. */
+ created_after?: ChannelMessageFiltersCreatedAfter;
+ /** When set, only return top-level messages created before this timestamp. */
+ created_before?: ChannelMessageFiltersCreatedBefore;
/** When non-empty, only return messages with these IDs. */
message_ids?: string[];
/** When set, only return top-level messages where the message itself or
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityAfter.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityAfter.ts
new file mode 100644
index 0000000000..944d8ce376
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityAfter.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When set, only return top-level messages with channel activity at or after
+this timestamp. Activity means either the message itself was created after
+this time, or a thread reply was created after this time.
+
+Accepts the legacy JSON field `last_activity` for backwards compatibility.
+ */
+export type ChannelMessageFiltersActivityAfter = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityBefore.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityBefore.ts
new file mode 100644
index 0000000000..2acf482a92
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersActivityBefore.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When set, only return top-level messages with channel activity before this
+timestamp. Activity means either the parent message or at least one thread
+reply falls in the requested activity window.
+ */
+export type ChannelMessageFiltersActivityBefore = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedAfter.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedAfter.ts
new file mode 100644
index 0000000000..d03fdecd80
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedAfter.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When set, only return top-level messages created at or after this timestamp.
+ */
+export type ChannelMessageFiltersCreatedAfter = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedBefore.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedBefore.ts
new file mode 100644
index 0000000000..8d525e99b7
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersCreatedBefore.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When set, only return top-level messages created before this timestamp.
+ */
+export type ChannelMessageFiltersCreatedBefore = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersLastActivity.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersLastActivity.ts
deleted file mode 100644
index 01681d44ab..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFiltersLastActivity.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * When set, only return top-level messages that have activity after this
-timestamp. Activity means either the message itself was created after
-this time, or a thread reply was created after this time.
- */
-export type ChannelMessageFiltersLastActivity = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index c37e40e2f9..4c8e16e76e 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -47,6 +47,7 @@ export * from './apiChannelAttachmentWidth';
export * from './apiChannelMessage';
export * from './apiChannelMessageDeletedAt';
export * from './apiChannelMessageEditedAt';
+export * from './apiChannelMessageKind';
export * from './apiChannelMessagesPage';
export * from './apiChannelMessagesPageNextCursor';
export * from './apiChannelMessagesPagePreviousCursor';
@@ -56,6 +57,7 @@ export * from './apiMessageAttachment';
export * from './apiMessageAttachmentHeight';
export * from './apiMessageAttachmentWidth';
export * from './apiParticipantRole';
+export * from './apiResolvedChannelMessage';
export * from './apiThreadInfo';
export * from './apiThreadInfoLatestReplyAt';
export * from './apiThreadReply';
@@ -112,7 +114,10 @@ export * from './channelFiltersTeamId';
export * from './channelMessage';
export * from './channelMessageDeletedAt';
export * from './channelMessageFilters';
-export * from './channelMessageFiltersLastActivity';
+export * from './channelMessageFiltersActivityAfter';
+export * from './channelMessageFiltersActivityBefore';
+export * from './channelMessageFiltersCreatedAfter';
+export * from './channelMessageFiltersCreatedBefore';
export * from './channelMessageThreadId';
export * from './channelName';
export * from './channelOrgId';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 45b56d3cfb..835c2c47fa 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1468,11 +1468,29 @@ export const postChannelMessagesQueryParams = zod.object({
export const postChannelMessagesBody = zod
.object({
- last_activity: zod.iso
+ activity_after: zod.iso
.datetime({})
.nullish()
.describe(
- 'When set, only return top-level messages that have activity after this\ntimestamp. Activity means either the message itself was created after\nthis time, or a thread reply was created after this time.'
+ 'When set, only return top-level messages with channel activity at or after\nthis timestamp. Activity means either the message itself was created after\nthis time, or a thread reply was created after this time.\n\nAccepts the legacy JSON field `last_activity` for backwards compatibility.'
+ ),
+ activity_before: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When set, only return top-level messages with channel activity before this\ntimestamp. Activity means either the parent message or at least one thread\nreply falls in the requested activity window.'
+ ),
+ created_after: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When set, only return top-level messages created at or after this timestamp.'
+ ),
+ created_before: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When set, only return top-level messages created before this timestamp.'
),
message_ids: zod
.array(zod.uuid())
@@ -1694,6 +1712,32 @@ export const getThreadRepliesResponseItem = zod
.describe('A thread reply shown in preview.');
export const getThreadRepliesResponse = zod.array(getThreadRepliesResponseItem);
+/**
+ * @summary Handler for `GET /channels/{channel_id}/messages/{message_id}/resolve`.
+ */
+export const resolveChannelMessageParams = zod.object({
+ channel_id: zod.uuid().describe('Channel ID'),
+ message_id: zod.uuid().describe('Message ID to resolve'),
+});
+
+export const resolveChannelMessageResponse = zod
+ .object({
+ channel_id: zod.uuid().describe('Channel this message belongs to.'),
+ created_at: zod.iso
+ .datetime({})
+ .describe('When the requested message was created.'),
+ kind: zod
+ .enum(['topLevelMessage', 'threadReply'])
+ .describe('Position of a message in the channel\/thread model.'),
+ message_id: zod.uuid().describe('The requested message id.'),
+ thread_id: zod
+ .uuid()
+ .describe(
+ 'The top-level parent\/thread id. Equals message_id for top-level messages.'
+ ),
+ })
+ .describe('Resolution metadata for any channel message id.');
+
/**
* @summary Handler for `GET /channels/{channel_id}/participants`.
*/
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 765027b7c2..07edc2379c 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -1618,6 +1618,77 @@
}
}
},
+ "/channels/{channel_id}/messages/{message_id}/resolve": {
+ "get": {
+ "tags": ["channels::inbound::axum_router"],
+ "summary": "Handler for `GET /channels/{channel_id}/messages/{message_id}/resolve`.",
+ "operationId": "resolve_channel_message",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "description": "Channel ID",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "message_id",
+ "in": "path",
+ "description": "Message ID to resolve",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiResolvedChannelMessage"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/channels/{channel_id}/participants": {
"get": {
"tags": ["channels::inbound::axum_router"],
@@ -5950,6 +6021,11 @@
}
}
},
+ "ApiChannelMessageKind": {
+ "type": "string",
+ "description": "Position of a message in the channel/thread model.",
+ "enum": ["topLevelMessage", "threadReply"]
+ },
"ApiChannelMessagesPage": {
"type": "object",
"description": "Paginated response of channel messages.",
@@ -6055,6 +6131,43 @@
"description": "Participant role in a channel.",
"enum": ["owner", "admin", "member"]
},
+ "ApiResolvedChannelMessage": {
+ "type": "object",
+ "description": "Resolution metadata for any channel message id.",
+ "required": [
+ "message_id",
+ "channel_id",
+ "kind",
+ "thread_id",
+ "created_at"
+ ],
+ "properties": {
+ "channel_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Channel this message belongs to."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the requested message was created."
+ },
+ "kind": {
+ "$ref": "#/components/schemas/ApiChannelMessageKind",
+ "description": "Whether the message is top-level or a thread reply."
+ },
+ "message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The requested message id."
+ },
+ "thread_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The top-level parent/thread id. Equals message_id for top-level messages."
+ }
+ }
+ },
"ApiThreadInfo": {
"type": "object",
"description": "Thread metadata and preview replies.",
@@ -6709,10 +6822,25 @@
"type": "object",
"description": "Filters for channel message queries.",
"properties": {
- "last_activity": {
+ "activity_after": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When set, only return top-level messages with channel activity at or after\nthis timestamp. Activity means either the message itself was created after\nthis time, or a thread reply was created after this time.\n\nAccepts the legacy JSON field `last_activity` for backwards compatibility."
+ },
+ "activity_before": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When set, only return top-level messages with channel activity before this\ntimestamp. Activity means either the parent message or at least one thread\nreply falls in the requested activity window."
+ },
+ "created_after": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When set, only return top-level messages created at or after this timestamp."
+ },
+ "created_before": {
"type": ["string", "null"],
"format": "date-time",
- "description": "When set, only return top-level messages that have activity after this\ntimestamp. Activity means either the message itself was created after\nthis time, or a thread reply was created after this time."
+ "description": "When set, only return top-level messages created before this timestamp."
},
"message_ids": {
"type": "array",
diff --git a/js/lexical-service/bun.lock b/js/lexical-service/bun.lock
index c692b63129..25246bdc2b 100644
--- a/js/lexical-service/bun.lock
+++ b/js/lexical-service/bun.lock
@@ -18,11 +18,11 @@
"@lexical/selection": "0.32.1",
"@lexical/table": "0.32.1",
"@lexical/utils": "0.32.1",
- "chanfana": "^2.6.3",
+ "chanfana": "^3.3.0",
"hono": "^4.6.20",
"lexical": "0.32.1",
"nanoid": "^5.1.5",
- "zod": "^3.24.1",
+ "zod": "^4.3.6",
},
"devDependencies": {
"@types/bun": "^1.2.19",
@@ -34,7 +34,7 @@
},
},
"packages": {
- "@asteasolutions/zod-to-openapi": ["@asteasolutions/[email protected]", "", { "dependencies": { "openapi3-ts": "^4.1.2" }, "peerDependencies": { "zod": "^3.20.2" } }, "sha512-/2rThQ5zPi9OzVwes6U7lK1+Yvug0iXu25olp7S0XsYmOqnyMfxH7gdSQjn/+DSOHRg7wnotwGJSyL+fBKdnEA=="],
+ "@asteasolutions/zod-to-openapi": ["@asteasolutions/[email protected]", "", { "dependencies": { "openapi3-ts": "^4.1.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-SABbKiObg5dLRiTFnqiW1WWwGcg1BJfmHtT2asIBnBHg6Smy/Ms2KHc650+JI4Hw7lSkdiNebEGXpwoxfben8Q=="],
"@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", { "dependencies": { "mime": "^3.0.0" } }, "sha512-+tv3z+SPp+gqTIcImN9o0hqE9xyfQjI1XD9pL6NuKjua9B1y7mNYv0S9cP+QEbA4ppVgGZEmKOvHX5G5Ei1CVA=="],
@@ -208,7 +208,7 @@
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-uAOTaZSPuYsWIXRpj7o56Let0g/wjihKCkeRqUBhlLVM/Bt+Fj9xTo+LhC1OV1XDaGkz4hNC80et5xgy+9KTHQ=="],
- "chanfana": ["[email protected]", "", { "dependencies": { "@asteasolutions/zod-to-openapi": "^7.2.0", "js-yaml": "^4.1.0", "openapi3-ts": "^4.4.0", "yargs-parser": "^22.0.0", "zod": "^3.23.8" }, "bin": { "chanfana": "dist/cli.js" } }, "sha512-iYNlH+pA2yXAV5YksIe/Wewr0b935+jot+cTDqdkyFAae2QzJ2t1t2/ShEMtUjHc8RdDb7IvPCDjZgtMl3Py8A=="],
+ "chanfana": ["[email protected]", "", { "dependencies": { "@asteasolutions/zod-to-openapi": "^8.4.1", "js-yaml": "^4.1.1", "openapi3-ts": "^4.5.0", "yargs-parser": "^22.0.0", "zod": "^4.3.6" }, "bin": { "chanfana": "dist/cli.js" } }, "sha512-YKZkjymihSi9Wiwb4BbdMzXH7j9OxT4KS+5b9Y9ZUsj6Wthfodkw81cgoSEOMvgMTicCryohKhKZSIKCA6GFQA=="],
"color": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="],
@@ -244,7 +244,7 @@
"is-arrayish": ["[email protected]", "", {}, "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ=="],
- "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
@@ -304,7 +304,7 @@
"youch-core": ["[email protected]", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="],
- "zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
+ "zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
"miniflare/zod": ["[email protected]", "", {}, "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug=="],
diff --git a/rust/cloud-storage/.sqlx/query-bdc2a74951d6efbce08d469970b29610352e02441283f12a67b0da0c44771522.json b/rust/cloud-storage/.sqlx/query-bdc2a74951d6efbce08d469970b29610352e02441283f12a67b0da0c44771522.json
new file mode 100644
index 0000000000..5e8933ecc4
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-bdc2a74951d6efbce08d469970b29610352e02441283f12a67b0da0c44771522.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n AND ($6::timestamptz IS NULL OR m.created_at >= $6)\n AND ($7::timestamptz IS NULL OR m.created_at < $7)\n AND (\n ($8::timestamptz IS NULL AND $9::timestamptz IS NULL)\n OR (\n ($8::timestamptz IS NULL OR m.created_at >= $8)\n AND ($9::timestamptz IS NULL OR m.created_at < $9)\n )\n OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id\n AND r.deleted_at IS NULL\n AND ($8::timestamptz IS NULL OR r.created_at >= $8)\n AND ($9::timestamptz IS NULL OR r.created_at < $9)\n )\n )\n AND ($10::bool = FALSE OR (\n ($11::bool IS NULL OR EXISTS (\n SELECT 1\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE un.user_id = $13::text\n AND un.deleted_at IS NULL\n AND un.done = $11\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n AND COALESCE(msg.thread_id, msg.id) = m.id\n ))\n AND ($12::bool IS NULL OR EXISTS (\n SELECT 1\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE un.user_id = $13::text\n AND un.deleted_at IS NULL\n AND (un.seen_at IS NOT NULL) = $12\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n AND COALESCE(msg.thread_id, msg.id) = m.id\n ))\n ))\n ORDER BY m.created_at ASC, m.id ASC\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "UuidArray",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool",
+ "Bool",
+ "Bool",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "bdc2a74951d6efbce08d469970b29610352e02441283f12a67b0da0c44771522"
+}
diff --git a/rust/cloud-storage/.sqlx/query-da0e4cfc27ca84e3cad6ed3d7b58d20ea15ba8756bc54a8d518ea82a39a27ec4.json b/rust/cloud-storage/.sqlx/query-da0e4cfc27ca84e3cad6ed3d7b58d20ea15ba8756bc54a8d518ea82a39a27ec4.json
new file mode 100644
index 0000000000..12f733e69c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-da0e4cfc27ca84e3cad6ed3d7b58d20ea15ba8756bc54a8d518ea82a39a27ec4.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n thread_id AS \"thread_id!\",\n sender_id,\n content,\n created_at,\n updated_at,\n edited_at::timestamptz AS \"edited_at?\"\n FROM comms_messages\n WHERE thread_id = $1\n AND deleted_at IS NULL\n ORDER BY created_at ASC, id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "thread_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "da0e4cfc27ca84e3cad6ed3d7b58d20ea15ba8756bc54a8d518ea82a39a27ec4"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e6f63b89995a909f72c7c4012ab340e40f13453f1bec6cf41cb202930c44e84a.json b/rust/cloud-storage/.sqlx/query-e6f63b89995a909f72c7c4012ab340e40f13453f1bec6cf41cb202930c44e84a.json
new file mode 100644
index 0000000000..9c27aa5033
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e6f63b89995a909f72c7c4012ab340e40f13453f1bec6cf41cb202930c44e84a.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, channel_id, thread_id, created_at\n FROM comms_messages\n WHERE id = $1\n AND channel_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "e6f63b89995a909f72c7c4012ab340e40f13453f1bec6cf41cb202930c44e84a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ec9e817e0985ec4f58c8c6bc5817016f366e31f1ac3a8cf8696ed61434472afb.json b/rust/cloud-storage/.sqlx/query-ec9e817e0985ec4f58c8c6bc5817016f366e31f1ac3a8cf8696ed61434472afb.json
new file mode 100644
index 0000000000..579bd20b2e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ec9e817e0985ec4f58c8c6bc5817016f366e31f1ac3a8cf8696ed61434472afb.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n AND ($6::timestamptz IS NULL OR m.created_at >= $6)\n AND ($7::timestamptz IS NULL OR m.created_at < $7)\n AND (\n ($8::timestamptz IS NULL AND $9::timestamptz IS NULL)\n OR (\n ($8::timestamptz IS NULL OR m.created_at >= $8)\n AND ($9::timestamptz IS NULL OR m.created_at < $9)\n )\n OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id\n AND r.deleted_at IS NULL\n AND ($8::timestamptz IS NULL OR r.created_at >= $8)\n AND ($9::timestamptz IS NULL OR r.created_at < $9)\n )\n )\n AND ($10::bool = FALSE OR (\n ($11::bool IS NULL OR EXISTS (\n SELECT 1\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE un.user_id = $13::text\n AND un.deleted_at IS NULL\n AND un.done = $11\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n AND COALESCE(msg.thread_id, msg.id) = m.id\n ))\n AND ($12::bool IS NULL OR EXISTS (\n SELECT 1\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid\n WHERE un.user_id = $13::text\n AND un.deleted_at IS NULL\n AND (un.seen_at IS NOT NULL) = $12\n AND n.event_item_type = 'channel'\n AND n.event_item_id = $1::uuid::text\n AND n.metadata->>'messageId' IS NOT NULL\n AND msg.channel_id = $1\n AND msg.deleted_at IS NULL\n AND COALESCE(msg.thread_id, msg.id) = m.id\n ))\n ))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "UuidArray",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool",
+ "Bool",
+ "Bool",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "ec9e817e0985ec4f58c8c6bc5817016f366e31f1ac3a8cf8696ed61434472afb"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e7f0283681..c2dccc08bd 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -97,6 +97,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"call",
+ "channels",
"chat",
"chrono",
"comms",
@@ -1884,7 +1885,9 @@ dependencies = [
name = "channels"
version = "0.1.0"
dependencies = [
+ "ai",
"anyhow",
+ "async-trait",
"axum",
"chrono",
"entity_access",
@@ -1895,6 +1898,7 @@ dependencies = [
"model-error-response",
"model_user",
"models_pagination",
+ "schemars",
"serde",
"serde_json",
"sqlx",
@@ -6564,6 +6568,7 @@ dependencies = [
"ai_toolset",
"anyhow",
"axum",
+ "call",
"chrono",
"comms",
"document_storage_service_client",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index aa58f1110b..127d2883eb 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -18,6 +18,7 @@ axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
+channels = { path = "../channels", features = ["ai_tools", "outbound"] }
chrono.workspace = true
dateparser.workspace = true
comms = { path = "../comms", features = ["outbound"] }
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 57f3464c13..0ac08c96d6 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -179,6 +179,7 @@ pub async fn build_tool_service_context_from_env(
PgUserRepo::new(pool.clone()),
frecency_storage,
);
+ let channel_tool_context = crate::tool_context::build_channel_tool_context(pool.clone());
let email_service_for_tools: Arc<crate::tool_context::ToolEmailService> =
Arc::new(email_service.clone());
let soup_service = Arc::new(SoupImpl::new(
@@ -294,6 +295,7 @@ pub async fn build_tool_service_context_from_env(
email_tool_context,
call_tool_context,
chat_tool_context,
+ channel_tool_context,
schedule_tool_context: crate::NoOpScheduleContext,
})
}
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 7067ae98c5..ade2fda6a5 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -11,6 +11,7 @@ mod subagent;
mod tool_context;
use call::inbound::toolset::call_toolset;
+use channels::inbound::toolset::channel_toolset;
use chat::inbound::toolset::chat_toolset;
use documents::inbound::toolset::document_toolset;
use email::inbound::toolset::email_toolset;
@@ -54,6 +55,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
.add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
.add_subtoolset::<ToolCallToolContext>(call_toolset())
.add_subtoolset::<ToolChatToolContext>(chat_toolset())
+ .add_subtoolset::<ToolChannelToolContext>(channel_toolset())
}
/// These are actually sent to the AI provider
diff --git a/rust/cloud-storage/ai_tools/src/subagent.rs b/rust/cloud-storage/ai_tools/src/subagent.rs
index 2245f64186..5f17b8ae91 100644
--- a/rust/cloud-storage/ai_tools/src/subagent.rs
+++ b/rust/cloud-storage/ai_tools/src/subagent.rs
@@ -20,7 +20,7 @@ pub struct SubagentResponse {
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(
title = "Subagent",
- description = "Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, and call tools. Use this for tasks that require multiple tool calls or independent research."
+ description = "Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, calls, and channel tools. Use this for tasks that require multiple tool calls or independent research."
)]
pub struct Subagent {
#[schemars(
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 6be6ce95d7..7ec7f29d6d 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -5,6 +5,9 @@ use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};
use call::inbound::toolset::CallToolContext;
use call::outbound::pg_call_repo::PgCallRepo;
use call::outbound::s3_recording_storage::S3RecordingStorage;
+use channels::domain::service::ChannelMessagesServiceImpl;
+use channels::inbound::toolset::ChannelToolContext;
+use channels::outbound::pg_channels_repo::PgChannelMessagesRepo;
use chat::domain::service::ChatServiceImpl;
use chat::inbound::toolset::ChatToolContext;
use chat::outbound::postgres::PgChatRepo;
@@ -46,6 +49,23 @@ pub type ToolCommsService = comms::domain::service::ChannelServiceImpl<
frecency::outbound::postgres::FrecencyPgStorage,
>;
+/// Type alias for the channel messages service implementation used by AI tools.
+pub type ToolChannelMessagesService = ChannelMessagesServiceImpl<PgChannelMessagesRepo>;
+
+/// Type alias for the channel AI tool context.
+pub type ToolChannelToolContext =
+ ChannelToolContext<ToolChannelMessagesService, ToolEntityAccessService>;
+
+/// Build the channel AI tool context from a Postgres pool.
+pub fn build_channel_tool_context(pool: sqlx::PgPool) -> ToolChannelToolContext {
+ ChannelToolContext::new(
+ ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(pool.clone())),
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool),
+ ),
+ )
+}
+
/// No-op task properties service (not needed for AI tools)
#[derive(Clone)]
pub struct NoOpTaskProperties;
@@ -287,6 +307,7 @@ pub struct ToolServiceContext {
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
pub chat_tool_context: ToolChatToolContext,
+ pub channel_tool_context: ToolChannelToolContext,
pub schedule_tool_context: NoOpScheduleContext,
}
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index 6bc2369c6e..ab5b98e5d0 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -5,9 +5,18 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai",
+ "dep:async-trait",
+ "dep:entity_access",
+ "dep:schemars",
+ "entity_access/ports",
+ "ports",
+]
inbound = [
"dep:axum",
"dep:entity_access",
+ "entity_access/inbound",
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
@@ -21,7 +30,7 @@ ports = ["dep:tokio"]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
-entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["inbound"] }
+entity_access = { path = "../entity_access", optional = true, default-features = false }
model-error-response = { path = "../model-error-response", optional = true }
macro_user_id = { path = "../macro_user_id" }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
@@ -34,6 +43,11 @@ tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
+# AI Tool dependencies
+ai = { path = "../ai", optional = true }
+async-trait = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
+
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 456348cca2..a30361fb67 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -30,11 +30,24 @@ pub struct ChannelMessageFilters {
/// When non-empty, only return messages with these IDs.
#[serde(default)]
pub message_ids: Vec<Uuid>,
- /// When set, only return top-level messages that have activity after this
- /// timestamp. Activity means either the message itself was created after
+ /// When set, only return top-level messages created at or after this timestamp.
+ #[serde(default)]
+ pub created_after: Option<DateTime<Utc>>,
+ /// When set, only return top-level messages created before this timestamp.
+ #[serde(default)]
+ pub created_before: Option<DateTime<Utc>>,
+ /// When set, only return top-level messages with channel activity at or after
+ /// this timestamp. Activity means either the message itself was created after
/// this time, or a thread reply was created after this time.
+ ///
+ /// Accepts the legacy JSON field `last_activity` for backwards compatibility.
+ #[serde(default, alias = "last_activity")]
+ pub activity_after: Option<DateTime<Utc>>,
+ /// When set, only return top-level messages with channel activity before this
+ /// timestamp. Activity means either the parent message or at least one thread
+ /// reply falls in the requested activity window.
#[serde(default)]
- pub last_activity: Option<DateTime<Utc>>,
+ pub activity_before: Option<DateTime<Utc>>,
/// When set, only return top-level messages where the message itself or
/// any active thread reply has a notification for the requesting user that
/// matches these notification state constraints.
@@ -63,6 +76,30 @@ impl NotificationFilters {
}
}
+/// Where a channel message sits in the channel/thread model.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ChannelMessageKind {
+ /// A top-level message in the channel timeline.
+ TopLevelMessage,
+ /// A reply inside a top-level message's thread.
+ ThreadReply,
+}
+
+/// Resolution metadata for any channel message id.
+#[derive(Debug, Clone)]
+pub struct ResolvedChannelMessage {
+ /// The requested message id.
+ pub message_id: Uuid,
+ /// Channel this message belongs to.
+ pub channel_id: Uuid,
+ /// Whether the message is top-level or a thread reply.
+ pub kind: ChannelMessageKind,
+ /// The top-level parent/thread id. Equals `message_id` for top-level messages.
+ pub thread_id: Uuid,
+ /// When the requested message was created.
+ pub created_at: DateTime<Utc>,
+}
+
/// Direction for cursor-based message pagination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessagePageDirection {
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index aa70049be3..528e6cde59 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -1,7 +1,7 @@
use crate::domain::models::{
ChannelAttachment, ChannelAttachmentType, ChannelMessageFilters, ChannelParticipant,
- CountedReaction, MessageAttachment, MessagePageDirection, ThreadData, ThreadReply,
- ThreadReplyRow, TopLevelMessageRow,
+ CountedReaction, MessageAttachment, MessagePageDirection, ResolvedChannelMessage, ThreadData,
+ ThreadReply, ThreadReplyRow, TopLevelMessageRow,
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -76,6 +76,13 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
message_id: Uuid,
) -> impl Future<Output = Result<Option<TopLevelMessageRow>, Self::Err>> + Send;
+ /// Resolve a message id to top-level/thread-reply metadata.
+ fn resolve_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<Option<ResolvedChannelMessage>, Self::Err>> + Send;
+
/// Fetch top-level messages around an anchor, split into before (DESC) and after (ASC).
/// Each side is limited to `limit` rows for overfetch; trimming happens in the service.
fn get_top_level_messages_around(
@@ -136,6 +143,16 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
channel_id: Uuid,
message_id: Uuid,
) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send;
+
+ /// Resolve whether a message id is top-level or a thread reply.
+ fn resolve_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {
+ let _ = channel_id;
+ async move { Err(ChannelMessagesErr::MessageNotFound(message_id)) }
+ }
}
/// A paginated page of channel messages.
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 2fd853d5c2..c6a4a86dcf 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -1,7 +1,7 @@
use crate::domain::{
models::{
ChannelAttachmentType, ChannelMessage, ChannelMessageFilters, ChannelParticipant,
- MessagePageDirection, ThreadInfo, ThreadReply, TopLevelMessageRow,
+ MessagePageDirection, ResolvedChannelMessage, ThreadInfo, ThreadReply, TopLevelMessageRow,
},
ports::{
ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult,
@@ -357,4 +357,17 @@ where
Ok(replies)
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn resolve_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<ResolvedChannelMessage, ChannelMessagesErr> {
+ self.repo
+ .resolve_message(channel_id, message_id)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(ChannelMessagesErr::MessageNotFound(message_id))
+ }
}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index e08a08ce19..4a2970f62f 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -2,8 +2,9 @@
mod test;
use crate::domain::models::{
- ChannelAttachment, ChannelAttachmentType, ChannelMessage, ChannelParticipant, CountedReaction,
- MessageAttachment, MessagePageDirection, ParticipantRole, ThreadInfo, ThreadReply,
+ ChannelAttachment, ChannelAttachmentType, ChannelMessage, ChannelMessageKind,
+ ChannelParticipant, CountedReaction, MessageAttachment, MessagePageDirection, ParticipantRole,
+ ResolvedChannelMessage, ThreadInfo, ThreadReply,
};
pub use crate::domain::models::{ChannelMessageFilters, NotificationFilters};
use crate::domain::ports::{
@@ -170,6 +171,10 @@ where
"/{channel_id}/messages/{message_id}/replies",
get(get_thread_replies_handler::<S, Svc>),
)
+ .route(
+ "/{channel_id}/messages/{message_id}/resolve",
+ get(resolve_channel_message_handler::<S, Svc>),
+ )
.route(
"/{channel_id}/attachments",
get(get_channel_attachments_handler::<S, Svc>),
@@ -394,6 +399,49 @@ pub async fn get_thread_replies_handler<S: ChannelMessagesService, Svc: EntityAc
))
}
+/// Handler for `GET /channels/{channel_id}/messages/{message_id}/resolve`.
+#[utoipa::path(
+ get,
+ operation_id = "resolve_channel_message",
+ path = "/channels/{channel_id}/messages/{message_id}/resolve",
+ params(
+ ("channel_id" = Uuid, Path, description = "Channel ID"),
+ ("message_id" = Uuid, Path, description = "Message ID to resolve")
+ ),
+ responses(
+ (status = 200, body = ApiResolvedChannelMessage),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(
+ err,
+ skip_all,
+ fields(channel_id = tracing::field::Empty, message_id = tracing::field::Empty)
+)]
+pub async fn resolve_channel_message_handler<
+ S: ChannelMessagesService,
+ Svc: EntityAccessService,
+>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ _access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+ Path(path): Path<ThreadRepliesPath>,
+) -> Result<Json<ApiResolvedChannelMessage>, ChannelsHandlerErr> {
+ let channel_id = path.channel_id;
+ let message_id = path.message_id;
+ let span = tracing::Span::current();
+ span.record("channel_id", tracing::field::display(channel_id));
+ span.record("message_id", tracing::field::display(message_id));
+
+ let resolved = state
+ .service
+ .resolve_message(channel_id, message_id)
+ .await?;
+
+ Ok(Json(ApiResolvedChannelMessage::from(resolved)))
+}
+
/// Handler for `GET /channels/{channel_id}/attachments`.
#[utoipa::path(
get,
@@ -616,6 +664,52 @@ impl From<ThreadReply> for ApiThreadReply {
}
}
+/// Position of a message in the channel/thread model.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub enum ApiChannelMessageKind {
+ /// A top-level channel message.
+ TopLevelMessage,
+ /// A reply inside a message thread.
+ ThreadReply,
+}
+
+impl From<ChannelMessageKind> for ApiChannelMessageKind {
+ fn from(kind: ChannelMessageKind) -> Self {
+ match kind {
+ ChannelMessageKind::TopLevelMessage => Self::TopLevelMessage,
+ ChannelMessageKind::ThreadReply => Self::ThreadReply,
+ }
+ }
+}
+
+/// Resolution metadata for any channel message id.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+pub struct ApiResolvedChannelMessage {
+ /// The requested message id.
+ message_id: Uuid,
+ /// Channel this message belongs to.
+ channel_id: Uuid,
+ /// Whether the message is top-level or a thread reply.
+ kind: ApiChannelMessageKind,
+ /// The top-level parent/thread id. Equals message_id for top-level messages.
+ thread_id: Uuid,
+ /// When the requested message was created.
+ created_at: DateTime<Utc>,
+}
+
+impl From<ResolvedChannelMessage> for ApiResolvedChannelMessage {
+ fn from(message: ResolvedChannelMessage) -> Self {
+ Self {
+ message_id: message.message_id,
+ channel_id: message.channel_id,
+ kind: ApiChannelMessageKind::from(message.kind),
+ thread_id: message.thread_id,
+ created_at: message.created_at,
+ }
+ }
+}
+
/// A reaction with emoji and user list.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ApiCountedReaction {
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index a12ec93be9..9f356696d8 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -941,7 +941,7 @@ async fn post_messages_empty_body_uses_default_filters() {
let captured = svc.captured.lock().unwrap().clone().unwrap();
assert!(captured.message_ids.is_empty());
- assert!(captured.last_activity.is_none());
+ assert!(captured.activity_after.is_none());
assert!(captured.notification_filters.is_empty());
assert!(svc.captured_notification_user_id.lock().unwrap().is_none());
}
@@ -997,8 +997,8 @@ async fn post_messages_forwards_last_activity_filter() {
assert_eq!(res.status(), StatusCode::OK);
let captured = svc.captured.lock().unwrap().clone().unwrap();
- assert!(captured.last_activity.is_some());
- let ts = captured.last_activity.unwrap();
+ assert!(captured.activity_after.is_some());
+ let ts = captured.activity_after.unwrap();
assert_eq!(
ts,
chrono::DateTime::parse_from_rfc3339("2024-06-01T12:00:00Z")
diff --git a/rust/cloud-storage/channels/src/inbound/mod.rs b/rust/cloud-storage/channels/src/inbound/mod.rs
index 1191bba681..a58543c20a 100644
--- a/rust/cloud-storage/channels/src/inbound/mod.rs
+++ b/rust/cloud-storage/channels/src/inbound/mod.rs
@@ -1,2 +1,6 @@
/// Axum handler and router for channel messages.
+#[cfg(feature = "inbound")]
pub mod axum_router;
+/// AI toolset for reading channel messages and threads.
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/mod.rs b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..6415b35ae9
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
@@ -0,0 +1,111 @@
+//! AI tools for reading channel messages and threads.
+
+mod read_channel_message_context;
+mod read_channel_messages;
+mod read_channel_thread;
+mod types;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::ports::ChannelMessagesService;
+use ai::tool::{AsyncToolSet, RequestContext, ToolCallError};
+use entity_access::domain::{
+ models::{AccessError, AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use std::sync::Arc;
+use uuid::Uuid;
+
+pub use read_channel_message_context::{
+ ReadChannelMessageContext, ReadChannelMessageContextResponse,
+};
+pub use read_channel_messages::{ReadChannelMessages, ReadChannelMessagesResponse};
+pub use read_channel_thread::{ReadChannelThread, ReadChannelThreadResponse};
+
+/// Service context for channel AI tools.
+pub struct ChannelToolContext<Svc, AccessSvc>
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ /// Channel message service used to read timelines, resolve messages, and fetch threads.
+ pub service: Arc<Svc>,
+ /// Entity access service used to ensure the caller is a channel member.
+ pub entity_access_service: Arc<AccessSvc>,
+}
+
+impl<Svc, AccessSvc> Clone for ChannelToolContext<Svc, AccessSvc>
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ }
+ }
+}
+
+impl<Svc, AccessSvc> ChannelToolContext<Svc, AccessSvc>
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ /// Create a new channel tool context.
+ pub fn new(service: Svc, entity_access_service: AccessSvc) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access_service: Arc::new(entity_access_service),
+ }
+ }
+
+ /// Require that the request user is an active member of the channel before reading it.
+ pub async fn require_channel_member(
+ &self,
+ request_context: &RequestContext,
+ channel_id: Uuid,
+ ) -> Result<(), ToolCallError> {
+ self.entity_access_service
+ .check_access(
+ Some(&*request_context.user_id),
+ &channel_id.to_string(),
+ EntityType::Channel,
+ AccessLevel::View,
+ )
+ .await
+ .map(|_| ())
+ .map_err(channel_access_error)
+ }
+}
+
+fn channel_access_error(err: AccessError) -> ToolCallError {
+ let description = match err {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ "user is not a member of the requested channel"
+ }
+ AccessError::NotFound(_) => "channel not found",
+ AccessError::BadRequest(_) => "invalid channel id",
+ AccessError::DatabaseError(_) | AccessError::Internal => {
+ "failed to verify channel membership"
+ }
+ };
+
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: err.into(),
+ }
+}
+
+/// Create the channel AI toolset.
+pub fn channel_toolset<Svc, AccessSvc>() -> AsyncToolSet<ChannelToolContext<Svc, AccessSvc>>
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ AsyncToolSet::new()
+ .add_tool::<ReadChannelMessages, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<ReadChannelMessageContext, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<ReadChannelThread, ChannelToolContext<Svc, AccessSvc>>()
+}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs
new file mode 100644
index 0000000000..8c40a6cc36
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_message_context.rs
@@ -0,0 +1,309 @@
+//! Tool for reading context around a specific channel message.
+
+use super::ChannelToolContext;
+use super::types::{
+ ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage, ToolThreadReply,
+ clamp_max_chars, content_truncation_omissions,
+};
+use crate::domain::models::ChannelMessageKind;
+use crate::domain::ports::ChannelMessagesService;
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Top-level channel context around an anchor or thread parent.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolChannelMessageContextWindow {
+ /// Older top-level messages before the anchor/parent, in chronological order.
+ pub before: Vec<ToolChannelMessage>,
+ /// The requested top-level message, or the parent if the requested message is a reply.
+ pub anchor_or_parent: ToolChannelMessage,
+ /// Newer top-level messages after the anchor/parent, in chronological order.
+ pub after: Vec<ToolChannelMessage>,
+}
+
+/// Thread reply context around a reply anchor.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolThreadReplyContextWindow {
+ /// Parent thread id.
+ pub thread_id: Uuid,
+ /// Parent top-level message.
+ pub parent: ToolChannelMessage,
+ /// Replies before the anchor reply, in chronological order.
+ pub replies_before: Vec<ToolThreadReply>,
+ /// Anchor reply, when the requested message was a thread reply.
+ pub anchor_reply: Option<ToolThreadReply>,
+ /// Replies after the anchor reply, in chronological order.
+ pub replies_after: Vec<ToolThreadReply>,
+ /// Number of earlier replies omitted from this context window.
+ pub omitted_before: usize,
+ /// Number of later replies omitted from this context window.
+ pub omitted_after: usize,
+}
+
+/// Read local context around a specific channel message id.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadChannelMessageContext",
+ description = "Read the local channel and thread context around one message id. If the id is a thread reply, this resolves the parent, returns nearby top-level channel messages, and returns nearby replies around the anchor reply."
+)]
+pub struct ReadChannelMessageContext {
+ /// Channel id containing the message.
+ #[schemars(description = "Channel id containing the message.")]
+ pub channel_id: Uuid,
+ /// Message id to anchor the context. May be top-level or a thread reply.
+ #[schemars(
+ description = "Message id to anchor the context. May be top-level or a thread reply."
+ )]
+ pub message_id: Uuid,
+ /// Approximate number of older top-level messages to include. Defaults to 3.
+ #[schemars(
+ description = "Approximate number of older top-level messages to include. Defaults to 3."
+ )]
+ #[serde(default)]
+ pub channel_before: Option<u16>,
+ /// Approximate number of newer top-level messages to include. Defaults to 3.
+ #[schemars(
+ description = "Approximate number of newer top-level messages to include. Defaults to 3."
+ )]
+ #[serde(default)]
+ pub channel_after: Option<u16>,
+ /// Number of replies before a reply anchor to include. Defaults to 10, maximum 50.
+ #[schemars(
+ description = "Number of replies before a reply anchor to include. Defaults to 10, maximum 50."
+ )]
+ #[serde(default)]
+ pub thread_before: Option<u16>,
+ /// Number of replies after a reply anchor to include. Defaults to 10, maximum 50.
+ #[schemars(
+ description = "Number of replies after a reply anchor to include. Defaults to 10, maximum 50."
+ )]
+ #[serde(default)]
+ pub thread_after: Option<u16>,
+ /// Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ #[schemars(
+ description = "Maximum characters to return per message/reply. Defaults to 4000, maximum 16000."
+ )]
+ #[serde(default)]
+ pub max_chars_per_message: Option<usize>,
+}
+
+/// Response from `ReadChannelMessageContext`.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadChannelMessageContextResponse {
+ /// Resolution metadata for the requested message id.
+ pub anchor: ToolResolvedMessage,
+ /// Nearby top-level channel messages around the anchor or parent.
+ pub channel_context: ToolChannelMessageContextWindow,
+ /// Nearby thread replies when the requested message is a reply.
+ pub thread_context: Option<ToolThreadReplyContextWindow>,
+ /// Information about omitted or truncated content.
+ pub omissions: Vec<ToolOmission>,
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelMessageContext
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ReadChannelMessageContextResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ service_context
+ .require_channel_member(&request_context, self.channel_id)
+ .await?;
+
+ let max_chars_per_message = clamp_max_chars(self.max_chars_per_message);
+ let channel_before = self.channel_before.unwrap_or(3).min(25);
+ let channel_after = self.channel_after.unwrap_or(3).min(25);
+ let channel_limit = channel_before
+ .saturating_add(channel_after)
+ .saturating_add(1);
+
+ let resolved = service_context
+ .service
+ .resolve_message(self.channel_id, self.message_id)
+ .await
+ .map_err(tool_err("failed to resolve channel message"))?;
+ let anchor = ToolResolvedMessage::from(resolved.clone());
+
+ let mut channel_page = service_context
+ .service
+ .get_channel_messages_around(self.channel_id, resolved.thread_id, channel_limit)
+ .await
+ .map_err(tool_err("failed to read channel context around message"))?
+ .page;
+ channel_page.items.reverse();
+ let channel_messages: Vec<ToolChannelMessage> = channel_page
+ .items
+ .into_iter()
+ .map(|message| ToolChannelMessage::from_message(message, true, max_chars_per_message))
+ .collect();
+
+ let parent_index = channel_messages
+ .iter()
+ .position(|message| message.id == resolved.thread_id)
+ .ok_or_else(|| ToolCallError {
+ description: "message parent was not returned in channel context".to_string(),
+ internal_error: anyhow::anyhow!("channel context missing parent"),
+ })?;
+ let before = channel_messages[..parent_index].to_vec();
+ let anchor_or_parent = channel_messages[parent_index].clone();
+ let after = channel_messages[parent_index + 1..].to_vec();
+ let channel_context = ToolChannelMessageContextWindow {
+ before,
+ anchor_or_parent: anchor_or_parent.clone(),
+ after,
+ };
+
+ let thread_context = match resolved.kind {
+ ChannelMessageKind::TopLevelMessage => None,
+ ChannelMessageKind::ThreadReply => Some(
+ read_reply_context(
+ &*service_context.service,
+ ReplyContextArgs {
+ channel_id: self.channel_id,
+ reply_id: self.message_id,
+ thread_id: resolved.thread_id,
+ parent: anchor_or_parent,
+ before: self.thread_before,
+ after: self.thread_after,
+ max_chars_per_message,
+ },
+ )
+ .await?,
+ ),
+ };
+
+ let channel_context_messages = flatten_channel_context(&channel_context);
+ let thread_context_replies = thread_context
+ .as_ref()
+ .map(flatten_thread_context)
+ .unwrap_or_default();
+ let mut omissions =
+ content_truncation_omissions(&channel_context_messages, &thread_context_replies);
+ if let Some(thread_context) = &thread_context {
+ if thread_context.omitted_before > 0 {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::ThreadReplies,
+ message_id: None,
+ thread_id: Some(thread_context.thread_id),
+ count: Some(thread_context.omitted_before as i64),
+ cursor: None,
+ });
+ }
+ if thread_context.omitted_after > 0 {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::ThreadReplies,
+ message_id: None,
+ thread_id: Some(thread_context.thread_id),
+ count: Some(thread_context.omitted_after as i64),
+ cursor: None,
+ });
+ }
+ }
+
+ Ok(ReadChannelMessageContextResponse {
+ anchor,
+ channel_context,
+ thread_context,
+ omissions,
+ })
+ }
+}
+
+struct ReplyContextArgs {
+ channel_id: Uuid,
+ reply_id: Uuid,
+ thread_id: Uuid,
+ parent: ToolChannelMessage,
+ before: Option<u16>,
+ after: Option<u16>,
+ max_chars_per_message: usize,
+}
+
+async fn read_reply_context<Svc>(
+ service: &Svc,
+ args: ReplyContextArgs,
+) -> Result<ToolThreadReplyContextWindow, ToolCallError>
+where
+ Svc: ChannelMessagesService,
+{
+ let before = usize::from(args.before.unwrap_or(10).min(50));
+ let after = usize::from(args.after.unwrap_or(10).min(50));
+ let replies = service
+ .get_thread_replies(args.channel_id, args.reply_id)
+ .await
+ .map_err(tool_err("failed to read thread replies around message"))?;
+ let total = replies.len();
+ let anchor_index = replies
+ .iter()
+ .position(|reply| reply.id == args.reply_id)
+ .ok_or_else(|| ToolCallError {
+ description: "message_id was resolved as a reply, but was not found in thread replies"
+ .to_string(),
+ internal_error: anyhow::anyhow!("resolved reply not found in thread replies"),
+ })?;
+ let start = anchor_index.saturating_sub(before);
+ let end = (anchor_index + after + 1).min(total);
+ let omitted_after = total.saturating_sub(end);
+
+ let mut mapped: Vec<ToolThreadReply> = replies
+ .into_iter()
+ .skip(start)
+ .take(end - start)
+ .map(|reply| ToolThreadReply::from_reply(reply, args.thread_id, args.max_chars_per_message))
+ .collect();
+ let anchor_offset = anchor_index - start;
+ let replies_after = mapped.split_off(anchor_offset + 1);
+ let anchor_reply = mapped.pop();
+ let replies_before = mapped;
+
+ Ok(ToolThreadReplyContextWindow {
+ thread_id: args.thread_id,
+ parent: args.parent,
+ replies_before,
+ anchor_reply,
+ replies_after,
+ omitted_before: start,
+ omitted_after,
+ })
+}
+
+fn flatten_channel_context(context: &ToolChannelMessageContextWindow) -> Vec<ToolChannelMessage> {
+ let mut messages = context.before.clone();
+ messages.push(context.anchor_or_parent.clone());
+ messages.extend(context.after.clone());
+ messages
+}
+
+fn flatten_thread_context(context: &ToolThreadReplyContextWindow) -> Vec<ToolThreadReply> {
+ let mut replies = context.replies_before.clone();
+ if let Some(anchor) = &context.anchor_reply {
+ replies.push(anchor.clone());
+ }
+ replies.extend(context.replies_after.clone());
+ replies
+}
+
+fn tool_err(
+ description: &'static str,
+) -> impl FnOnce(crate::domain::ports::ChannelMessagesErr) -> ToolCallError {
+ move |err| ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::Error::new(err),
+ }
+}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs
new file mode 100644
index 0000000000..035815ea62
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_messages.rs
@@ -0,0 +1,561 @@
+//! Tool for reading bounded channel timeline windows.
+
+use super::ChannelToolContext;
+use super::types::{
+ PageDirection, ToolChannelMessage, ToolNavigation, ToolOmission, ToolOmissionKind, clamp_limit,
+ clamp_max_chars, content_truncation_omissions,
+};
+use crate::domain::models::{ChannelMessageFilters, MessagePageDirection};
+use crate::domain::ports::{ChannelMessagesQueryResult, ChannelMessagesService};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use entity_access::domain::ports::EntityAccessService;
+use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, CursorWithValAndFilter, Query};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ChannelMessagesCursorFilter {
+ #[serde(default)]
+ message_ids: Vec<Uuid>,
+ #[serde(default)]
+ created_after: Option<DateTime<Utc>>,
+ #[serde(default)]
+ created_before: Option<DateTime<Utc>>,
+ #[serde(default)]
+ activity_after: Option<DateTime<Utc>>,
+ #[serde(default)]
+ activity_before: Option<DateTime<Utc>>,
+}
+
+impl ChannelMessagesCursorFilter {
+ fn to_channel_message_filters(&self) -> ChannelMessageFilters {
+ ChannelMessageFilters {
+ message_ids: self.message_ids.clone(),
+ created_after: self.created_after,
+ created_before: self.created_before,
+ activity_after: self.activity_after,
+ activity_before: self.activity_before,
+ ..Default::default()
+ }
+ }
+}
+
+/// Type of channel timeline window to read.
+#[allow(missing_docs)]
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ChannelMessagesWindowType {
+ Latest,
+ TimeRange,
+ AroundMessage,
+ Page,
+ Messages,
+}
+
+/// Resolved window metadata echoed in the response.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ResolvedChannelMessagesWindow {
+ /// Window type that was read.
+ pub window_type: ChannelMessagesWindowType,
+ /// Inclusive lower bound for activity timestamps, for time range windows.
+ pub from: Option<DateTime<Utc>>,
+ /// Exclusive upper bound for activity timestamps, for time range windows.
+ pub to: Option<DateTime<Utc>>,
+ /// Anchor message id for around-message windows.
+ pub message_id: Option<Uuid>,
+ /// Cursor direction for page windows.
+ pub direction: Option<PageDirection>,
+ /// Requested message ids for messages windows.
+ pub message_ids: Vec<Uuid>,
+}
+
+/// Read a bounded, structured window of top-level channel messages.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadChannelMessages",
+ description = "Read a small structured window of top-level messages from a channel. Use this for latest messages, bounded time ranges, cursor continuation, or a window around a message. For full thread replies, use ReadChannelThread."
+)]
+pub struct ReadChannelMessages {
+ /// Channel id to read.
+ #[schemars(description = "Channel id to read.")]
+ pub channel_id: Uuid,
+ /// Which channel window to read.
+ #[schemars(
+ description = "Which bounded channel window to read: latest, timeRange, aroundMessage, page, or messages."
+ )]
+ pub window_type: ChannelMessagesWindowType,
+ /// Inclusive lower bound for activity timestamps. Required when windowType is timeRange.
+ #[schemars(
+ description = "Inclusive lower bound for activity timestamps. Required when windowType is timeRange."
+ )]
+ #[serde(default)]
+ pub from: Option<DateTime<Utc>>,
+ /// Exclusive upper bound for activity timestamps. Required when windowType is timeRange.
+ #[schemars(
+ description = "Exclusive upper bound for activity timestamps. Required when windowType is timeRange."
+ )]
+ #[serde(default)]
+ pub to: Option<DateTime<Utc>>,
+ /// Anchor message id. Required when windowType is aroundMessage.
+ #[schemars(description = "Anchor message id. Required when windowType is aroundMessage.")]
+ #[serde(default)]
+ pub message_id: Option<Uuid>,
+ /// Opaque cursor returned by this tool. Required when windowType is page.
+ #[schemars(
+ description = "Opaque cursor returned by this tool. Required when windowType is page."
+ )]
+ #[serde(default)]
+ pub cursor: Option<String>,
+ /// Direction to read from the cursor. Required when windowType is page.
+ #[schemars(
+ description = "Direction to read from the cursor. Required when windowType is page."
+ )]
+ #[serde(default)]
+ pub direction: Option<PageDirection>,
+ /// Top-level message ids to read. Required when windowType is messages.
+ #[schemars(
+ description = "Top-level message ids to read. Required when windowType is messages."
+ )]
+ #[serde(default)]
+ pub message_ids: Vec<Uuid>,
+ /// Maximum number of top-level messages to return. Defaults to 25, maximum 100.
+ #[schemars(
+ description = "Maximum number of top-level messages to return. Defaults to 25, maximum 100."
+ )]
+ #[serde(default)]
+ pub limit: Option<u16>,
+ /// Whether to include thread preview replies on returned top-level messages. Defaults to true.
+ #[schemars(
+ description = "Whether to include thread preview replies on returned top-level messages. Defaults to true."
+ )]
+ #[serde(default)]
+ pub include_thread_previews: Option<bool>,
+ /// Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ #[schemars(
+ description = "Maximum characters to return per message/reply. Defaults to 4000, maximum 16000."
+ )]
+ #[serde(default)]
+ pub max_chars_per_message: Option<usize>,
+}
+
+/// Response from `ReadChannelMessages`.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadChannelMessagesResponse {
+ /// Channel id that was read.
+ pub channel_id: Uuid,
+ /// Resolved window metadata.
+ pub window: ResolvedChannelMessagesWindow,
+ /// Top-level channel messages in chronological order.
+ pub messages: Vec<ToolChannelMessage>,
+ /// Continuation cursors and paging hints.
+ pub navigation: ToolNavigation,
+ /// Information about omitted or truncated content.
+ pub omissions: Vec<ToolOmission>,
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelMessages
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ReadChannelMessagesResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ service_context
+ .require_channel_member(&request_context, self.channel_id)
+ .await?;
+
+ let limit = clamp_limit(self.limit);
+ let max_chars_per_message = clamp_max_chars(self.max_chars_per_message);
+ let include_thread_preview = self.include_thread_previews.unwrap_or(true);
+
+ let (page, has_more_newer, resolved_window, cursor_filter) = match self.window_type {
+ ChannelMessagesWindowType::Latest => {
+ let cursor_filter = ChannelMessagesCursorFilter::default();
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = service_context
+ .service
+ .get_channel_messages(
+ self.channel_id,
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ limit,
+ &cursor_filter.to_channel_message_filters(),
+ None,
+ )
+ .await
+ .map_err(tool_err("failed to read latest channel messages"))?;
+ (
+ page,
+ has_more_newer,
+ resolved_window(ChannelMessagesWindowType::Latest, self),
+ cursor_filter,
+ )
+ }
+ ChannelMessagesWindowType::TimeRange => {
+ let from = self.from.ok_or_else(|| ToolCallError {
+ description: "from is required when windowType is timeRange".to_string(),
+ internal_error: anyhow::anyhow!("missing time range from"),
+ })?;
+ let to = self.to.ok_or_else(|| ToolCallError {
+ description: "to is required when windowType is timeRange".to_string(),
+ internal_error: anyhow::anyhow!("missing time range to"),
+ })?;
+ if from >= to {
+ return Err(ToolCallError {
+ description: "time range `from` must be before `to`".to_string(),
+ internal_error: anyhow::anyhow!("invalid channel message time range"),
+ });
+ }
+ let cursor_filter = ChannelMessagesCursorFilter {
+ activity_after: Some(from),
+ activity_before: Some(to),
+ ..Default::default()
+ };
+ let filters = cursor_filter.to_channel_message_filters();
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = service_context
+ .service
+ .get_channel_messages(
+ self.channel_id,
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ limit,
+ &filters,
+ None,
+ )
+ .await
+ .map_err(tool_err("failed to read channel messages in time range"))?;
+ (
+ page,
+ has_more_newer,
+ resolved_window(ChannelMessagesWindowType::TimeRange, self),
+ cursor_filter,
+ )
+ }
+ ChannelMessagesWindowType::AroundMessage => {
+ let cursor_filter = ChannelMessagesCursorFilter::default();
+ let message_id = self.message_id.ok_or_else(|| ToolCallError {
+ description: "messageId is required when windowType is aroundMessage"
+ .to_string(),
+ internal_error: anyhow::anyhow!("missing around-message id"),
+ })?;
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = service_context
+ .service
+ .get_channel_messages_around(self.channel_id, message_id, limit)
+ .await
+ .map_err(tool_err("failed to read channel messages around message"))?;
+ (
+ page,
+ has_more_newer,
+ resolved_window(ChannelMessagesWindowType::AroundMessage, self),
+ cursor_filter,
+ )
+ }
+ ChannelMessagesWindowType::Page => {
+ let cursor = self.cursor.as_deref().ok_or_else(|| ToolCallError {
+ description: "cursor is required when windowType is page".to_string(),
+ internal_error: anyhow::anyhow!("missing channel cursor"),
+ })?;
+ let direction = self.direction.ok_or_else(|| ToolCallError {
+ description: "direction is required when windowType is page".to_string(),
+ internal_error: anyhow::anyhow!("missing channel cursor direction"),
+ })?;
+ let cursor = decode_channel_cursor(cursor)?;
+ let cursor_filter = cursor.filter.clone();
+ let filters = cursor_filter.to_channel_message_filters();
+ let direction_for_service = match direction {
+ PageDirection::Older => MessagePageDirection::Older,
+ PageDirection::Newer => MessagePageDirection::Newer,
+ };
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = service_context
+ .service
+ .get_channel_messages(
+ self.channel_id,
+ Query::Cursor(cursor.map_filter(|_| ())),
+ direction_for_service,
+ limit,
+ &filters,
+ None,
+ )
+ .await
+ .map_err(tool_err("failed to read channel message page"))?;
+ let resolved_window = ResolvedChannelMessagesWindow {
+ window_type: ChannelMessagesWindowType::Page,
+ from: cursor_filter.activity_after,
+ to: cursor_filter.activity_before,
+ message_id: self.message_id,
+ direction: self.direction,
+ message_ids: cursor_filter.message_ids.clone(),
+ };
+ (page, has_more_newer, resolved_window, cursor_filter)
+ }
+ ChannelMessagesWindowType::Messages => {
+ if self.message_ids.is_empty() {
+ return Err(ToolCallError {
+ description: "message_ids must not be empty".to_string(),
+ internal_error: anyhow::anyhow!("empty channel message id list"),
+ });
+ }
+ let cursor_filter = ChannelMessagesCursorFilter {
+ message_ids: self.message_ids.clone(),
+ ..Default::default()
+ };
+ let filters = cursor_filter.to_channel_message_filters();
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = service_context
+ .service
+ .get_channel_messages(
+ self.channel_id,
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ limit,
+ &filters,
+ None,
+ )
+ .await
+ .map_err(tool_err("failed to read requested channel messages"))?;
+ (
+ page,
+ has_more_newer,
+ resolved_window(ChannelMessagesWindowType::Messages, self),
+ cursor_filter,
+ )
+ }
+ };
+
+ let service_has_more_older = page.next_cursor.is_some();
+ let mut raw_messages = page.items;
+ raw_messages.reverse();
+ let messages: Vec<ToolChannelMessage> = raw_messages
+ .into_iter()
+ .map(|message| {
+ ToolChannelMessage::from_message(
+ message,
+ include_thread_preview,
+ max_chars_per_message,
+ )
+ })
+ .collect();
+
+ let has_more_older = match self.window_type {
+ ChannelMessagesWindowType::Messages => false,
+ ChannelMessagesWindowType::Page if self.direction == Some(PageDirection::Newer) => {
+ !messages.is_empty()
+ }
+ _ => service_has_more_older,
+ };
+ let older_cursor = has_more_older
+ .then(|| cursor_from_oldest_message(&messages, limit, cursor_filter.clone()))
+ .flatten();
+
+ let has_more_newer = match self.window_type {
+ ChannelMessagesWindowType::Latest
+ | ChannelMessagesWindowType::Messages
+ | ChannelMessagesWindowType::AroundMessage => false,
+ _ => has_more_newer,
+ };
+ let can_read_newer =
+ has_more_newer || matches!(self.window_type, ChannelMessagesWindowType::AroundMessage);
+ let newer_cursor = can_read_newer
+ .then(|| cursor_from_newest_message(&messages, limit, cursor_filter.clone()))
+ .flatten();
+
+ let mut omissions = Vec::new();
+ if let Some(cursor) = older_cursor.clone() {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::OlderMessages,
+ message_id: None,
+ thread_id: None,
+ count: None,
+ cursor: Some(cursor),
+ });
+ }
+ if has_more_newer {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::NewerMessages,
+ message_id: None,
+ thread_id: None,
+ count: None,
+ cursor: newer_cursor.clone(),
+ });
+ }
+ for message in &messages {
+ if message.thread.omitted_reply_count > 0 {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::ThreadReplies,
+ message_id: Some(message.id),
+ thread_id: Some(message.thread.thread_id),
+ count: Some(message.thread.omitted_reply_count),
+ cursor: None,
+ });
+ }
+ }
+ omissions.extend(content_truncation_omissions(&messages, &[]));
+
+ Ok(ReadChannelMessagesResponse {
+ channel_id: self.channel_id,
+ window: resolved_window,
+ messages,
+ navigation: ToolNavigation {
+ has_more_older,
+ has_more_newer,
+ older_cursor,
+ newer_cursor,
+ },
+ omissions,
+ })
+ }
+}
+
+fn resolved_window(
+ window_type: ChannelMessagesWindowType,
+ tool: &ReadChannelMessages,
+) -> ResolvedChannelMessagesWindow {
+ ResolvedChannelMessagesWindow {
+ window_type,
+ from: tool.from,
+ to: tool.to,
+ message_id: tool.message_id,
+ direction: tool.direction,
+ message_ids: tool.message_ids.clone(),
+ }
+}
+
+fn decode_channel_cursor(
+ cursor: &str,
+) -> Result<CursorWithValAndFilter<Uuid, CreatedAt, ChannelMessagesCursorFilter>, ToolCallError> {
+ Base64Str::new_from_string(cursor.to_string())
+ .decode_json()
+ .map_err(|err| ToolCallError {
+ description: "invalid channel cursor".to_string(),
+ internal_error: anyhow::anyhow!("invalid channel cursor: {err:?}"),
+ })
+}
+
+fn cursor_from_oldest_message(
+ messages: &[ToolChannelMessage],
+ limit: u16,
+ filter: ChannelMessagesCursorFilter,
+) -> Option<String> {
+ messages
+ .first()
+ .map(|message| cursor_from_message(message, limit, filter))
+}
+
+fn cursor_from_newest_message(
+ messages: &[ToolChannelMessage],
+ limit: u16,
+ filter: ChannelMessagesCursorFilter,
+) -> Option<String> {
+ messages
+ .last()
+ .map(|message| cursor_from_message(message, limit, filter))
+}
+
+fn cursor_from_message(
+ message: &ToolChannelMessage,
+ limit: u16,
+ filter: ChannelMessagesCursorFilter,
+) -> String {
+ Base64Str::encode_json(Cursor {
+ id: message.id,
+ limit: usize::from(limit),
+ val: CursorVal {
+ sort_type: CreatedAt,
+ last_val: message.created_at,
+ },
+ filter,
+ })
+ .type_erase()
+}
+
+fn tool_err(
+ description: &'static str,
+) -> impl FnOnce(crate::domain::ports::ChannelMessagesErr) -> ToolCallError {
+ move |err| ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::Error::new(err),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::inbound::toolset::types::ToolThreadSummary;
+
+ fn dt(seconds: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp(seconds, 0).unwrap()
+ }
+
+ fn message(id: Uuid, created_at: DateTime<Utc>) -> ToolChannelMessage {
+ ToolChannelMessage {
+ id,
+ channel_id: Uuid::new_v4(),
+ sender_id: "macro|[email protected]".to_string(),
+ content: "hello".to_string(),
+ content_truncated: false,
+ created_at,
+ updated_at: created_at,
+ edited_at: None,
+ deleted_at: None,
+ thread: ToolThreadSummary {
+ thread_id: id,
+ reply_count: 0,
+ latest_reply_at: None,
+ preview: None,
+ omitted_reply_count: 0,
+ },
+ reactions: Vec::new(),
+ attachments: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn cursor_round_trip_preserves_filters() {
+ let message_id = Uuid::new_v4();
+ let requested_message_id = Uuid::new_v4();
+ let filter = ChannelMessagesCursorFilter {
+ message_ids: vec![requested_message_id],
+ created_after: None,
+ created_before: None,
+ activity_after: Some(dt(10)),
+ activity_before: Some(dt(20)),
+ };
+ let cursor = cursor_from_newest_message(&[message(message_id, dt(15))], 25, filter)
+ .expect("message should produce cursor");
+
+ let decoded = decode_channel_cursor(&cursor).expect("cursor should decode");
+
+ assert_eq!(decoded.id, message_id);
+ assert_eq!(decoded.val.last_val, dt(15));
+ assert_eq!(decoded.filter.message_ids, vec![requested_message_id]);
+ assert_eq!(decoded.filter.activity_after, Some(dt(10)));
+ assert_eq!(decoded.filter.activity_before, Some(dt(20)));
+ }
+}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs
new file mode 100644
index 0000000000..e122dd599c
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/read_channel_thread.rs
@@ -0,0 +1,301 @@
+//! Tool for reading a channel message thread.
+
+use super::ChannelToolContext;
+use super::types::{
+ ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage, ToolThreadReply,
+ clamp_limit, clamp_max_chars, content_truncation_omissions,
+};
+use crate::domain::ports::ChannelMessagesService;
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Which part of a thread to read.
+#[allow(missing_docs)]
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ChannelThreadWindowType {
+ AllIfSmall,
+ Latest,
+ AroundReply,
+}
+
+/// Metadata about the thread being read.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadChannelThreadInfo {
+ /// Channel id containing the thread.
+ pub channel_id: Uuid,
+ /// Thread id, equal to the top-level parent message id.
+ pub thread_id: Uuid,
+ /// Parent top-level message.
+ pub parent: ToolChannelMessage,
+ /// Total number of replies in this thread.
+ pub reply_count: usize,
+ /// Timestamp of the latest reply, if any.
+ pub latest_reply_at: Option<DateTime<Utc>>,
+}
+
+/// Read replies from a channel thread.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadChannelThread",
+ description = "Read replies from a channel message thread. The messageId may be either the top-level parent message id or any reply id in the thread. Use this after ReadChannelMessages or ContentSearch finds a relevant threaded discussion."
+)]
+pub struct ReadChannelThread {
+ /// Channel id containing the thread.
+ #[schemars(description = "Channel id containing the thread.")]
+ pub channel_id: Uuid,
+ /// Parent message id or any reply id in the thread.
+ #[schemars(description = "Parent message id or any reply id in the thread.")]
+ pub message_id: Uuid,
+ /// Thread window to read. Defaults to latest replies.
+ #[schemars(
+ description = "Thread window to read: latest, allIfSmall, or aroundReply. Defaults to latest."
+ )]
+ #[serde(default)]
+ pub window_type: Option<ChannelThreadWindowType>,
+ /// Reply id to center around. Required when windowType is aroundReply.
+ #[schemars(
+ description = "Reply id to center around. Required when windowType is aroundReply."
+ )]
+ #[serde(default)]
+ pub reply_id: Option<Uuid>,
+ /// Number of replies before replyId for aroundReply windows. Defaults to 10, maximum 50.
+ #[schemars(
+ description = "Number of replies before replyId for aroundReply windows. Defaults to 10, maximum 50."
+ )]
+ #[serde(default)]
+ pub before: Option<u16>,
+ /// Number of replies after replyId for aroundReply windows. Defaults to 10, maximum 50.
+ #[schemars(
+ description = "Number of replies after replyId for aroundReply windows. Defaults to 10, maximum 50."
+ )]
+ #[serde(default)]
+ pub after: Option<u16>,
+ /// Maximum number of replies to return for latest/all-if-small windows. Defaults to 25, maximum 100.
+ #[schemars(
+ description = "Maximum number of replies to return for latest/all-if-small windows. Defaults to 25, maximum 100."
+ )]
+ #[serde(default)]
+ pub limit: Option<u16>,
+ /// Whether to include nearby top-level channel messages around the parent. Defaults to false.
+ #[schemars(
+ description = "Whether to include nearby top-level channel messages around the parent. Defaults to false."
+ )]
+ #[serde(default)]
+ pub include_channel_context: Option<bool>,
+ /// Maximum characters to return per message/reply. Defaults to 4000, maximum 16000.
+ #[schemars(
+ description = "Maximum characters to return per message/reply. Defaults to 4000, maximum 16000."
+ )]
+ #[serde(default)]
+ pub max_chars_per_message: Option<usize>,
+}
+
+/// Response from `ReadChannelThread`.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadChannelThreadResponse {
+ /// Resolution metadata for the requested message id.
+ pub anchor: ToolResolvedMessage,
+ /// Thread metadata and parent message.
+ pub thread: ReadChannelThreadInfo,
+ /// Replies returned for the requested window, in chronological order.
+ pub replies: Vec<ToolThreadReply>,
+ /// Nearby top-level channel messages around the parent, when requested.
+ pub channel_context: Option<Vec<ToolChannelMessage>>,
+ /// Information about omitted or truncated content.
+ pub omissions: Vec<ToolOmission>,
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ReadChannelThread
+where
+ Svc: ChannelMessagesService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ReadChannelThreadResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ service_context
+ .require_channel_member(&request_context, self.channel_id)
+ .await?;
+
+ let limit = clamp_limit(self.limit);
+ let max_chars_per_message = clamp_max_chars(self.max_chars_per_message);
+
+ let resolved = service_context
+ .service
+ .resolve_message(self.channel_id, self.message_id)
+ .await
+ .map_err(tool_err("failed to resolve channel message"))?;
+ let anchor = ToolResolvedMessage::from(resolved.clone());
+
+ let mut parent_page = service_context
+ .service
+ .get_channel_messages_around(self.channel_id, resolved.thread_id, 1)
+ .await
+ .map_err(tool_err("failed to read thread parent message"))?
+ .page;
+ let parent = parent_page.items.pop().ok_or_else(|| ToolCallError {
+ description: "thread parent message not found".to_string(),
+ internal_error: anyhow::anyhow!("thread parent not returned by channel service"),
+ })?;
+ let parent = ToolChannelMessage::from_message(parent, true, max_chars_per_message);
+
+ let all_replies = service_context
+ .service
+ .get_thread_replies(self.channel_id, resolved.thread_id)
+ .await
+ .map_err(tool_err("failed to read channel thread replies"))?;
+ let reply_count = all_replies.len();
+ let latest_reply_at = all_replies.last().map(|reply| reply.created_at);
+
+ let (reply_window, omitted_before, omitted_after) = select_replies(
+ all_replies,
+ self.window_type.unwrap_or(ChannelThreadWindowType::Latest),
+ self.reply_id,
+ self.before,
+ self.after,
+ limit,
+ )?;
+
+ let replies: Vec<ToolThreadReply> = reply_window
+ .into_iter()
+ .map(|reply| {
+ ToolThreadReply::from_reply(reply, resolved.thread_id, max_chars_per_message)
+ })
+ .collect();
+
+ let channel_context: Option<Vec<ToolChannelMessage>> =
+ if self.include_channel_context.unwrap_or(false) {
+ let mut page = service_context
+ .service
+ .get_channel_messages_around(self.channel_id, resolved.thread_id, 7)
+ .await
+ .map_err(tool_err("failed to read channel context around thread"))?
+ .page;
+ page.items.reverse();
+ Some(
+ page.items
+ .into_iter()
+ .map(|message| {
+ ToolChannelMessage::from_message(message, false, max_chars_per_message)
+ })
+ .collect(),
+ )
+ } else {
+ None
+ };
+
+ let mut omissions = Vec::new();
+ if omitted_before > 0 {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::ThreadReplies,
+ message_id: None,
+ thread_id: Some(resolved.thread_id),
+ count: Some(omitted_before as i64),
+ cursor: None,
+ });
+ }
+ if omitted_after > 0 {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::ThreadReplies,
+ message_id: None,
+ thread_id: Some(resolved.thread_id),
+ count: Some(omitted_after as i64),
+ cursor: None,
+ });
+ }
+ omissions.extend(content_truncation_omissions(
+ std::slice::from_ref(&parent),
+ &replies,
+ ));
+ if let Some(channel_context) = &channel_context {
+ omissions.extend(content_truncation_omissions(channel_context, &[]));
+ }
+
+ Ok(ReadChannelThreadResponse {
+ anchor,
+ thread: ReadChannelThreadInfo {
+ channel_id: self.channel_id,
+ thread_id: resolved.thread_id,
+ parent,
+ reply_count,
+ latest_reply_at,
+ },
+ replies,
+ channel_context,
+ omissions,
+ })
+ }
+}
+
+fn select_replies(
+ replies: Vec<crate::domain::models::ThreadReply>,
+ window_type: ChannelThreadWindowType,
+ reply_id: Option<Uuid>,
+ before: Option<u16>,
+ after: Option<u16>,
+ limit: u16,
+) -> Result<(Vec<crate::domain::models::ThreadReply>, usize, usize), ToolCallError> {
+ let total = replies.len();
+ let limit = usize::from(limit);
+ match window_type {
+ ChannelThreadWindowType::AllIfSmall => {
+ if total <= limit {
+ Ok((replies, 0, 0))
+ } else {
+ let start = total.saturating_sub(limit);
+ Ok((replies.into_iter().skip(start).collect(), start, 0))
+ }
+ }
+ ChannelThreadWindowType::Latest => {
+ let start = total.saturating_sub(limit);
+ Ok((replies.into_iter().skip(start).collect(), start, 0))
+ }
+ ChannelThreadWindowType::AroundReply => {
+ let reply_id = reply_id.ok_or_else(|| ToolCallError {
+ description: "replyId is required when windowType is aroundReply".to_string(),
+ internal_error: anyhow::anyhow!("missing thread reply anchor"),
+ })?;
+ let before = usize::from(before.unwrap_or(10).min(50));
+ let after = usize::from(after.unwrap_or(10).min(50));
+ let anchor_index = replies
+ .iter()
+ .position(|reply| reply.id == reply_id)
+ .ok_or_else(|| ToolCallError {
+ description: "replyId was not found in this thread".to_string(),
+ internal_error: anyhow::anyhow!("thread reply anchor not found"),
+ })?;
+ let start = anchor_index.saturating_sub(before);
+ let end = (anchor_index + after + 1).min(total);
+ let omitted_after = total.saturating_sub(end);
+ Ok((
+ replies.into_iter().skip(start).take(end - start).collect(),
+ start,
+ omitted_after,
+ ))
+ }
+ }
+}
+
+fn tool_err(
+ description: &'static str,
+) -> impl FnOnce(crate::domain::ports::ChannelMessagesErr) -> ToolCallError {
+ move |err| ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::Error::new(err),
+ }
+}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/test.rs b/rust/cloud-storage/channels/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..b60ab9ab08
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/test.rs
@@ -0,0 +1,39 @@
+use super::{ReadChannelMessageContext, ReadChannelMessages, ReadChannelThread};
+use ai::tool::tool_object::validate_tool_schema;
+use ai::{generate_tool_input_schema, generate_tool_output_schema};
+
+#[test]
+fn read_channel_messages_schema_is_valid() {
+ let schema = generate_tool_input_schema!(ReadChannelMessages);
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{result:?}");
+ let (name, description) = result.unwrap();
+ assert_eq!(name, "ReadChannelMessages");
+ assert!(description.contains("Read a small structured window"));
+
+ let _ = generate_tool_output_schema!(super::ReadChannelMessagesResponse);
+}
+
+#[test]
+fn read_channel_message_context_schema_is_valid() {
+ let schema = generate_tool_input_schema!(ReadChannelMessageContext);
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{result:?}");
+ let (name, description) = result.unwrap();
+ assert_eq!(name, "ReadChannelMessageContext");
+ assert!(description.contains("Read the local channel and thread context"));
+
+ let _ = generate_tool_output_schema!(super::ReadChannelMessageContextResponse);
+}
+
+#[test]
+fn read_channel_thread_schema_is_valid() {
+ let schema = generate_tool_input_schema!(ReadChannelThread);
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{result:?}");
+ let (name, description) = result.unwrap();
+ assert_eq!(name, "ReadChannelThread");
+ assert!(description.contains("Read"));
+
+ let _ = generate_tool_output_schema!(super::ReadChannelThreadResponse);
+}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/types.rs b/rust/cloud-storage/channels/src/inbound/toolset/types.rs
new file mode 100644
index 0000000000..1946d77b38
--- /dev/null
+++ b/rust/cloud-storage/channels/src/inbound/toolset/types.rs
@@ -0,0 +1,455 @@
+//! Shared channel AI tool input/output types.
+
+use crate::domain::models::{
+ ChannelMessage, ChannelMessageKind, CountedReaction, MessageAttachment, ResolvedChannelMessage,
+ ThreadReply,
+};
+use chrono::{DateTime, Utc};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Default number of messages/replies returned by channel AI tools.
+pub(crate) const DEFAULT_LIMIT: u16 = 25;
+/// Maximum number of messages/replies returned by channel AI tools.
+pub(crate) const MAX_LIMIT: u16 = 100;
+/// Default maximum content length per message.
+pub(crate) const DEFAULT_MAX_CHARS_PER_MESSAGE: usize = 4_000;
+/// Maximum allowed content length per message.
+pub(crate) const MAX_CHARS_PER_MESSAGE: usize = 16_000;
+
+/// Direction for reading more messages around a cursor.
+#[allow(missing_docs)]
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum PageDirection {
+ Older,
+ Newer,
+}
+
+/// Position of a channel message.
+#[derive(Debug, Clone, Copy, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub enum ToolMessageKind {
+ /// A top-level message in the channel timeline.
+ TopLevelMessage,
+ /// A reply inside a top-level message's thread.
+ ThreadReply,
+}
+
+impl From<ChannelMessageKind> for ToolMessageKind {
+ fn from(kind: ChannelMessageKind) -> Self {
+ match kind {
+ ChannelMessageKind::TopLevelMessage => Self::TopLevelMessage,
+ ChannelMessageKind::ThreadReply => Self::ThreadReply,
+ }
+ }
+}
+
+/// A reaction summary on a message.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolReaction {
+ /// Emoji that was reacted with.
+ pub emoji: String,
+ /// User ids that reacted with this emoji.
+ pub users: Vec<String>,
+}
+
+impl From<CountedReaction> for ToolReaction {
+ fn from(reaction: CountedReaction) -> Self {
+ Self {
+ emoji: reaction.emoji,
+ users: reaction.users,
+ }
+ }
+}
+
+/// A compact attachment reference on a message.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolAttachment {
+ /// Attachment id.
+ pub id: Uuid,
+ /// Attached entity type.
+ pub entity_type: String,
+ /// Attached entity id.
+ pub entity_id: String,
+ /// When the attachment was created.
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<MessageAttachment> for ToolAttachment {
+ fn from(attachment: MessageAttachment) -> Self {
+ Self {
+ id: attachment.id,
+ entity_type: attachment.entity_type,
+ entity_id: attachment.entity_id,
+ created_at: attachment.created_at,
+ }
+ }
+}
+
+/// A compact thread reply returned by channel AI tools.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolThreadReply {
+ /// Reply message id.
+ pub id: Uuid,
+ /// Parent thread id.
+ pub thread_id: Uuid,
+ /// Sender user id.
+ pub sender_id: String,
+ /// Reply content, possibly truncated.
+ pub content: String,
+ /// Whether the reply content was truncated.
+ pub content_truncated: bool,
+ /// When the reply was created.
+ pub created_at: DateTime<Utc>,
+ /// When the reply was last updated.
+ pub updated_at: DateTime<Utc>,
+ /// When the reply was edited, if ever.
+ pub edited_at: Option<DateTime<Utc>>,
+ /// Reactions on this reply.
+ pub reactions: Vec<ToolReaction>,
+ /// Attachments on this reply.
+ pub attachments: Vec<ToolAttachment>,
+}
+
+impl ToolThreadReply {
+ pub(crate) fn from_reply(
+ reply: ThreadReply,
+ thread_id: Uuid,
+ max_chars_per_message: usize,
+ ) -> Self {
+ let TruncatedContent {
+ content,
+ content_truncated,
+ } = truncate_content(reply.content, max_chars_per_message);
+
+ Self {
+ id: reply.id,
+ thread_id,
+ sender_id: reply.sender_id,
+ content,
+ content_truncated,
+ created_at: reply.created_at,
+ updated_at: reply.updated_at,
+ edited_at: reply.edited_at,
+ reactions: reply
+ .reactions
+ .into_iter()
+ .map(ToolReaction::from)
+ .collect(),
+ attachments: reply
+ .attachments
+ .into_iter()
+ .map(ToolAttachment::from)
+ .collect(),
+ }
+ }
+}
+
+/// Thread metadata attached to a top-level message.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolThreadSummary {
+ /// Parent thread id. This equals the top-level message id.
+ pub thread_id: Uuid,
+ /// Total number of replies in the thread.
+ pub reply_count: i64,
+ /// Timestamp of the latest reply, if any.
+ pub latest_reply_at: Option<DateTime<Utc>>,
+ /// Preview replies, when requested.
+ pub preview: Option<Vec<ToolThreadReply>>,
+ /// Reply count not included in `preview`.
+ pub omitted_reply_count: i64,
+}
+
+/// A compact top-level channel message returned by channel AI tools.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolChannelMessage {
+ /// Message id.
+ pub id: Uuid,
+ /// Channel id.
+ pub channel_id: Uuid,
+ /// Sender user id.
+ pub sender_id: String,
+ /// Message content, possibly truncated.
+ pub content: String,
+ /// Whether message content was truncated.
+ pub content_truncated: bool,
+ /// When the message was created.
+ pub created_at: DateTime<Utc>,
+ /// When the message was last updated.
+ pub updated_at: DateTime<Utc>,
+ /// When the message was edited, if ever.
+ pub edited_at: Option<DateTime<Utc>>,
+ /// When the message was deleted, if ever.
+ pub deleted_at: Option<DateTime<Utc>>,
+ /// Thread metadata for this message.
+ pub thread: ToolThreadSummary,
+ /// Reactions on this message.
+ pub reactions: Vec<ToolReaction>,
+ /// Attachments on this message.
+ pub attachments: Vec<ToolAttachment>,
+}
+
+impl ToolChannelMessage {
+ pub(crate) fn from_message(
+ message: ChannelMessage,
+ include_thread_preview: bool,
+ max_chars_per_message: usize,
+ ) -> Self {
+ let thread_id = message.id;
+ let TruncatedContent {
+ content,
+ content_truncated,
+ } = truncate_content(message.content, max_chars_per_message);
+ let preview_replies = message.thread.preview;
+ let preview_len = if include_thread_preview {
+ preview_replies.len() as i64
+ } else {
+ 0
+ };
+ let preview = include_thread_preview.then(|| {
+ preview_replies
+ .into_iter()
+ .map(|reply| ToolThreadReply::from_reply(reply, thread_id, max_chars_per_message))
+ .collect()
+ });
+
+ Self {
+ id: message.id,
+ channel_id: message.channel_id,
+ sender_id: message.sender_id,
+ content,
+ content_truncated,
+ created_at: message.created_at,
+ updated_at: message.updated_at,
+ edited_at: message.edited_at,
+ deleted_at: message.deleted_at,
+ thread: ToolThreadSummary {
+ thread_id,
+ reply_count: message.thread.reply_count,
+ latest_reply_at: message.thread.latest_reply_at,
+ preview,
+ omitted_reply_count: (message.thread.reply_count - preview_len).max(0),
+ },
+ reactions: message
+ .reactions
+ .into_iter()
+ .map(ToolReaction::from)
+ .collect(),
+ attachments: message
+ .attachments
+ .into_iter()
+ .map(ToolAttachment::from)
+ .collect(),
+ }
+ }
+}
+
+/// Resolution details for a requested message id.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolResolvedMessage {
+ /// Requested message id.
+ pub message_id: Uuid,
+ /// Channel id.
+ pub channel_id: Uuid,
+ /// Whether the message is top-level or a thread reply.
+ pub kind: ToolMessageKind,
+ /// Parent thread id. Equals `message_id` for top-level messages.
+ pub thread_id: Uuid,
+ /// When the requested message was created.
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<ResolvedChannelMessage> for ToolResolvedMessage {
+ fn from(message: ResolvedChannelMessage) -> Self {
+ Self {
+ message_id: message.message_id,
+ channel_id: message.channel_id,
+ kind: ToolMessageKind::from(message.kind),
+ thread_id: message.thread_id,
+ created_at: message.created_at,
+ }
+ }
+}
+
+/// Navigation cursors and continuation hints for a bounded result.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolNavigation {
+ /// Cursor for reading older items, if available.
+ pub older_cursor: Option<String>,
+ /// Cursor for reading newer items, if available.
+ pub newer_cursor: Option<String>,
+ /// Whether an older cursor was returned.
+ pub has_more_older: bool,
+ /// Whether newer messages are known to exist.
+ pub has_more_newer: bool,
+}
+
+/// Kind of content omitted from a bounded tool response.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub enum ToolOmissionKind {
+ /// Older channel messages exist outside the returned window.
+ OlderMessages,
+ /// Newer channel messages exist outside the returned window.
+ NewerMessages,
+ /// Thread replies were omitted.
+ ThreadReplies,
+ /// Message content was truncated.
+ TruncatedContent,
+}
+
+/// Information about content omitted from a tool response.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolOmission {
+ /// Omission category.
+ pub kind: ToolOmissionKind,
+ /// Message id associated with the omission, when applicable.
+ pub message_id: Option<Uuid>,
+ /// Thread id associated with the omission, when applicable.
+ pub thread_id: Option<Uuid>,
+ /// Number of omitted items, when known.
+ pub count: Option<i64>,
+ /// Cursor that can be used to continue reading, when available.
+ pub cursor: Option<String>,
+}
+
+struct TruncatedContent {
+ content: String,
+ content_truncated: bool,
+}
+
+pub(crate) fn clamp_limit(limit: Option<u16>) -> u16 {
+ limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT)
+}
+
+pub(crate) fn clamp_max_chars(max_chars_per_message: Option<usize>) -> usize {
+ max_chars_per_message
+ .unwrap_or(DEFAULT_MAX_CHARS_PER_MESSAGE)
+ .clamp(1, MAX_CHARS_PER_MESSAGE)
+}
+
+fn truncate_content(content: String, max_chars: usize) -> TruncatedContent {
+ let mut chars = content.chars();
+ let truncated: String = chars.by_ref().take(max_chars).collect();
+ let content_truncated = chars.next().is_some();
+
+ TruncatedContent {
+ content: truncated,
+ content_truncated,
+ }
+}
+
+pub(crate) fn content_truncation_omissions(
+ messages: &[ToolChannelMessage],
+ replies: &[ToolThreadReply],
+) -> Vec<ToolOmission> {
+ let mut omissions = Vec::new();
+ for message in messages {
+ if message.content_truncated {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::TruncatedContent,
+ message_id: Some(message.id),
+ thread_id: None,
+ count: None,
+ cursor: None,
+ });
+ }
+ for reply in message.thread.preview.iter().flatten() {
+ if reply.content_truncated {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::TruncatedContent,
+ message_id: Some(reply.id),
+ thread_id: Some(reply.thread_id),
+ count: None,
+ cursor: None,
+ });
+ }
+ }
+ }
+ for reply in replies {
+ if reply.content_truncated {
+ omissions.push(ToolOmission {
+ kind: ToolOmissionKind::TruncatedContent,
+ message_id: Some(reply.id),
+ thread_id: Some(reply.thread_id),
+ count: None,
+ cursor: None,
+ });
+ }
+ }
+ omissions
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::domain::models::ThreadInfo;
+
+ fn dt(seconds: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp(seconds, 0).unwrap()
+ }
+
+ fn reply(seconds: i64) -> ThreadReply {
+ ThreadReply {
+ id: Uuid::new_v4(),
+ sender_id: "macro|[email protected]".to_string(),
+ content: "reply".to_string(),
+ created_at: dt(seconds),
+ updated_at: dt(seconds),
+ edited_at: None,
+ reactions: Vec::new(),
+ attachments: Vec::new(),
+ }
+ }
+
+ fn message_with_thread(reply_count: i64, preview: Vec<ThreadReply>) -> ChannelMessage {
+ let id = Uuid::new_v4();
+ ChannelMessage {
+ id,
+ channel_id: Uuid::new_v4(),
+ sender_id: "macro|[email protected]".to_string(),
+ content: "parent".to_string(),
+ created_at: dt(1),
+ updated_at: dt(1),
+ edited_at: None,
+ deleted_at: None,
+ thread: ThreadInfo {
+ reply_count,
+ latest_reply_at: None,
+ preview,
+ },
+ reactions: Vec::new(),
+ attachments: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn omitted_reply_count_includes_hidden_previews_when_preview_is_disabled() {
+ let message = message_with_thread(5, vec![reply(2), reply(3), reply(4)]);
+
+ let tool_message = ToolChannelMessage::from_message(message, false, 4_000);
+
+ assert!(tool_message.thread.preview.is_none());
+ assert_eq!(tool_message.thread.omitted_reply_count, 5);
+ }
+
+ #[test]
+ fn omitted_reply_count_excludes_included_previews_when_preview_is_enabled() {
+ let message = message_with_thread(5, vec![reply(2), reply(3), reply(4)]);
+
+ let tool_message = ToolChannelMessage::from_message(message, true, 4_000);
+
+ assert_eq!(tool_message.thread.preview.as_ref().unwrap().len(), 3);
+ assert_eq!(tool_message.thread.omitted_reply_count, 2);
+ }
+}
diff --git a/rust/cloud-storage/channels/src/lib.rs b/rust/cloud-storage/channels/src/lib.rs
index 4c710727a9..2996f1bc26 100644
--- a/rust/cloud-storage/channels/src/lib.rs
+++ b/rust/cloud-storage/channels/src/lib.rs
@@ -4,7 +4,7 @@
/// Domain layer: models, ports, and service.
pub mod domain;
/// Inbound layer: axum handler and router.
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
/// Outbound layer: postgres repository.
#[cfg(feature = "outbound")]
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index b954545fd3..a27f5a4659 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -3,9 +3,9 @@ mod tests;
use crate::domain::{
models::{
- ChannelAttachment, ChannelAttachmentType, ChannelMessageFilters, ChannelParticipant,
- CountedReaction, MessageAttachment, MessagePageDirection, ParticipantRole, ThreadData,
- ThreadReplyRow, TopLevelMessageRow,
+ ChannelAttachment, ChannelAttachmentType, ChannelMessageFilters, ChannelMessageKind,
+ ChannelParticipant, CountedReaction, MessageAttachment, MessagePageDirection,
+ ParticipantRole, ResolvedChannelMessage, ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
ports::{ChannelMessagesRepo, TopLevelMessagesQueryResult},
};
@@ -29,7 +29,7 @@ impl PgChannelMessagesRepo {
}
/// Intermediate row for the top-level messages query.
-#[derive(Debug)]
+#[derive(Debug, sqlx::FromRow)]
struct TopLevelRow {
id: Uuid,
channel_id: Uuid,
@@ -41,6 +41,15 @@ struct TopLevelRow {
deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}
+/// Intermediate row for resolving a message id.
+#[derive(Debug, sqlx::FromRow)]
+struct ResolvedMessageRow {
+ id: Uuid,
+ channel_id: Uuid,
+ thread_id: Option<Uuid>,
+ created_at: chrono::DateTime<chrono::Utc>,
+}
+
/// Intermediate row for the merged thread data query (stats + preview replies).
#[derive(Debug)]
struct ThreadDataRow {
@@ -136,7 +145,10 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
} else {
Some(&filters.message_ids)
};
- let last_activity = filters.last_activity;
+ let created_after = filters.created_after;
+ let created_before = filters.created_before;
+ let activity_after = filters.activity_after;
+ let activity_before = filters.activity_before;
let notification_filter_active = !filters.notification_filters.is_empty();
let notification_user_id = match (notification_filter_active, notification_user_id.as_ref())
{
@@ -151,94 +163,9 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
let (rows, has_more_newer) = match direction {
MessagePageDirection::Older => {
- let rows = if notification_filter_active {
- sqlx::query_as!(
- TopLevelRow,
- r#"
- WITH done_top_level AS (
- SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
- FROM notification n
- JOIN user_notification un ON un.notification_id = n.id
- JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
- WHERE $8::bool IS NOT NULL
- AND un.user_id = $7::text
- AND un.deleted_at IS NULL
- AND un.done = $8
- AND n.event_item_type = 'channel'
- AND n.event_item_id = $1::uuid::text
- AND n.metadata->>'messageId' IS NOT NULL
- AND msg.channel_id = $1
- AND msg.deleted_at IS NULL
- ),
- seen_top_level AS (
- SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
- FROM notification n
- JOIN user_notification un ON un.notification_id = n.id
- JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
- WHERE $9::bool IS NOT NULL
- AND un.user_id = $7::text
- AND un.deleted_at IS NULL
- AND (un.seen_at IS NOT NULL) = $9
- AND n.event_item_type = 'channel'
- AND n.event_item_id = $1::uuid::text
- AND n.metadata->>'messageId' IS NOT NULL
- AND msg.channel_id = $1
- AND msg.deleted_at IS NULL
- )
- SELECT
- m.id,
- m.channel_id,
- m.sender_id,
- m.content,
- m.created_at,
- m.updated_at,
- m.edited_at::timestamptz AS "edited_at?",
- m.deleted_at::timestamptz AS "deleted_at?"
- FROM comms_messages m
- WHERE m.channel_id = $1
- AND m.thread_id IS NULL
- AND (m.deleted_at IS NULL OR EXISTS (
- SELECT 1 FROM comms_messages r
- WHERE r.thread_id = m.id AND r.deleted_at IS NULL
- ))
- AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))
- AND ($5::uuid[] IS NULL OR m.id = ANY($5))
- AND ($6::timestamptz IS NULL OR (
- m.created_at > $6
- OR EXISTS (
- SELECT 1 FROM comms_messages r
- WHERE r.thread_id = m.id
- AND r.deleted_at IS NULL
- AND r.created_at > $6
- )
- ))
- AND ($8::bool IS NULL OR EXISTS (
- SELECT 1 FROM done_top_level dt
- WHERE dt.top_level_id = m.id
- ))
- AND ($9::bool IS NULL OR EXISTS (
- SELECT 1 FROM seen_top_level st
- WHERE st.top_level_id = m.id
- ))
- ORDER BY m.created_at DESC, m.id DESC
- LIMIT $4
- "#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- notification_user_id,
- notification_done,
- notification_seen,
- )
- .fetch_all(&self.pool)
- .await?
- } else {
- sqlx::query_as!(
- TopLevelRow,
- r#"
+ let rows = sqlx::query_as!(
+ TopLevelRow,
+ r#"
SELECT
m.id,
m.channel_id,
@@ -257,120 +184,80 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
))
AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))
AND ($5::uuid[] IS NULL OR m.id = ANY($5))
- AND ($6::timestamptz IS NULL OR (
- m.created_at > $6
+ AND ($6::timestamptz IS NULL OR m.created_at >= $6)
+ AND ($7::timestamptz IS NULL OR m.created_at < $7)
+ AND (
+ ($8::timestamptz IS NULL AND $9::timestamptz IS NULL)
+ OR (
+ ($8::timestamptz IS NULL OR m.created_at >= $8)
+ AND ($9::timestamptz IS NULL OR m.created_at < $9)
+ )
OR EXISTS (
SELECT 1 FROM comms_messages r
WHERE r.thread_id = m.id
AND r.deleted_at IS NULL
- AND r.created_at > $6
+ AND ($8::timestamptz IS NULL OR r.created_at >= $8)
+ AND ($9::timestamptz IS NULL OR r.created_at < $9)
)
+ )
+ AND ($10::bool = FALSE OR (
+ ($11::bool IS NULL OR EXISTS (
+ SELECT 1
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE un.user_id = $13::text
+ AND un.deleted_at IS NULL
+ AND un.done = $11
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ AND COALESCE(msg.thread_id, msg.id) = m.id
+ ))
+ AND ($12::bool IS NULL OR EXISTS (
+ SELECT 1
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE un.user_id = $13::text
+ AND un.deleted_at IS NULL
+ AND (un.seen_at IS NOT NULL) = $12
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ AND COALESCE(msg.thread_id, msg.id) = m.id
+ ))
))
ORDER BY m.created_at DESC, m.id DESC
LIMIT $4
"#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- )
- .fetch_all(&self.pool)
- .await?
- };
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64,
+ message_ids_filter as Option<&[Uuid]>,
+ created_after,
+ created_before,
+ activity_after,
+ activity_before,
+ notification_filter_active,
+ notification_done,
+ notification_seen,
+ notification_user_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
(rows, cursor_created_at.is_some())
}
MessagePageDirection::Newer => {
- let mut rows = if notification_filter_active {
- sqlx::query_as!(
- TopLevelRow,
- r#"
- WITH done_top_level AS (
- SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
- FROM notification n
- JOIN user_notification un ON un.notification_id = n.id
- JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
- WHERE $8::bool IS NOT NULL
- AND un.user_id = $7::text
- AND un.deleted_at IS NULL
- AND un.done = $8
- AND n.event_item_type = 'channel'
- AND n.event_item_id = $1::uuid::text
- AND n.metadata->>'messageId' IS NOT NULL
- AND msg.channel_id = $1
- AND msg.deleted_at IS NULL
- ),
- seen_top_level AS (
- SELECT DISTINCT COALESCE(msg.thread_id, msg.id) AS top_level_id
- FROM notification n
- JOIN user_notification un ON un.notification_id = n.id
- JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
- WHERE $9::bool IS NOT NULL
- AND un.user_id = $7::text
- AND un.deleted_at IS NULL
- AND (un.seen_at IS NOT NULL) = $9
- AND n.event_item_type = 'channel'
- AND n.event_item_id = $1::uuid::text
- AND n.metadata->>'messageId' IS NOT NULL
- AND msg.channel_id = $1
- AND msg.deleted_at IS NULL
- )
- SELECT
- m.id,
- m.channel_id,
- m.sender_id,
- m.content,
- m.created_at,
- m.updated_at,
- m.edited_at::timestamptz AS "edited_at?",
- m.deleted_at::timestamptz AS "deleted_at?"
- FROM comms_messages m
- WHERE m.channel_id = $1
- AND m.thread_id IS NULL
- AND (m.deleted_at IS NULL OR EXISTS (
- SELECT 1 FROM comms_messages r
- WHERE r.thread_id = m.id AND r.deleted_at IS NULL
- ))
- AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))
- AND ($5::uuid[] IS NULL OR m.id = ANY($5))
- AND ($6::timestamptz IS NULL OR (
- m.created_at > $6
- OR EXISTS (
- SELECT 1 FROM comms_messages r
- WHERE r.thread_id = m.id
- AND r.deleted_at IS NULL
- AND r.created_at > $6
- )
- ))
- AND ($8::bool IS NULL OR EXISTS (
- SELECT 1 FROM done_top_level dt
- WHERE dt.top_level_id = m.id
- ))
- AND ($9::bool IS NULL OR EXISTS (
- SELECT 1 FROM seen_top_level st
- WHERE st.top_level_id = m.id
- ))
- ORDER BY m.created_at ASC, m.id ASC
- LIMIT $4
- "#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64 + 1,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- notification_user_id,
- notification_done,
- notification_seen,
- )
- .fetch_all(&self.pool)
- .await?
- } else {
- sqlx::query_as!(
- TopLevelRow,
- r#"
+ let mut rows = sqlx::query_as!(
+ TopLevelRow,
+ r#"
SELECT
m.id,
m.channel_id,
@@ -389,28 +276,73 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
))
AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))
AND ($5::uuid[] IS NULL OR m.id = ANY($5))
- AND ($6::timestamptz IS NULL OR (
- m.created_at > $6
+ AND ($6::timestamptz IS NULL OR m.created_at >= $6)
+ AND ($7::timestamptz IS NULL OR m.created_at < $7)
+ AND (
+ ($8::timestamptz IS NULL AND $9::timestamptz IS NULL)
+ OR (
+ ($8::timestamptz IS NULL OR m.created_at >= $8)
+ AND ($9::timestamptz IS NULL OR m.created_at < $9)
+ )
OR EXISTS (
SELECT 1 FROM comms_messages r
WHERE r.thread_id = m.id
AND r.deleted_at IS NULL
- AND r.created_at > $6
+ AND ($8::timestamptz IS NULL OR r.created_at >= $8)
+ AND ($9::timestamptz IS NULL OR r.created_at < $9)
)
+ )
+ AND ($10::bool = FALSE OR (
+ ($11::bool IS NULL OR EXISTS (
+ SELECT 1
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE un.user_id = $13::text
+ AND un.deleted_at IS NULL
+ AND un.done = $11
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ AND COALESCE(msg.thread_id, msg.id) = m.id
+ ))
+ AND ($12::bool IS NULL OR EXISTS (
+ SELECT 1
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ JOIN comms_messages msg ON msg.id = (n.metadata->>'messageId')::uuid
+ WHERE un.user_id = $13::text
+ AND un.deleted_at IS NULL
+ AND (un.seen_at IS NOT NULL) = $12
+ AND n.event_item_type = 'channel'
+ AND n.event_item_id = $1::uuid::text
+ AND n.metadata->>'messageId' IS NOT NULL
+ AND msg.channel_id = $1
+ AND msg.deleted_at IS NULL
+ AND COALESCE(msg.thread_id, msg.id) = m.id
+ ))
))
ORDER BY m.created_at ASC, m.id ASC
LIMIT $4
"#,
- channel_id,
- cursor_created_at,
- cursor_id,
- limit_i64 + 1,
- message_ids_filter as Option<&[Uuid]>,
- last_activity,
- )
- .fetch_all(&self.pool)
- .await?
- };
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64 + 1,
+ message_ids_filter as Option<&[Uuid]>,
+ created_after,
+ created_before,
+ activity_after,
+ activity_before,
+ notification_filter_active,
+ notification_done,
+ notification_seen,
+ notification_user_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
let has_more_newer = rows.len() > limit_usize;
if has_more_newer {
@@ -510,23 +442,24 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
#[tracing::instrument(err, skip(self))]
async fn get_thread_replies(&self, parent_id: Uuid) -> Result<Vec<ThreadReplyRow>, Self::Err> {
- let rows = sqlx::query_as::<_, ThreadReplyOnlyRow>(
+ let rows = sqlx::query_as!(
+ ThreadReplyOnlyRow,
r#"
SELECT
id,
- thread_id,
+ thread_id AS "thread_id!",
sender_id,
content,
created_at,
updated_at,
- edited_at::timestamptz AS edited_at
+ edited_at::timestamptz AS "edited_at?"
FROM comms_messages
WHERE thread_id = $1
AND deleted_at IS NULL
ORDER BY created_at ASC, id ASC
"#,
+ parent_id,
)
- .bind(parent_id)
.fetch_all(&self.pool)
.await?;
@@ -763,6 +696,42 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
}))
}
+ #[tracing::instrument(err, skip(self))]
+ async fn resolve_message(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<Option<ResolvedChannelMessage>, Self::Err> {
+ let row = sqlx::query_as!(
+ ResolvedMessageRow,
+ r#"
+ SELECT id, channel_id, thread_id, created_at
+ FROM comms_messages
+ WHERE id = $1
+ AND channel_id = $2
+ "#,
+ message_id,
+ channel_id,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(row.map(|r| {
+ let kind = if r.thread_id.is_some() {
+ ChannelMessageKind::ThreadReply
+ } else {
+ ChannelMessageKind::TopLevelMessage
+ };
+ ResolvedChannelMessage {
+ message_id: r.id,
+ channel_id: r.channel_id,
+ kind,
+ thread_id: r.thread_id.unwrap_or(r.id),
+ created_at: r.created_at,
+ }
+ }))
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_top_level_messages_around(
&self,
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index 4180595b6e..4c49e80c42 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -11,7 +11,10 @@ use uuid::Uuid;
const NO_FILTERS: ChannelMessageFilters = ChannelMessageFilters {
message_ids: Vec::new(),
- last_activity: None,
+ created_after: None,
+ created_before: None,
+ activity_after: None,
+ activity_before: None,
notification_filters: NotificationFilters {
done: None,
seen: None,
@@ -812,7 +815,7 @@ async fn last_activity_filters_by_message_created_at(pool: Pool<Postgres>) -> an
let repo = repo(pool);
// msg3 created at 12:00 — only it was created after 11:30
let filters = ChannelMessageFilters {
- last_activity: Some(
+ activity_after: Some(
chrono::DateTime::parse_from_rfc3339("2024-01-01T11:30:00Z")
.unwrap()
.with_timezone(&chrono::Utc),
@@ -849,7 +852,7 @@ async fn last_activity_includes_messages_with_recent_thread_replies(
// last_activity = 10:05 excludes msg1 (created 10:00, last reply 10:04),
// but includes msg2 (reply at 11:01) and msg3 (created 12:00).
let filters = ChannelMessageFilters {
- last_activity: Some(
+ activity_after: Some(
chrono::DateTime::parse_from_rfc3339("2024-01-01T10:05:00Z")
.unwrap()
.with_timezone(&chrono::Utc),
@@ -881,7 +884,7 @@ async fn last_activity_combined_with_message_ids(pool: Pool<Postgres>) -> anyhow
// Ask for msg1 and msg3, but with last_activity that excludes msg1
let filters = ChannelMessageFilters {
message_ids: vec![MSG1, MSG3],
- last_activity: Some(
+ activity_after: Some(
chrono::DateTime::parse_from_rfc3339("2024-01-01T11:00:00Z")
.unwrap()
.with_timezone(&chrono::Utc),
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 27f2d823cd..9f4870a4c3 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -325,6 +325,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
chat_tool_context,
+ channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),
schedule_tool_context: ai_tools::no_op_schedule_context(),
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index af435247bb..2454828b69 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -345,6 +345,7 @@ async fn main() -> anyhow::Result<()> {
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
chat_tool_context,
+ channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index d3dce93d95..7590816974 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -63,9 +63,10 @@ use crate::{
},
};
use channels::inbound::axum_router::{
- ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelMessage, ApiChannelMessagesPage,
- ApiChannelParticipant, ApiCountedReaction, ApiMessageAttachment, ApiParticipantRole,
- ApiThreadInfo, ApiThreadReply, ChannelMessageFilters,
+ ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelMessage, ApiChannelMessageKind,
+ ApiChannelMessagesPage, ApiChannelParticipant, ApiCountedReaction, ApiMessageAttachment,
+ ApiParticipantRole, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply,
+ ChannelMessageFilters,
};
use document_sub_type::DocumentSubType;
use documents_hex::inbound::axum_router::ShortIdResponse;
@@ -189,6 +190,7 @@ use utoipa::OpenApi;
channels::inbound::axum_router::get_channel_messages_handler,
channels::inbound::axum_router::post_channel_messages_handler,
channels::inbound::axum_router::get_thread_replies_handler,
+ channels::inbound::axum_router::resolve_channel_message_handler,
channels::inbound::axum_router::get_channel_attachments_handler,
channels::inbound::axum_router::get_channel_participants_handler,
@@ -335,6 +337,8 @@ use utoipa::OpenApi;
ApiChannelMessage,
ApiThreadInfo,
ApiThreadReply,
+ ApiChannelMessageKind,
+ ApiResolvedChannelMessage,
ApiCountedReaction,
ApiMessageAttachment,
ApiChannelAttachmentsPage,
diff --git a/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs b/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs
index acf19ee909..acbba3880f 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs
@@ -93,7 +93,7 @@ const DEFAULT_LIMIT: i64 = 10;
description = "Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation."
)]
#[serde(rename_all = "camelCase")]
-pub struct ReadThread {
+pub struct GetThread {
/// The ID of the email thread to retrieve.
pub thread_id: Uuid,
/// Maximum number of messages to return (default 10).
@@ -102,7 +102,7 @@ pub struct ReadThread {
}
#[async_trait]
-impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for ReadThread
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for GetThread
where
T: EmailService,
G: GmailTokenProvider,
diff --git a/rust/cloud-storage/email/src/inbound/toolset/mod.rs b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
index 75ca5e97e6..643197642e 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
@@ -17,7 +17,7 @@ use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
-pub use get_thread::{GetThreadResponse, ReadThread};
+pub use get_thread::{GetThread, GetThreadResponse};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
pub use send_email::{SendEmail, SendEmailResponse};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
@@ -98,6 +98,6 @@ where
{
AsyncToolSet::new()
.add_tool::<UpdateThreadLabels, EmailToolContext<T, G, E>>()
- .add_tool::<ReadThread, EmailToolContext<T, G, E>>()
+ .add_tool::<GetThread, EmailToolContext<T, G, E>>()
.add_user_tool::<SendEmail, EmailToolContext<T, G, E>>()
}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/test.rs b/rust/cloud-storage/email/src/inbound/toolset/test.rs
index 14d121ca78..27f52d869e 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/test.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/test.rs
@@ -73,7 +73,7 @@ fn test_send_email_schema_validation() {
#[test]
fn test_get_thread_schema_validation() {
- let schema = generate_tool_input_schema!(ReadThread);
+ let schema = generate_tool_input_schema!(GetThread);
let result = validate_tool_schema(&schema);
assert!(result.is_ok(), "{:?}", result);
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 0bf156422c..0d3499c0d0 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -316,6 +316,7 @@ async fn build_tool_context(
email_tool_context,
call_tool_context,
chat_tool_context,
+ channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),
schedule_tool_context: NoOpScheduleContext,
};
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
index 6f75468f5b..2af363999b 100644
--- a/rust/cloud-storage/memory/Cargo.toml
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -28,6 +28,7 @@ tracing = { workspace = true }
utoipa = { workspace = true }
# For building ToolServiceContext
+call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
comms = { path = "../comms" }
document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents" }
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index f2e6281229..fbc194fdeb 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -183,6 +183,24 @@ pub async fn build_tool_service_context(
))),
);
+ let call_service = call::domain::service::CallServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ ai_tools::NoOpCallRtcClient,
+ ai_tools::NoOpConnectionService,
+ (*entity_access_service).clone(),
+ ai_tools::NoOpNotificationIngress,
+ None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
+ String::new(),
+ );
+ let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(
+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
+ );
+ let call_tool_context = call::inbound::toolset::CallToolContext::new(
+ call_service,
+ call_query_service,
+ (*entity_access_service).clone(),
+ );
+
Ok(ToolServiceContext {
search_service_client: search_client,
email_service_client: email_ext_client,
@@ -192,5 +210,8 @@ pub async fn build_tool_service_context(
document_tool_context,
properties_tool_context,
email_tool_context,
+ call_tool_context,
+ channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),
+ schedule_tool_context: ai_tools::NoOpScheduleContext,
})
}