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): email tools (#2362)

Eric Hayes4351f169d684
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index 8c60f0ae10..1e68254b4b 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -19,19 +19,19 @@ import {
} from '@core/user';
import { whenSettled } from '@core/util/whenSettled';
import { createEffectOnEntityTypeNotification } from '@notifications';
+import { queryClient } from '@queries/client';
+import { emailKeys } from '@queries/email/keys';
import {
- useArchiveThreadMutation,
blockSenderWithToast,
- markSenderSignalWithToast,
markSenderNoiseWithToast,
+ markSenderSignalWithToast,
+ useArchiveThreadMutation,
useThreadQuery,
} from '@queries/email/thread';
-import { emailKeys } from '@queries/email/keys';
-import { queryClient } from '@queries/client';
import type {
+ ApiMessage,
ApiThread,
ContactInfo,
- ApiMessage,
} from '@service-email/generated/schemas';
import { useSearchParams } from '@solidjs/router';
import {
@@ -59,7 +59,6 @@ const draftSavedThreadIds = new Set<string>();
export function markThreadDraftSaved(threadId: string) {
draftSavedThreadIds.add(threadId);
}
-
export type EmailRecipient = WithCustomUserInput<'user' | 'contact'>;
export type EmailContextValues = {
diff --git a/js/app/packages/block-email/component/compose/Compose.tsx b/js/app/packages/block-email/component/compose/Compose.tsx
index f6b7051262..8c865db0bf 100644
--- a/js/app/packages/block-email/component/compose/Compose.tsx
+++ b/js/app/packages/block-email/component/compose/Compose.tsx
@@ -1,3 +1,8 @@
+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
+import {
+ SplitHeaderBadge,
+ StaticSplitLabel,
+} from '@app/component/split-layout/components/SplitLabel';
import { useSplitLayout } from '@app/component/split-layout/layout';
import type { EmailFormRecipients } from '@block-email/component/createEmailFormState';
import {
@@ -15,7 +20,11 @@ import {
} from '@block-email/util/prepareEmailBody';
import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';
import { useHasPaidAccess } from '@core/auth';
+import { ClippedPanel } from '@core/component/ClippedPanel';
+import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';
import { toast } from '@core/component/Toast/Toast';
+import { isMobile } from '@core/mobile/isMobile';
+import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import {
type ContactInfo,
@@ -49,8 +58,9 @@ import {
import { invalidateSoupEntity } from '@queries/soup/cache';
import { emailClient } from '@service-email/client';
import { debounce } from '@solid-primitives/scheduled';
+import { beveledCorners } from 'core/signal/beveledCorners';
import type { LexicalEditor } from 'lexical';
-import { createEffect, createMemo, createSignal, on } from 'solid-js';
+import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
import { unwrap } from 'solid-js/store';
import {
type ComposeContextValue,
@@ -626,11 +636,35 @@ export function EmailCompose(props: EmailComposeProps) {
return (
<ComposeProvider value={ctxValue}>
- <ComposeLayout
- toolbar={<EmailComposeToolbar editor={editor} />}
- hasLinkError={hasLinkError}
- previewName={previewName}
- />
+ <Show when={!isMobile()}>
+ <SplitHeaderLeft>
+ <StaticSplitLabel
+ class="ph-no-capture"
+ label={ctxValue.subject() || previewName?.() || 'Draft email'}
+ iconType="email"
+ badges={[
+ <SplitHeaderBadge text="draft" tooltip="This is a Draft Email" />,
+ ]}
+ />
+ </SplitHeaderLeft>
+ </Show>
+ <div class="relative flex flex-col w-full h-full min-h-0 overflow-hidden text-sm">
+ <Show when={hasLinkError()}>
+ <EmailPermissionsBanner />
+ </Show>
+ <div class="macro-message-width sm:macro-message-padding mx-auto w-full min-h-120 max-h-full my-2 sm:my-12 mobile:my-0 px-2 sm:px-4 mobile:px-0 overflow-hidden mobile:overflow-y-auto mobile:hide-scrollbar mobile:min-h-full">
+ <WrapUnlessMobile
+ wrapper={(children) => (
+ <ClippedPanel tl={!beveledCorners()}>{children}</ClippedPanel>
+ )}
+ >
+ <ComposeLayout
+ toolbar={<EmailComposeToolbar editor={editor} />}
+ class="w-full h-full p-4 bg-input max-h-full mobile:max-h-none overflow-y-auto flex flex-col min-h-0 mobile:min-h-full"
+ />
+ </WrapUnlessMobile>
+ </div>
+ </div>
</ComposeProvider>
);
}
diff --git a/js/app/packages/block-email/component/compose/ComposeBody.tsx b/js/app/packages/block-email/component/compose/ComposeBody.tsx
index b72b60ac85..db26e230cd 100644
--- a/js/app/packages/block-email/component/compose/ComposeBody.tsx
+++ b/js/app/packages/block-email/component/compose/ComposeBody.tsx
@@ -7,13 +7,17 @@ import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core
import { createFilesReadyHandler } from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { handleFileFolderDrop } from '@core/util/upload';
+import { logger } from '@observability/logger';
import { cn } from '@ui/utils/classname';
import type { LexicalEditor } from 'lexical';
import {
type Accessor,
+ createEffect,
createSignal,
For,
Match,
+ on,
+ onCleanup,
Show,
Switch,
} from 'solid-js';
@@ -25,6 +29,7 @@ import { useCompose } from './ComposeContext';
false && fileFolderDrop;
export function ComposeBody(props: {
+ debugName?: string;
inputRef?: (el: HTMLDivElement) => void;
mobileScrollRef?: Accessor<HTMLElement | undefined>;
onAddFiles?: (files: File[]) => void;
@@ -80,14 +85,58 @@ export function ComposeBody(props: {
let bodyDiv!: HTMLDivElement;
+ const logComposeBody = (event: string, details?: Record<string, unknown>) => {
+ if (!props.debugName) return;
+ logger.log(`[ComposeBody] ${event}`, {
+ debugName: props.debugName,
+ ...details,
+ });
+ };
+
const captureEditor = (ed: LexicalEditor) => {
+ logComposeBody('captureEditor called');
setEditor(ed);
ctx.captureEditor(ed);
};
+ logComposeBody('mounted', {
+ initialHtmlLength: ctx.initialHtml()?.length ?? 0,
+ initialMarkdownLength: ctx.initialMarkdown?.()?.length ?? 0,
+ });
+
+ onCleanup(() => {
+ logComposeBody('unmounted');
+ });
+
+ createEffect(
+ on(
+ () => ctx.initialMarkdown?.(),
+ (next, prev) => {
+ logComposeBody('initialMarkdown changed', {
+ nextLength: next?.length ?? 0,
+ previousLength: prev?.length ?? 0,
+ });
+ },
+ { defer: true }
+ )
+ );
+
+ createEffect(
+ on(
+ () => ctx.initialHtml(),
+ (next, prev) => {
+ logComposeBody('initialHtml changed', {
+ nextLength: next?.length ?? 0,
+ previousLength: prev?.length ?? 0,
+ });
+ },
+ { defer: true }
+ )
+ );
+
return (
<>
- <div class="w-full h-full min-h-60 sm:max-h-full mobile:flex-1 flex flex-col">
+ <div class="w-full h-full min-h-0 sm:max-h-full mobile:flex-1 flex flex-col flex-1">
<div
class="grow w-full h-full flex flex-col cursor-text placeholder:text-ink-placeholder placeholder:opacity-50 overflow-auto"
ref={bodyDiv}
@@ -107,11 +156,13 @@ export function ComposeBody(props: {
<div class={cn('absolute inset-0', !isDragging() && 'hidden')}>
<FileDropOverlay>Drop file(s) to attach</FileDropOverlay>
</div>
+
<MarkdownTextarea
domRef={props.inputRef}
captureEditor={captureEditor}
scrollRef={props.mobileScrollRef}
initialHtml={ctx.initialHtml()}
+ initialValue={ctx.initialMarkdown?.()}
class="text-sm break-words text-ink mobile:overflow-auto h-auto"
editable={() => !ctx.disabled()}
placeholder="Use `@` to reference files"
diff --git a/js/app/packages/block-email/component/compose/ComposeContext.ts b/js/app/packages/block-email/component/compose/ComposeContext.ts
index 0e56f28fd7..37debd80fd 100644
--- a/js/app/packages/block-email/component/compose/ComposeContext.ts
+++ b/js/app/packages/block-email/component/compose/ComposeContext.ts
@@ -23,6 +23,7 @@ export interface ComposeContextValue {
attachments: () => DraftFormAttachment[];
sendTime: () => Date | null | undefined;
initialHtml: () => string | undefined;
+ initialMarkdown?: () => string | undefined;
// Form state (write)
setRecipients: (
@@ -39,12 +40,14 @@ export interface ComposeContextValue {
// Actions
onSend: () => void;
+ onSaveDraft?: () => void | Promise<void>;
onDelete?: () => void;
onSendTimeChange?: (date: Date | null) => void;
// Status
disabled: Accessor<boolean>;
isSending: Accessor<boolean>;
+ isSavingDraft?: Accessor<boolean>;
hasDraft: Accessor<boolean>;
// Validation
@@ -55,6 +58,8 @@ export interface ComposeContextValue {
// Recipients config
recipientOptions: () => Array<EmailRecipient>;
focusRecipientsOnMount: boolean;
+ includeSelf?: boolean;
+ hideAttachments?: boolean;
// Schedule send
scheduleSendDisabled?: Accessor<boolean>;
diff --git a/js/app/packages/block-email/component/compose/ComposeLayout.tsx b/js/app/packages/block-email/component/compose/ComposeLayout.tsx
index a20eb1da79..c775f7a18c 100644
--- a/js/app/packages/block-email/component/compose/ComposeLayout.tsx
+++ b/js/app/packages/block-email/component/compose/ComposeLayout.tsx
@@ -1,21 +1,11 @@
-import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
-import {
- SplitHeaderBadge,
- StaticSplitLabel,
-} from '@app/component/split-layout/components/SplitLabel';
-import { ClippedPanel } from '@core/component/ClippedPanel';
-import { EmailPermissionsBanner } from '@core/component/EmailPermissionsBanner';
+import { CircleSpinner } from '@core/component/CircleSpinner';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
-import { isMobile } from '@core/mobile/isMobile';
-import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';
-import { beveledCorners } from 'core/signal/beveledCorners';
import { createSignal, type JSX, onMount, Show, Suspense } from 'solid-js';
-import { CircleSpinner } from '@core/component/CircleSpinner';
+import { ComposeBody } from './ComposeBody';
import { useCompose } from './ComposeContext';
import { ComposeRecipients } from './ComposeRecipients';
import { ComposeSubject } from './ComposeSubject';
-import { ComposeBody } from './ComposeBody';
type ComposeLayoutRefs = {
directRecipientsSelector: HTMLElement | undefined;
@@ -26,16 +16,19 @@ type ComposeLayoutRefs = {
messageInput: HTMLElement | undefined;
};
+/**
+ * Pure UI layout for the email compose form.
+ * Renders recipients, subject, body, and toolbar.
+ * Does NOT render any split-panel chrome — the caller is responsible for that.
+ */
export function ComposeLayout(props: {
toolbar?: JSX.Element;
header?: JSX.Element;
- hasLinkError?: () => boolean;
- previewName?: () => string;
+ class?: string;
+ bodyDebugName?: string;
}) {
const ctx = useCompose();
- const hasLinkError = props.hasLinkError ?? (() => false);
-
const [refs, setRefs] = createSignal<ComposeLayoutRefs>({
directRecipientsSelector: undefined,
ccRecipientsSelector: undefined,
@@ -75,6 +68,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Edit "To" recipients',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
refs()?.directRecipientsSelector?.focus();
return true;
},
@@ -88,6 +82,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Edit "Cc" recipients',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
if (!showCc()) {
setShowCc(true);
queueMicrotask(() => refs()?.ccRecipientsSelector?.focus());
@@ -106,6 +101,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Edit "Bcc" recipients',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
if (!showBcc()) {
setShowBcc(true);
queueMicrotask(() => refs()?.bccRecipientsSelector?.focus());
@@ -124,6 +120,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Edit subject',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
refs()?.subjectInput?.focus();
return true;
},
@@ -137,6 +134,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Edit message',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
refs()?.messageInput?.focus();
return true;
},
@@ -150,6 +148,7 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Send email',
keyDownHandler: () => {
+ if (ctx.disabled()) return false;
if (ctx.sendTime()) return false;
ctx.onSend();
return true;
@@ -158,132 +157,85 @@ export function ComposeLayout(props: {
hotkeyToken: 'email.send',
displayPriority: 10,
});
-
return (
- <>
- <Show when={!isMobile()}>
- <SplitHeaderLeft>
- <StaticSplitLabel
- class="ph-no-capture"
- label={ctx.subject() || props.previewName?.() || 'Draft email'}
- iconType="email"
- badges={[
- <SplitHeaderBadge text="draft" tooltip="This is a Draft Email" />,
- ]}
- />
- </SplitHeaderLeft>
- </Show>
- <div
- ref={registerRef('containerRef')}
- class="relative flex flex-col w-full h-full min-h-0 overflow-hidden text-sm"
- >
- <Show when={hasLinkError()}>
- <EmailPermissionsBanner />
- </Show>
-
- <div
- ref={mobileScrollRef}
- class="macro-message-width sm:macro-message-padding mx-auto w-full max-h-full my-2 sm:my-12 mobile:my-0 px-2 sm:px-4 mobile:px-0 overflow-hidden mobile:overflow-y-auto mobile:hide-scrollbar mobile:min-h-full"
- classList={{
- 'pointer-events-none opacity-50': hasLinkError(),
- }}
- >
- <WrapUnlessMobile
- wrapper={(children) => (
- <ClippedPanel tl={!beveledCorners()}>{children}</ClippedPanel>
- )}
- >
- <div
- class="w-full p-4 bg-input max-h-full mobile:max-h-none overflow-y-auto flex flex-col min-h-0 mobile:min-h-full"
- classList={{
- 'pointer-events-none opacity-50': hasLinkError(),
- }}
- >
- <div class="macro-message-width mx-auto pb-1 w-full h-max shrink-0">
- <div class="mb-4 h-6 flex items-center justify-between">
- <Show
- when={props.header}
- fallback={
- <Suspense
- fallback={
- <div class="flex gap-1 items-center">
- <CircleSpinner class="w-4 h-4 animate-spin" />
- <span class="text-ink-extra-muted/50 text-xs">
- Processing...
- </span>
- </div>
- }
- >
- <Show when={ctx.fromAddress?.()}>
- {(addr) => (
- <div class="text-xs text-ink-extra-muted/50">
- from {addr()}
- </div>
- )}
- </Show>
- </Suspense>
- }
- >
- {props.header}
- </Show>
- <div class="flex gap-2 ml-auto">
- <Show when={!isCcVisible()}>
- <button
- type="button"
- class="text-ink-muted hover:text-ink hover:bg-hover"
- onClick={() => setShowCc(true)}
- disabled={hasLinkError()}
- >
- + Cc
- </button>
- </Show>
- <Show when={!isBccVisible()}>
- <button
- type="button"
- class="text-ink-muted hover:text-ink hover:bg-hover"
- onClick={() => setShowBcc(true)}
- disabled={hasLinkError()}
- >
- + Bcc
- </button>
- </Show>
+ <div ref={registerRef('containerRef')} class={props.class}>
+ <div class="pb-1 w-full h-max shrink-0">
+ <div class="mb-4 h-6 flex items-center justify-between">
+ <Show
+ when={props.header}
+ fallback={
+ <Suspense
+ fallback={
+ <div class="flex gap-1 items-center">
+ <CircleSpinner class="w-4 h-4 animate-spin" />
+ <span class="text-ink-extra-muted/50 text-xs">
+ Processing...
+ </span>
</div>
- </div>
-
- <ComposeRecipients
- toRef={registerRef('directRecipientsSelector')}
- ccRef={registerRef('ccRecipientsSelector')}
- bccRef={registerRef('bccRecipientsSelector')}
- showCc={showCc}
- setShowCc={setShowCc}
- showBcc={showBcc}
- setShowBcc={setShowBcc}
- />
-
- <ComposeSubject inputRef={registerRef('subjectInput')} />
- </div>
-
- <div
- class="w-full h-full flex flex-col min-h-0 mt-4"
- classList={{
- 'pointer-events-none opacity-50': hasLinkError(),
- }}
+ }
+ >
+ <Show when={ctx.fromAddress?.()}>
+ {(addr) => (
+ <div class="text-xs text-ink-extra-muted/50">
+ from {addr()}
+ </div>
+ )}
+ </Show>
+ </Suspense>
+ }
+ >
+ {props.header}
+ </Show>
+ <div class="flex gap-2 ml-auto">
+ <Show when={!isCcVisible()}>
+ <button
+ type="button"
+ class="text-ink-muted hover:text-ink hover:bg-hover"
+ onClick={() => setShowCc(true)}
+ disabled={ctx.disabled()}
+ >
+ + Cc
+ </button>
+ </Show>
+ <Show when={!isBccVisible()}>
+ <button
+ type="button"
+ class="text-ink-muted hover:text-ink hover:bg-hover"
+ onClick={() => setShowBcc(true)}
+ disabled={ctx.disabled()}
>
- <ComposeBody
- inputRef={registerRef('messageInput')}
- mobileScrollRef={() => mobileScrollRef}
- onAddFiles={(files) => {
- ctx.onAddAttachments(
- files.map((file) => ({ type: 'local', file }))
- );
- }}
- />
- {props.toolbar ?? ctx.toolbar?.()}
- </div>
- </div>
- </WrapUnlessMobile>
+ + Bcc
+ </button>
+ </Show>
+ </div>
</div>
+
+ <ComposeRecipients
+ toRef={registerRef('directRecipientsSelector')}
+ ccRef={registerRef('ccRecipientsSelector')}
+ bccRef={registerRef('bccRecipientsSelector')}
+ showCc={showCc}
+ setShowCc={setShowCc}
+ showBcc={showBcc}
+ setShowBcc={setShowBcc}
+ />
+
+ <ComposeSubject inputRef={registerRef('subjectInput')} />
+ </div>
+
+ <div class="w-full flex flex-col min-h-0 mt-4 h-full">
+ <ComposeBody
+ debugName={props.bodyDebugName}
+ inputRef={registerRef('messageInput')}
+ mobileScrollRef={() => mobileScrollRef}
+ onAddFiles={(files) => {
+ ctx.onAddAttachments(
+ files.map((file) => ({ type: 'local', file }))
+ );
+ }}
+ />
+ {props.toolbar ?? ctx.toolbar?.()}
</div>
- </>
+ </div>
);
}
diff --git a/js/app/packages/block-email/component/compose/ComposeRecipients.tsx b/js/app/packages/block-email/component/compose/ComposeRecipients.tsx
index bea504593f..bdc7fb729b 100644
--- a/js/app/packages/block-email/component/compose/ComposeRecipients.tsx
+++ b/js/app/packages/block-email/component/compose/ComposeRecipients.tsx
@@ -126,6 +126,7 @@ export function ComposeRecipients(props: {
hideBorder
noBrackets
disabled={ctx.disabled()}
+ includeSelf={ctx.includeSelf}
onChipDragStart={(option, e) => handleChipDragStart('to', option, e)}
onChipDragEnd={handleChipDragEnd}
/>
diff --git a/js/app/packages/block-email/component/compose/ComposeToolbar.tsx b/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
index 612c360b74..fe9a99d283 100644
--- a/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
+++ b/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
@@ -2,7 +2,6 @@ import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHe
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
import { EmailDateSelector } from '@block-email/component/email-date-selector';
import { MAX_ATTACHMENTS_BYTES_SIZE } from '@block-email/constants';
-import { Button } from '@ui/components/Button';
import { DropdownMenuContent, MenuItem } from '@core/component/Menu';
import { toast } from '@core/component/Toast/Toast';
import { Tooltip } from '@core/component/Tooltip';
@@ -19,6 +18,7 @@ import DotsThreeIcon from '@phosphor-icons/core/bold/dots-three-bold.svg?compone
import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
import PaperclipHorizontalIcon from '@phosphor-icons/core/regular/paperclip-horizontal.svg?component-solid';
+import { Button } from '@ui/components/Button';
import { defaultSelectionData } from 'core/component/LexicalMarkdown/plugins';
import {
NODE_TRANSFORM,
@@ -98,21 +98,23 @@ export function EmailComposeToolbar(props: {
}
>
<div class="flex flex-row items-center gap-2">
- <div class="relative" ref={attachButtonRef}>
- <Button
- ref={(el) =>
- fileSelector(el, () => ({
- multiple: true,
- onSelect: handleAddAttachments,
- }))
- }
- tooltip="Attach"
- class="aspect-square p-1"
- disabled={ctx.disabled()}
- >
- <PaperclipIcon class="h-5" />
- </Button>
- </div>
+ <Show when={!ctx.hideAttachments}>
+ <div class="relative" ref={attachButtonRef}>
+ <Button
+ ref={(el) =>
+ fileSelector(el, () => ({
+ multiple: true,
+ onSelect: handleAddAttachments,
+ }))
+ }
+ tooltip="Attach"
+ class="aspect-square p-1"
+ disabled={ctx.disabled()}
+ >
+ <PaperclipIcon class="h-5" />
+ </Button>
+ </div>
+ </Show>
<Button
variant="ghost"
size="icon-sm"
@@ -141,26 +143,43 @@ export function EmailComposeToolbar(props: {
</Show>
</div>
- <Tooltip
- tooltip={ctx.sendTime() ? 'Send time is scheduled' : undefined}
- >
- <button
- disabled={ctx.isSending() || ctx.disabled() || !!ctx.sendTime()}
- onClick={() => ctx.onSend()}
- class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent disabled:opacity-30"
+ <div class="flex items-center gap-2">
+ <Show when={ctx.onSaveDraft}>
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={
+ ctx.isSending() || ctx.isSavingDraft?.() || ctx.disabled()
+ }
+ onClick={() => void ctx.onSaveDraft?.()}
+ >
+ {ctx.isSavingDraft?.() ? 'Saving…' : 'Save Draft'}
+ </Button>
+ </Show>
+ <Tooltip
+ tooltip={ctx.sendTime() ? 'Send time is scheduled' : undefined}
>
- <Show
- when={!ctx.isSending()}
- fallback={
- <Spinner class="size-6 animate-spin cursor-disabled" />
+ <button
+ disabled={
+ ctx.isSending() ||
+ ctx.isSavingDraft?.() ||
+ ctx.disabled() ||
+ !!ctx.sendTime()
}
+ onClick={() => ctx.onSend()}
+ class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent disabled:opacity-30"
>
- <div class="group hover:bg-accent transition ease-in-out size-6 border border-accent rounded-full flex items-center justify-center p-0">
- <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />
- </div>
- </Show>
- </button>
- </Tooltip>
+ <Show
+ when={!ctx.isSending()}
+ fallback={<Spinner class="size-6 animate-spin" />}
+ >
+ <div class="group hover:bg-accent transition ease-in-out size-6 border border-accent rounded-full flex items-center justify-center p-0">
+ <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />
+ </div>
+ </Show>
+ </button>
+ </Tooltip>
+ </div>
</Show>
</div>
</>
@@ -202,8 +221,25 @@ function MobileToolbar(props: {
<Tooltip
tooltip={ctx.sendTime() ? 'Send time is scheduled' : undefined}
>
+ <Show when={ctx.onSaveDraft}>
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={
+ ctx.isSending() || ctx.isSavingDraft?.() || ctx.disabled()
+ }
+ onClick={() => void ctx.onSaveDraft?.()}
+ >
+ {ctx.isSavingDraft?.() ? 'Saving…' : 'Draft'}
+ </Button>
+ </Show>
<Button
- disabled={ctx.isSending() || ctx.disabled() || !!ctx.sendTime()}
+ disabled={
+ ctx.isSending() ||
+ ctx.isSavingDraft?.() ||
+ ctx.disabled() ||
+ !!ctx.sendTime()
+ }
onClick={() => ctx.onSend()}
>
<PaperPlane class="size-4.5 text-accent" />
diff --git a/js/app/packages/block-email/component/compose/index.ts b/js/app/packages/block-email/component/compose/index.ts
index 324d83b574..21f052ff50 100644
--- a/js/app/packages/block-email/component/compose/index.ts
+++ b/js/app/packages/block-email/component/compose/index.ts
@@ -1,11 +1,8 @@
export { EmailCompose } from './Compose';
-export { ComposeProvider, useCompose } from './ComposeContext';
-export type {
- ComposeContextValue,
- ComposeValidationError,
-} from './ComposeContext';
-export { ComposeLayout } from './ComposeLayout';
export { ComposeBody } from './ComposeBody';
+
+export * from './ComposeContext';
+export { ComposeLayout } from './ComposeLayout';
export { ComposeRecipients } from './ComposeRecipients';
export { ComposeSubject } from './ComposeSubject';
export { EmailComposeToolbar } from './ComposeToolbar';
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index f8ae29f788..c91a16afa8 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -91,7 +91,7 @@ export function createEmailFormState(
let replyingTo: ApiMessage | undefined;
if (purpose?.type === 'replying_to') {
- replyingTo = options?.getMessageByID(purpose.messageID);
+ replyingTo = options?.getMessageByID?.(purpose.messageID);
}
let draft: ApiMessage | undefined;
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
index c6d0c2f7e7..b414e33eec 100644
--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
@@ -1,7 +1,7 @@
import { useSplitLayout } from '@app/component/split-layout/layout';
-import { generateTitle } from '@service-cognition/client';
import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
import { RenderTool } from '@core/component/AI/component/tool/handler';
+import { useChatContext } from '@core/component/AI/context';
import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';
import { ENABLE_TTFT } from '@core/constant/featureFlags';
import { createMarkdownFile } from '@core/util/create';
@@ -10,13 +10,13 @@ import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid'
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
+import { generateTitle } from '@service-cognition/client';
import type { AssistantMessagePart } from '@service-cognition/generated/schemas/assistantMessagePart';
import type { ChatMessageContent } from '@service-cognition/generated/schemas/chatMessageContent';
import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas/chatMessageWithAttachments';
import { createCallback } from '@solid-primitives/rootless';
import {
createMemo,
- createSelector,
createSignal,
For,
Match,
@@ -24,6 +24,7 @@ import {
Show,
Switch,
} from 'solid-js';
+import { match } from 'ts-pattern';
function messageContentIsEmpty(content: ChatMessageContent) {
if (typeof content === 'string' || Array.isArray(content)) {
@@ -298,7 +299,6 @@ function pairToolCalls(parts: AssistantMessagePart[]): AssistantMessagePart[] {
return pairParts(parts.slice(1), newParts);
}
}
-
return pairParts(parts, []);
}
@@ -324,23 +324,7 @@ function AssistantMessageParts(props: {
message: ChatMessageWithAttachments;
isStreaming: boolean;
}) {
- // const chatId = chatStore.get.id;
- // if (!chatId) return;
- const completedToolIds = createMemo(() => {
- const ids = new Set<string>();
- for (const part of props.parts) {
- if (part.type === 'toolCallResponseJson' || part.type === 'toolCallErr') {
- ids.add(part.id);
- }
- }
- return ids;
- });
-
- const isCompleteSelector = createSelector(
- completedToolIds,
- (id: string, completed) => completed.has(id)
- );
-
+ const chat = useChatContext();
const parts = createMemo(() => {
return pairToolCalls(props.parts);
});
@@ -369,67 +353,69 @@ function AssistantMessageParts(props: {
{(part, i) => {
const currentPart = () => part();
if (!currentPart()) return null;
+ const previousPart = () => stableParts()[i() - 1]?.();
- if (currentPart()!.type === 'toolCall') {
- const toolCall = () =>
- currentPart()! as Extract<
- AssistantMessagePart,
- { type: 'toolCall' }
- >;
-
- return (
+ return match(currentPart()!)
+ .with({ type: 'toolCall' }, (toolCall) => (
<RenderTool
- tool_id={toolCall().id}
- chat_id={'todo'}
- json={toolCall().json}
- name={toolCall().name}
+ tool_id={toolCall.id}
+ chat_id={chat.chatId()}
+ tool_call={toolCall.json}
+ name={toolCall.name}
message_id={props.message.id}
part_index={i()}
type="call"
- isComplete={isCompleteSelector(toolCall().id)}
- renderContext={{
- renderContext: {
- isStreaming: props.isStreaming,
- },
- }}
- />
- );
- } else if (currentPart()!.type === 'toolCallResponseJson') {
- const toolResponse = () =>
- currentPart()! as Extract<
- AssistantMessagePart,
- { type: 'toolCallResponseJson' }
- >;
-
- return (
- <RenderTool
- isComplete={true}
- tool_id={toolResponse().id}
- chat_id={'todo'}
- json={toolResponse().json}
- name={toolResponse().name}
- message_id={props.message.id}
- part_index={i()}
- type="response"
renderContext={{
renderContext: {
isStreaming: props.isStreaming,
},
}}
/>
- );
- } else if (currentPart()!.type === 'text') {
- const textPart = () =>
- currentPart()! as Extract<AssistantMessagePart, { type: 'text' }>;
+ ))
+ .with({ type: 'toolCallResponseJson' }, (toolResponse) => {
+ const callPart = previousPart();
+ if (
+ callPart?.type !== 'toolCall' ||
+ callPart.id !== toolResponse.id
+ ) {
+ return null;
+ }
+
+ return (
+ <RenderTool
+ tool_id={toolResponse.id}
+ chat_id={chat.chatId()}
+ call_part_index={i() - 1}
+ name={toolResponse.name}
+ message_id={props.message.id}
+ part_index={i()}
+ tool_call={callPart.json}
+ tool_response={toolResponse.json}
+ type="response"
+ renderContext={{
+ renderContext: {
+ isStreaming: props.isStreaming,
+ },
+ }}
+ />
+ );
+ })
+ .with({ type: 'toolCallErr' }, (toolError) => (
+ <div class="px-2 py-1 text-sm text-ink-muted">
+ Tool `{toolError.name}` failed: {toolError.description}
+ </div>
+ ))
+ .with({ type: 'text' }, (textPart) => {
+ if (textPart.text.trim().length === 0) return null;
- if (textPart().text.trim().length > 0)
return (
<ChatMessageMarkdown
- text={textPart().text}
+ text={textPart.text}
generating={() => props.isStreaming}
/>
);
- }
+ })
+ .exhaustive();
}}
</For>
);
diff --git a/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx
index d73a32cbd4..af0366af88 100644
--- a/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx
+++ b/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx
@@ -103,7 +103,8 @@ const handler = createToolRenderer({
),
renderResponse: (ctx) => {
const isError =
- ctx.tool.data.content.type === 'bash_code_execution_tool_result_error';
+ ctx.toolResponse.tool.data.content.type ===
+ 'bash_code_execution_tool_result_error';
return (
<BaseTool renderContext={ctx.renderContext} type="response">
<Switch>
@@ -112,7 +113,9 @@ const handler = createToolRenderer({
</Match>
<Match when={!isError}>
<BashResult
- result={ctx.tool.data.content as BashCodeExecutionResult}
+ result={
+ ctx.toolResponse.tool.data.content as BashCodeExecutionResult
+ }
/>
</Match>
</Switch>
diff --git a/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx
index cb9542201b..4a2c15e72f 100644
--- a/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx
+++ b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx
@@ -15,7 +15,7 @@ const handler = createToolRenderer({
),
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
- <ItemPreview id={ctx.tool.data.documentId} type="document" />
+ <ItemPreview id={ctx.toolResponse.tool.data.documentId} type="document" />
</BaseTool>
),
});
diff --git a/js/app/packages/core/component/AI/component/tool/GetThread.tsx b/js/app/packages/core/component/AI/component/tool/GetThread.tsx
new file mode 100644
index 0000000000..9d37ba73ec
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/GetThread.tsx
@@ -0,0 +1,15 @@
+import EnvelopeOpen from '@phosphor-icons/core/regular/envelope-open.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'GetThread',
+ renderCall: (ctx) => (
+ <BaseTool icon={EnvelopeOpen} renderContext={ctx.renderContext} type="call">
+ Read thread
+ </BaseTool>
+ ),
+ renderResponse: (_) => undefined,
+});
+
+export const getThreadHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
index ddd75e8545..c051d9d859 100644
--- a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx
@@ -187,8 +187,8 @@ const handler = createToolRenderer({
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
<ListEntitiesToolResponse
- items={ctx.tool.data.items}
- summary={ctx.tool.data.summary}
+ items={ctx.toolResponse.tool.data.items}
+ summary={ctx.toolResponse.tool.data.summary}
/>
</BaseTool>
),
diff --git a/js/app/packages/core/component/AI/component/tool/Properties.tsx b/js/app/packages/core/component/AI/component/tool/Properties.tsx
index dd00d343e3..ae5678d0bd 100644
--- a/js/app/packages/core/component/AI/component/tool/Properties.tsx
+++ b/js/app/packages/core/component/AI/component/tool/Properties.tsx
@@ -13,7 +13,7 @@ const getHandler = createToolRenderer({
),
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
- {ctx.tool.data.summary}
+ {ctx.toolResponse.tool.data.summary}
</BaseTool>
),
});
@@ -28,7 +28,7 @@ const setHandler = createToolRenderer({
),
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
- {ctx.tool.data.message}
+ {ctx.toolResponse.tool.data.message}
</BaseTool>
),
});
diff --git a/js/app/packages/core/component/AI/component/tool/Search.tsx b/js/app/packages/core/component/AI/component/tool/Search.tsx
index 353ee2361b..7b95c36417 100644
--- a/js/app/packages/core/component/AI/component/tool/Search.tsx
+++ b/js/app/packages/core/component/AI/component/tool/Search.tsx
@@ -336,7 +336,9 @@ const createHandler = (name: 'NameSearch' | 'ContentSearch') =>
),
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
- <UnifiedSearchToolResponse results={ctx.tool.data.results} />
+ <UnifiedSearchToolResponse
+ results={ctx.toolResponse.tool.data.results}
+ />
</BaseTool>
),
});
diff --git a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx
new file mode 100644
index 0000000000..67251d3cd7
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx
@@ -0,0 +1,241 @@
+import { ComposeTool } from './email/ChatCompose';
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import { ItemPreview } from '@core/component/ItemPreview';
+import { EntityIcon } from '@core/component/EntityIcon';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import CaretRight from '@icon/regular/caret-right.svg';
+import { Match, Switch } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+import { cn } from '@ui/utils/classname';
+import type { SendEmail } from '@service-cognition/generated/tools/types';
+
+type SendEmailResponse = NamedTool<'SendEmail', 'response'>['data'];
+
+function getRecipientsLabel(data: SendEmail) {
+ const recipients = [...data.to, ...data.cc, ...data.bcc];
+ const labels = Array.from(
+ new Map(
+ recipients.map((recipient) => [
+ recipient.email,
+ recipient.name?.trim() || recipient.email,
+ ])
+ ).values()
+ );
+
+ if (labels.length === 0) return 'recipient';
+ if (labels.length === 1) return labels[0]!;
+ if (labels.length === 2) return `${labels[0]} and ${labels[1]}`;
+ return `${labels[0]}, ${labels[1]}, +${labels.length - 2} more`;
+}
+
+function getUserAction(response: SendEmailResponse) {
+ if (
+ typeof response === 'object' &&
+ response !== null &&
+ 'UserAction' in response
+ ) {
+ return response.UserAction;
+ }
+
+ return null;
+}
+
+function getSentResponse(response: SendEmailResponse) {
+ const userAction = getUserAction(response);
+ if (
+ typeof userAction === 'object' &&
+ userAction !== null &&
+ 'sent' in userAction
+ ) {
+ return userAction.sent;
+ }
+
+ return null;
+}
+
+function getDraftResponse(response: SendEmailResponse) {
+ const userAction = getUserAction(response);
+ if (
+ typeof userAction === 'object' &&
+ userAction !== null &&
+ 'convertedToDraft' in userAction
+ ) {
+ const draft = userAction.convertedToDraft;
+ if (
+ typeof draft === 'object' &&
+ draft !== null &&
+ 'draft_id' in draft &&
+ typeof draft.draft_id === 'string'
+ ) {
+ return {
+ draft_id: draft.draft_id,
+ thread_id:
+ 'thread_id' in draft && typeof draft.thread_id === 'string'
+ ? draft.thread_id
+ : undefined,
+ };
+ }
+ }
+
+ return null;
+}
+
+function DraftPreviewButton(props: {
+ draftId: string;
+ subject: string;
+ threadId?: string;
+}) {
+ const { replaceOrInsertSplit } = useSplitLayout();
+
+ return (
+ <button
+ class="text-ink-base text-sm ring-1 ring-edge-muted rounded-xs hover:bg-panel-hover flex flex-row h-6 px-2 justify-center items-center"
+ onClick={() =>
+ replaceOrInsertSplit({
+ ...(props.threadId
+ ? { type: 'email' as const, id: props.threadId }
+ : {
+ type: 'component' as const,
+ id: 'email-compose',
+ params: { draftID: props.draftId },
+ }),
+ })
+ }
+ >
+ <div class="flex justify-start items-center w-3.5 h-3.5 mr-2">
+ <EntityIcon targetType="email" size="xs" />
+ </div>
+ <div class="flex-1 text-left leading-5 min-w-0 truncate">
+ {props.subject || 'Draft email'}
+ </div>
+ </button>
+ );
+}
+
+function SentEmailResponse(props: {
+ args: SendEmail;
+ chatId: string;
+ messageId: string;
+ renderContext: Parameters<typeof BaseTool>[0]['renderContext'];
+ threadId: string;
+ toolCallId: string;
+}) {
+ return (
+ <details class="group">
+ <summary class="list-none [&::-webkit-details-marker]:hidden">
+ <BaseTool renderContext={props.renderContext} type="response">
+ <div class="flex items-center justify-between gap-3 text-sm text-ink">
+ <div class="flex min-w-0 flex-wrap items-center gap-2">
+ <span class="text-base">{`Email sent to ${getRecipientsLabel(props.args)}`}</span>
+ <ItemPreview id={props.threadId} type="email" />
+ </div>
+ <span class="shrink-0 text-ink-muted">
+ <CaretRight
+ class={cn(
+ 'h-4 w-4 transition-transform',
+ 'group-open:rotate-90'
+ )}
+ />
+ </span>
+ </div>
+ </BaseTool>
+ </summary>
+ <div class="mt-3">
+ <ComposeTool
+ chatId={props.chatId}
+ initialData={props.args}
+ messageId={props.messageId}
+ toolCallId={props.toolCallId}
+ readOnly
+ header={<div class="text-xs text-ink-extra-muted/60">Email sent</div>}
+ />
+ </div>
+ </details>
+ );
+}
+
+function DraftEmailResponse(props: {
+ args: SendEmail;
+ draftId: string;
+ renderContext: Parameters<typeof BaseTool>[0]['renderContext'];
+ threadId?: string;
+}) {
+ return (
+ <BaseTool renderContext={props.renderContext} type="response">
+ <div class="flex items-center justify-between gap-3 text-sm text-ink">
+ <div class="flex min-w-0 flex-wrap items-center gap-2">
+ <span class="text-base">{`Email saved as draft for ${getRecipientsLabel(props.args)}`}</span>
+ <DraftPreviewButton
+ draftId={props.draftId}
+ subject={props.args.subject}
+ threadId={props.threadId}
+ />
+ </div>
+ </div>
+ </BaseTool>
+ );
+}
+
+const handler = createToolRenderer({
+ name: 'SendEmail',
+ renderCall: () => undefined,
+ renderResponse: (ctx) => {
+ const response = ctx.toolResponse.tool.data;
+ const args = ctx.toolCall.tool.data;
+ const userAction = getUserAction(response);
+ const sentResponse = getSentResponse(response);
+ const draftResponse = getDraftResponse(response);
+
+ return (
+ <Switch>
+ <Match
+ when={
+ response === 'PendingUserExecution' || userAction === 'userEdited'
+ }
+ >
+ <ComposeTool
+ chatId={ctx.toolResponse.chat_id}
+ initialData={ctx.toolCall.tool.data}
+ messageId={ctx.toolResponse.message_id}
+ toolCallId={ctx.toolCall.tool.id}
+ streamLocked={ctx.renderContext.isStreaming}
+ header={
+ ctx.renderContext.isStreaming ? (
+ <div class="text-xs text-ink-extra-muted/60">
+ Waiting for the response to finish before this email can be
+ edited.
+ </div>
+ ) : undefined
+ }
+ />
+ </Match>
+ <Match when={response === 'Rejected'}>
+ <BaseTool renderContext={ctx.renderContext} type="response">
+ Email send rejected
+ </BaseTool>
+ </Match>
+ <Match when={sentResponse}>
+ <SentEmailResponse
+ args={args}
+ chatId={ctx.toolResponse.chat_id}
+ messageId={ctx.toolResponse.message_id}
+ renderContext={ctx.renderContext}
+ threadId={sentResponse!.thread_id}
+ toolCallId={ctx.toolCall.tool.id}
+ />
+ </Match>
+ <Match when={draftResponse}>
+ <DraftEmailResponse
+ args={args}
+ draftId={draftResponse!.draft_id}
+ renderContext={ctx.renderContext}
+ threadId={draftResponse!.thread_id}
+ />
+ </Match>
+ </Switch>
+ );
+ },
+});
+
+export const sendEmailHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
index 34293132ff..bc3d5cf66c 100644
--- a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
+++ b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
@@ -33,19 +33,12 @@ type TextEditorCodeExecutionStrReplaceResult = TextEditorCodeExecutionResult & {
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
-// Store file creation data from tool calls to use when handling responses
-type FileCreationData = {
- path: string;
- fileText: string;
-};
-
type CreatedFileInfo = {
documentId: string;
fileName: string;
extension: string;
};
-const toolFileDataMap: Record<string, FileCreationData> = {};
const createdFilesMap: Record<string, CreatedFileInfo> = {};
function getExtensionFromPath(path: string): string | null {
@@ -245,32 +238,20 @@ function TextEditorResult(props: {
const handler = createToolRenderer({
name: 'text_editor_code_execution',
- handleCall: async (ctx) => {
- // Store file creation data for use in handleResponse
- if (ctx.tool.data.command === 'create' && ctx.tool.data.file_text) {
- toolFileDataMap[ctx.tool.id] = {
- path: ctx.tool.data.path,
- fileText: ctx.tool.data.file_text,
- };
- }
- },
handleResponse: async (ctx) => {
- const { content } = ctx.tool.data;
+ const { content } = ctx.toolResponse.tool.data;
+ const { command, file_text: fileText, path } = ctx.toolCall.tool.data;
// Only create macro files for successful file creations
- if (content.type !== 'text_editor_code_execution_create_result') {
+ if (
+ content.type !== 'text_editor_code_execution_create_result' ||
+ command !== 'create' ||
+ !fileText
+ ) {
return;
}
- const fileData = toolFileDataMap[ctx.tool.id];
- if (!fileData) {
- return;
- }
-
- // Clean up stored data
- delete toolFileDataMap[ctx.tool.id];
-
- const extension = getExtensionFromPath(fileData.path);
+ const extension = getExtensionFromPath(path);
if (!extension || !allSupportedExtensionSet.has(extension)) {
return;
}
@@ -280,17 +261,17 @@ const handler = createToolRenderer({
return;
}
- const fileName = getFileNameFromPath(fileData.path);
+ const fileName = getFileNameFromPath(path);
const result = await createCodeFileFromText({
- code: fileData.fileText,
+ code: fileText,
extension: extension as CodeFileExtension,
title: fileName,
});
if (isOk(result)) {
const documentId = result[1].documentId;
- createdFilesMap[ctx.tool.id] = {
+ createdFilesMap[ctx.toolResponse.tool.id] = {
documentId,
fileName,
extension,
@@ -298,7 +279,7 @@ const handler = createToolRenderer({
// Persist the mapping to the backend for retrieval on chat refresh
await cognitionApiServiceClient.createIdMapping({
- source_id: ctx.tool.id,
+ source_id: ctx.toolResponse.tool.id,
target_id: JSON.stringify({ documentId, fileName, extension }),
});
}
@@ -312,8 +293,8 @@ const handler = createToolRenderer({
return (
<BaseTool renderContext={ctx.renderContext} type="response">
<TextEditorResult
- content={ctx.tool.data.content}
- toolId={ctx.tool.id}
+ content={ctx.toolResponse.tool.data.content}
+ toolId={ctx.toolResponse.tool.id}
/>
</BaseTool>
);
diff --git a/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx b/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx
index 3f6d09d9f0..fad307603d 100644
--- a/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx
+++ b/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx
@@ -1,7 +1,7 @@
+import type { Component } from 'solid-js';
import type {
NamedTool,
ToolContext,
- ToolHandler,
ToolName,
} from '@service-cognition/generated/tools/tool';
@@ -11,36 +11,66 @@ export type RenderContext = {
};
};
-import type { Component } from 'solid-js';
+export type ToolCallContext<TName extends ToolName = ToolName> = ToolContext<
+ NamedTool<TName, 'call'>
+>;
+
+export type ToolResponseContext<TName extends ToolName = ToolName> =
+ ToolContext<NamedTool<TName, 'response'>>;
-export interface ToolRendererConfig<TName extends ToolName, RenderContext> {
+export type ToolResponseRenderContext<TName extends ToolName = ToolName> = {
+ toolCall: ToolCallContext<TName>;
+ toolResponse: ToolResponseContext<TName>;
+};
+
+export interface ToolRendererHandler<
+ TContext extends Record<string, unknown>,
+ TRenderContext extends Record<string, unknown>,
+> {
+ handle?: (context: TContext) => void | Promise<void>;
+ render?: Component<TContext & TRenderContext>;
+}
+
+export interface AnyToolRenderer<
+ TRenderContext extends Record<string, unknown>,
+> {
+ call: ToolRendererHandler<ToolCallContext, TRenderContext>;
+ response: ToolRendererHandler<ToolResponseRenderContext, TRenderContext>;
+}
+
+export type ToolRendererMap<TRenderContext extends Record<string, unknown>> =
+ Record<ToolName, AnyToolRenderer<TRenderContext>>;
+
+export interface ToolRendererConfig<
+ TName extends ToolName,
+ TRenderContext extends Record<string, unknown>,
+> {
name: TName;
- renderCall: Component<ToolContext<NamedTool<TName, 'call'>> & RenderContext>;
- renderResponse: Component<
- ToolContext<NamedTool<TName, 'response'>> & RenderContext
- >;
- handleCall?: (
- context: ToolContext<NamedTool<TName, 'call'>>
- ) => void | Promise<void>;
+ renderCall: Component<ToolCallContext<TName> & TRenderContext>;
+ renderResponse: Component<ToolResponseRenderContext<TName> & TRenderContext>;
+ handleCall?: (context: ToolCallContext<TName>) => void | Promise<void>;
handleResponse?: (
- context: ToolContext<NamedTool<TName, 'response'>>
+ context: ToolResponseRenderContext<TName>
) => void | Promise<void>;
}
export function createToolRenderer<TName extends ToolName>(
config: ToolRendererConfig<TName, RenderContext>
-) {
- const callHandler: ToolHandler<NamedTool<TName, 'call'>, RenderContext> = {
- render: config.renderCall,
- handle: config.handleCall,
+): AnyToolRenderer<RenderContext> {
+ const callHandler: AnyToolRenderer<RenderContext>['call'] = {
+ render: config.renderCall as Component<ToolCallContext & RenderContext>,
+ handle: config.handleCall as
+ | ((context: ToolCallContext) => void | Promise<void>)
+ | undefined,
};
- const responseHandler: ToolHandler<
- NamedTool<TName, 'response'>,
- RenderContext
- > = {
- render: config.renderResponse,
- handle: config.handleResponse,
+ const responseHandler: AnyToolRenderer<RenderContext>['response'] = {
+ render: config.renderResponse as Component<
+ ToolResponseRenderContext & RenderContext
+ >,
+ handle: config.handleResponse as
+ | ((context: ToolResponseRenderContext) => void | Promise<void>)
+ | undefined,
};
return {
diff --git a/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx b/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx
new file mode 100644
index 0000000000..5f0c0b9b22
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx
@@ -0,0 +1,15 @@
+import TagSimple from '@phosphor-icons/core/regular/tag-simple.svg';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'UpdateThreadLabels',
+ renderCall: (ctx) => (
+ <BaseTool icon={TagSimple} renderContext={ctx.renderContext} type="call">
+ {ctx.tool.data.add ? 'Add' : 'Remove'} label on thread
+ </BaseTool>
+ ),
+ renderResponse: (_) => undefined,
+});
+
+export const updateThreadLabelsHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/WebSearch.tsx b/js/app/packages/core/component/AI/component/tool/WebSearch.tsx
index 2d1dc77fb4..d9c7a2abc1 100644
--- a/js/app/packages/core/component/AI/component/tool/WebSearch.tsx
+++ b/js/app/packages/core/component/AI/component/tool/WebSearch.tsx
@@ -13,7 +13,7 @@ const handler = createToolRenderer({
renderResponse: (ctx) => (
<BaseTool renderContext={ctx.renderContext} type="response">
<UnfurledLinkCollection
- links={ctx.tool.data.content.map((result) => ({
+ links={ctx.toolResponse.tool.data.content.map((result) => ({
title: result.title,
url: result.url,
}))}
diff --git a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
new file mode 100644
index 0000000000..d8d6878ca0
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx
@@ -0,0 +1,384 @@
+import {
+ ComposeLayout,
+ EmailComposeToolbar,
+} from '@block-email/component/compose';
+import {
+ type ComposeContextValue,
+ ComposeProvider,
+ type ComposeValidationError,
+} from '@block-email/component/compose/ComposeContext';
+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';
+import type { EmailRecipient } from '@block-email/component/EmailContext';
+import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';
+import { useChatContext } from '@core/component/AI/context';
+import type { AssistantMessagePart } from '@core/component/AI/types';
+import { toast } from '@core/component/Toast/Toast';
+import { isErr } from '@core/util/maybeResult';
+import { useChatQuery } from '@queries/chat';
+import { useEmailLinksQuery } from '@queries/email/link';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import type { SendEmail } from '@service-cognition/generated/tools/types';
+import { debounce } from '@solid-primitives/scheduled';
+import type { LexicalEditor } from 'lexical';
+import { createSignal, type JSX, Show } from 'solid-js';
+
+type ComposeToolProps = {
+ chatId: string;
+ messageId: string;
+ toolCallId: string;
+ initialData: SendEmail;
+ recipientOptions?: EmailRecipient[];
+ header?: JSX.Element;
+ readOnly?: boolean;
+ streamLocked?: boolean;
+};
+
+type SendEmailSnapshot = {
+ bcc: Array<{ email: string; name: string | null }>;
+ body: string;
+ cc: Array<{ email: string; name: string | null }>;
+ replyingToId: string | null;
+ subject: string;
+ to: Array<{ email: string; name: string | null }>;
+};
+
+function toEmailRecipients(
+ items: Array<{ email: string; name: string | null }>
+): EmailRecipient[] {
+ return items.map(convertContactInfoToEmailRecipient);
+}
+
+function fromEmailRecipients(
+ items: EmailRecipient[]
+): Array<{ email: string; name: string | null }> {
+ return items.map((recipient) => {
+ const email = 'email' in recipient.data ? recipient.data.email : '';
+ const name =
+ 'name' in recipient.data ? (recipient.data.name ?? null) : null;
+ return { email, name };
+ });
+}
+
+function createSendEmailSnapshot(data: SendEmail): SendEmailSnapshot {
+ return {
+ to: (data.to ?? []).map((item) => ({
+ email: item.email,
+ name: item.name ?? null,
+ })),
+ cc: (data.cc ?? []).map((item) => ({
+ email: item.email,
+ name: item.name ?? null,
+ })),
+ bcc: (data.bcc ?? []).map((item) => ({
+ email: item.email,
+ name: item.name ?? null,
+ })),
+ subject: data.subject ?? '',
+ body: data.body ?? '',
+ replyingToId: data.replyingToId ?? null,
+ };
+}
+
+function sameSendEmailSnapshot(
+ left: SendEmailSnapshot,
+ right: SendEmailSnapshot
+) {
+ return JSON.stringify(left) === JSON.stringify(right);
+}
+
+function getSentToolResponse(result: unknown): {
+ message_id: string;
+ thread_id: string;
+} | null {
+ if (typeof result !== 'object' || result === null) return null;
+
+ if (
+ 'UserAction' in result &&
+ typeof result.UserAction === 'object' &&
+ result.UserAction !== null &&
+ 'sent' in result.UserAction &&
+ typeof result.UserAction.sent === 'object' &&
+ result.UserAction.sent !== null &&
+ 'message_id' in result.UserAction.sent &&
+ 'thread_id' in result.UserAction.sent &&
+ typeof result.UserAction.sent.message_id === 'string' &&
+ typeof result.UserAction.sent.thread_id === 'string'
+ ) {
+ return {
+ message_id: result.UserAction.sent.message_id,
+ thread_id: result.UserAction.sent.thread_id,
+ };
+ }
+
+ return null;
+}
+
+function toSentResponse(messageId: string, threadId: string) {
+ return {
+ UserAction: {
+ sent: {
+ message_id: messageId,
+ thread_id: threadId,
+ },
+ },
+ } as const;
+}
+
+function updateToolParts(
+ parts: AssistantMessagePart[],
+ args: SendEmail,
+ response: unknown,
+ toolCallId: string
+) {
+ let changed = false;
+
+ const nextParts = parts.map((part) => {
+ if (part.type === 'toolCall' && part.id === toolCallId) {
+ changed = true;
+ return { ...part, json: args };
+ }
+
+ if (part.type === 'toolCallResponseJson' && part.id === toolCallId) {
+ changed = true;
+ return { ...part, json: response };
+ }
+
+ return part;
+ });
+
+ return changed ? nextParts : parts;
+}
+
+export function ComposeTool(props: ComposeToolProps) {
+ const chat = useChatContext();
+ const chatQuery = useChatQuery(() => props.chatId);
+ const isOwner = () => chatQuery.data?.userAccessLevel === 'owner';
+ const ownerGateDisabled = () => !chatQuery.isSuccess || !isOwner();
+ const showOwnerDisabledMessage = () =>
+ chatQuery.isSuccess && !isOwner() && props.readOnly !== true;
+ const uiDisabled = () =>
+ ownerGateDisabled() ||
+ props.readOnly === true ||
+ props.streamLocked === true;
+ const emailLinksQuery = useEmailLinksQuery();
+ const fromAddress = () => {
+ const links = emailLinksQuery.data?.links;
+ return links && links.length > 0 ? links[0].email_address : undefined;
+ };
+
+ const [recipients, setRecipients] = createSignal({
+ to: toEmailRecipients(props.initialData.to ?? []),
+ cc: toEmailRecipients(props.initialData.cc ?? []),
+ bcc: toEmailRecipients(props.initialData.bcc ?? []),
+ });
+ const [subject, setSubject] = createSignal(props.initialData.subject ?? '');
+ const [body, setBody] = createSignal(props.initialData.body ?? '');
+ const [isSending, setIsSending] = createSignal(false);
+ const [editor, setEditor] = createSignal<LexicalEditor>();
+ const [validationErrors, setValidationErrors] = createSignal<
+ ComposeValidationError[]
+ >([]);
+ let toolFinalized = false;
+ let lastPersistedSnapshot = createSendEmailSnapshot(props.initialData);
+
+ function collectArgs(): SendEmail {
+ return {
+ to: fromEmailRecipients(recipients().to),
+ cc: fromEmailRecipients(recipients().cc),
+ bcc: fromEmailRecipients(recipients().bcc),
+ subject: subject(),
+ body: body(),
+ replyingToId: props.initialData.replyingToId,
+ };
+ }
+
+ function validate(): boolean {
+ const errors: ComposeValidationError[] = [];
+
+ if (recipients().to.length === 0) {
+ errors.push({
+ type: 'no_recipient',
+ message: 'Add at least one recipient',
+ });
+ }
+
+ if (!body().trim()) {
+ errors.push({ type: 'no_message', message: 'Write a message' });
+ }
+
+ setValidationErrors(errors);
+ return errors.length === 0;
+ }
+
+ const debouncedUpdate = debounce(flushUpdate, 150);
+
+ function scheduleUpdate() {
+ if (toolFinalized) return;
+ debouncedUpdate();
+ }
+
+ async function flushUpdate() {
+ if (toolFinalized) return;
+
+ const args = collectArgs();
+ const nextSnapshot = createSendEmailSnapshot(args);
+
+ if (sameSendEmailSnapshot(nextSnapshot, lastPersistedSnapshot)) {
+ return;
+ }
+
+ const updateCallResult =
+ await cognitionApiServiceClient.updateToolCall<'SendEmail'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ });
+
+ if (isErr(updateCallResult)) {
+ toast.failure('Failed to save changes');
+ return;
+ }
+
+ const updateResponseResult =
+ await cognitionApiServiceClient.updateToolResponse<'SendEmail'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ response: { UserAction: 'userEdited' },
+ });
+
+ if (isErr(updateResponseResult)) {
+ toast.failure('Failed to save changes');
+ return;
+ }
+
+ lastPersistedSnapshot = nextSnapshot;
+ }
+
+ async function handleSend() {
+ if (ownerGateDisabled()) return;
+ if (!validate()) return;
+
+ setIsSending(true);
+ const args = collectArgs();
+
+ const result = await cognitionApiServiceClient.callTool<'SendEmail'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ });
+
+ setIsSending(false);
+
+ if (isErr(result)) {
+ toast.failure('Failed to send email');
+ return;
+ }
+
+ const sentResponse = getSentToolResponse(result[1]);
+ if (sentResponse) {
+ toolFinalized = true;
+ chat.setMessages((messages) =>
+ messages.map((message) => {
+ if (
+ message.id !== props.messageId ||
+ !Array.isArray(message.content)
+ ) {
+ return message;
+ }
+
+ const content = updateToolParts(
+ message.content,
+ args,
+ toSentResponse(sentResponse.message_id, sentResponse.thread_id),
+ props.toolCallId
+ );
+
+ if (content === message.content) return message;
+ return { ...message, content };
+ })
+ );
+ }
+
+ toast.success('Email sent');
+ }
+
+ const ctx: ComposeContextValue = {
+ subject,
+ attachments: () => [],
+ sendTime: () => undefined,
+ initialHtml: () => undefined,
+ initialMarkdown: () => props.initialData.body,
+ setRecipients: (field, value) => {
+ setRecipients((prev) => ({ ...prev, [field]: value }));
+ scheduleUpdate();
+ },
+ setSubject: (value) => {
+ setSubject(value);
+ scheduleUpdate();
+ },
+ onContentChange: (content) => {
+ setBody(content);
+ scheduleUpdate();
+ },
+ onAddAttachments: (_: DraftFormAttachment[]) => {},
+ onRemoveAttachment: (_: DraftFormAttachment) => {},
+ captureEditor: setEditor,
+ onSend: handleSend,
+ disabled: () =>
+ isSending() ||
+ ownerGateDisabled() ||
+ props.readOnly === true ||
+ props.streamLocked === true,
+ isSending,
+ isSavingDraft: () => false,
+ hasDraft: () => false,
+ hasPaidAccess: () => true,
+ focusRecipientsOnMount: false,
+ includeSelf: true,
+ hideAttachments: true,
+ recipientOptions: () => [
+ ...recipients().to,
+ ...recipients().cc,
+ ...recipients().bcc,
+ ...(props.recipientOptions ?? []),
+ ],
+ validationError: (type) => validationErrors().find((e) => e.type === type),
+ fromAddress,
+ recipients,
+ };
+
+ return (
+ <ComposeProvider value={ctx}>
+ <div class="relative">
+ <ComposeLayout
+ bodyDebugName={`chat-compose:${props.chatId}:${props.messageId}:${props.toolCallId}`}
+ class={`flex flex-col w-full text-sm border border-edge-muted rounded-lg p-4 bg-input ${
+ uiDisabled()
+ ? '[&_button:disabled]:opacity-50 [&_button:disabled]:text-ink-disabled [&_input:disabled]:text-ink-muted'
+ : ''
+ }`}
+ header={
+ showOwnerDisabledMessage() ? (
+ <div class="text-xs text-ink-extra-muted/60">
+ Only the chat owner can send or edit this email.
+ </div>
+ ) : (
+ props.header
+ )
+ }
+ toolbar={
+ props.readOnly === true ? undefined : (
+ <EmailComposeToolbar editor={editor} />
+ )
+ }
+ />
+ <Show when={uiDisabled()}>
+ <div aria-hidden="true" class="absolute inset-0 z-10 rounded-lg" />
+ </Show>
+ </div>
+ </ComposeProvider>
+ );
+}
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 3b48f4888c..da31249e2b 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -2,144 +2,232 @@ import { isErr } from '@core/util/maybeResult';
import {
deserializeToolCall,
deserializeToolResponse,
- type NamedTool,
- type ToolContext,
- type ToolHandler,
- type ToolHandlerMap,
type ToolName,
} from '@service-cognition/generated/tools/tool';
+import type { Component } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { bashCodeExecutionHandler } from './BashCodeExecution';
import { createDocumentHandler } from './CreateDocument';
+import { getThreadHandler } from './GetThread';
import { listEntitiesHandler } from './ListEntities';
import {
getEntityPropertiesHandler,
setEntityPropertyHandler,
} from './Properties';
-import { readThreadHandler } from './ReadThread';
import { readContentHandler } from './ReadContent';
import { readMetadataHandler } from './ReadMetadata';
+import { readThreadHandler } from './ReadThread';
import { contentSearchHandler, nameSearchHandler } from './Search';
+import { sendEmailHandler } from './SendEmail';
import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';
-import type { RenderContext } from './ToolRenderer';
+import type {
+ RenderContext,
+ ToolCallContext,
+ ToolRendererMap,
+ ToolResponseRenderContext,
+} from './ToolRenderer';
+import { updateThreadLabelsHandler } from './UpdateThreadLabels';
import { webFetchHandler } from './WebFetch';
import { webSearchHandler } from './WebSearch';
-const toolHandlers: ToolHandlerMap<RenderContext> = {
+const toolHandlers: ToolRendererMap<RenderContext> = {
GetEntityProperties: getEntityPropertiesHandler,
ListEntities: listEntitiesHandler,
bash_code_execution: bashCodeExecutionHandler,
ContentSearch: contentSearchHandler,
CreateDocument: createDocumentHandler,
+ GetThread: getThreadHandler,
NameSearch: nameSearchHandler,
ReadThread: readThreadHandler,
ReadContent: readContentHandler,
ReadMetadata: readMetadataHandler,
+ SendEmail: sendEmailHandler,
SetEntityProperty: setEntityPropertyHandler,
text_editor_code_execution: textEditorCodeExecutionHandler,
+ UpdateThreadLabels: updateThreadLabelsHandler,
web_fetch: webFetchHandler,
web_search: webSearchHandler,
};
-type ToolProps = {
+type BaseToolProps = {
tool_id: string;
- json: unknown;
name: string;
part_index: number;
chat_id: string;
message_id: string;
- type: 'call' | 'response' | 'error';
- // TODO: this should be removed. Render one of "call" | "response" | "error"
- isComplete: boolean;
renderContext: RenderContext;
};
-export function RenderTool(props: ToolProps) {
- let handler: ToolHandler<NamedTool, RenderContext>;
- let context: ToolContext<NamedTool>;
+type ToolCallProps = BaseToolProps & {
+ type: 'call';
+ tool_call: unknown;
+};
- if (props.type === 'call') {
- const maybeTool = deserializeToolCall({
- id: props.tool_id,
- json: props.json,
- name: props.name as ToolName,
- });
- if (isErr(maybeTool)) return null;
- const tool = maybeTool[1];
- handler = toolHandlers[tool.name].call;
- const ctx: ToolContext<NamedTool<ToolName, 'call'>> = {
- chat_id: props.chat_id,
- message_id: props.message_id,
- part_index: props.part_index,
- tool,
- isComplete: props.isComplete,
- };
- context = ctx;
- } else if (props.type === 'response') {
- const maybeTool = deserializeToolResponse({
- id: props.tool_id,
- json: props.json,
- name: props.name as ToolName,
+type ToolResponseProps = BaseToolProps & {
+ type: 'response';
+ call_part_index: number;
+ tool_call: unknown;
+ tool_response: unknown;
+};
+
+type RenderToolProps = ToolCallProps | ToolResponseProps;
+
+type TriggerToolCallArgs =
+ | Omit<ToolCallProps, 'renderContext'>
+ | (Omit<
+ ToolResponseProps,
+ 'renderContext' | 'call_part_index' | 'tool_call'
+ > & {
+ type: 'response';
});
- if (isErr(maybeTool)) return null;
- const tool = maybeTool[1];
- handler = toolHandlers[tool.name].response;
- const ctx: ToolContext<NamedTool<ToolName, 'response'>> = {
- chat_id: props.chat_id,
- message_id: props.message_id,
- part_index: props.part_index,
- tool,
- isComplete: props.isComplete,
- };
- context = ctx;
- } else {
- return;
- }
+
+const pendingToolCalls = new Map<string, ToolCallContext>();
+
+function createCallContext(args: {
+ tool_id: string;
+ tool_call: unknown;
+ name: string;
+ part_index: number;
+ chat_id: string;
+ message_id: string;
+}): ToolCallContext | null {
+ const maybeTool = deserializeToolCall({
+ id: args.tool_id,
+ json: args.tool_call,
+ name: args.name as ToolName,
+ });
+
+ if (isErr(maybeTool)) return null;
+
+ return {
+ chat_id: args.chat_id,
+ isComplete: true,
+ message_id: args.message_id,
+ part_index: args.part_index,
+ tool: maybeTool[1],
+ };
+}
+
+function createResponseContext(args: {
+ tool_id: string;
+ tool_call: unknown;
+ tool_response: unknown;
+ name: string;
+ call_part_index: number;
+ part_index: number;
+ chat_id: string;
+ message_id: string;
+}): ToolResponseRenderContext | null {
+ const toolCall = createCallContext({
+ chat_id: args.chat_id,
+ message_id: args.message_id,
+ name: args.name,
+ part_index: args.call_part_index,
+ tool_call: args.tool_call,
+ tool_id: args.tool_id,
+ });
+
+ if (!toolCall) return null;
+
+ const maybeToolResponse = deserializeToolResponse({
+ id: args.tool_id,
+ json: args.tool_response,
+ name: args.name as ToolName,
+ });
+
+ if (isErr(maybeToolResponse)) return null;
+
+ return {
+ toolCall,
+ toolResponse: {
+ chat_id: args.chat_id,
+ isComplete: true,
+ message_id: args.message_id,
+ part_index: args.part_index,
+ tool: maybeToolResponse[1],
+ },
+ };
+}
+
+function renderWithContext<TContext extends Record<string, unknown>>(
+ handler:
+ | {
+ render?: Component<TContext & RenderContext>;
+ }
+ | undefined,
+ context: TContext,
+ renderContext: RenderContext
+) {
+ if (!handler?.render) return null;
return (
<Dynamic
component={handler.render}
{...context}
renderContext={{
- isStreaming: props.renderContext.renderContext.isStreaming,
+ isStreaming: renderContext.renderContext.isStreaming,
}}
/>
);
}
-export async function triggerToolCall(args: Omit<ToolProps, 'renderContext'>) {
- const { tool_id, json, name, chat_id, message_id, part_index, type } = args;
+export function RenderToolCall(props: ToolCallProps) {
+ const context = createCallContext(props);
+ if (!context) return null;
+
+ return renderWithContext(
+ toolHandlers[context.tool.name].call,
+ context,
+ props.renderContext
+ );
+}
+
+export function RenderToolResponse(props: ToolResponseProps) {
+ const context = createResponseContext(props);
+ if (!context) return null;
- if (type === 'error') {
- return;
+ return renderWithContext(
+ toolHandlers[context.toolResponse.tool.name].response,
+ context,
+ props.renderContext
+ );
+}
+
+export function RenderTool(props: RenderToolProps) {
+ if (props.type === 'call') {
+ return <RenderToolCall {...props} />;
}
- const maybeTool =
- type === 'call'
- ? deserializeToolCall({
- id: tool_id,
- json,
- name: name as ToolName,
- })
- : deserializeToolResponse({
- id: tool_id,
- json,
- name: name as ToolName,
- });
-
- if (isErr(maybeTool)) return;
-
- const tool = maybeTool[1];
- const handler = toolHandlers[tool.name][type];
- if (!handler.handle) return;
- const context: ToolContext<NamedTool> = {
- chat_id,
- message_id,
- part_index,
- tool,
- isComplete: type !== 'call',
- };
+ return <RenderToolResponse {...props} />;
+}
+
+export async function triggerToolCall(args: TriggerToolCallArgs) {
+ if (args.type === 'call') {
+ const context = createCallContext(args);
+ if (!context) return;
- // TODO
- return handler.handle(context as any);
+ pendingToolCalls.set(context.tool.id, context);
+ return toolHandlers[context.tool.name].call.handle?.(context);
+ }
+
+ const toolCall = pendingToolCalls.get(args.tool_id);
+ if (!toolCall) return;
+
+ const context = createResponseContext({
+ chat_id: args.chat_id,
+ message_id: args.message_id,
+ name: args.name,
+ part_index: args.part_index,
+ call_part_index: toolCall.part_index,
+ tool_call: toolCall.tool.data,
+ tool_response: args.tool_response,
+ tool_id: args.tool_id,
+ });
+
+ if (!context) return;
+
+ pendingToolCalls.delete(args.tool_id);
+ return toolHandlers[context.toolResponse.tool.name].response.handle?.(
+ context
+ );
}
diff --git a/js/app/packages/core/component/AI/signal/tool.ts b/js/app/packages/core/component/AI/signal/tool.ts
index 6eada02f66..d70e76dd80 100644
--- a/js/app/packages/core/component/AI/signal/tool.ts
+++ b/js/app/packages/core/component/AI/signal/tool.ts
@@ -21,12 +21,11 @@ export function registerToolHandler(stream: () => StreamLike | undefined) {
) {
await triggerToolCall({
chat_id: latest.chat_id,
- isComplete: false,
- json: latest.content.json,
message_id: latest.message_id,
name: latest.content.name,
part_index: -1,
tool_id: latest.content.id,
+ tool_call: latest.content.json,
type: 'call',
});
} else if (
@@ -35,12 +34,11 @@ export function registerToolHandler(stream: () => StreamLike | undefined) {
) {
await triggerToolCall({
chat_id: latest.chat_id,
- isComplete: false,
- json: latest.content.json,
message_id: latest.message_id,
name: latest.content.name,
part_index: -1,
tool_id: latest.content.id,
+ tool_response: latest.content.json,
type: 'response',
});
}
diff --git a/js/app/packages/queries/chat.ts b/js/app/packages/queries/chat.ts
new file mode 100644
index 0000000000..fb8af135b3
--- /dev/null
+++ b/js/app/packages/queries/chat.ts
@@ -0,0 +1,21 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import { useQuery } from '@tanstack/solid-query';
+
+const CHAT_STALE_TIME = 30 * 1000;
+
+export function useChatQuery(chatId: () => string | undefined) {
+ return useQuery(() => {
+ const id = chatId();
+
+ return {
+ queryKey: ['chat', id],
+ queryFn: async () =>
+ throwOnErr(
+ async () => await cognitionApiServiceClient.getChat({ chat_id: id! })
+ ),
+ staleTime: CHAT_STALE_TIME,
+ enabled: !!id,
+ };
+ });
+}
diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.ts
index 4ea6f3f625..1c17ff54ff 100644
--- a/js/app/packages/service-clients/service-cognition/client.ts
+++ b/js/app/packages/service-clients/service-cognition/client.ts
@@ -28,6 +28,14 @@ import type { HttpSendChatMessageRequest } from './generated/schemas/httpSendCha
import type { PatchChatRequest } from './generated/schemas/patchChatRequest';
import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';
import type { StringIDResponse } from './generated/schemas/stringIDResponse';
+import type * as toolTypes from './generated/tools/tool.ts';
+
+type ToolCallArgs = {
+ [K in toolTypes.ToolName]: toolTypes.NamedTool<K, 'call'>['data'];
+};
+type ToolResponseArgs = {
+ [K in toolTypes.ToolName]: toolTypes.NamedTool<K, 'response'>['data'];
+};
const dcsHost: string = SERVER_HOSTS['cognition-service'];
@@ -227,6 +235,75 @@ export const cognitionApiServiceClient = {
(result) => result
);
},
+ /** Update a tool call's arguments (validates against tool schema server-side). */
+ async updateToolCall<T extends keyof ToolCallArgs>(args: {
+ chat_id: string;
+ messageId: string;
+ toolCallId: string;
+ args: ToolCallArgs[T];
+ }) {
+ return await dcsFetch(`/chats/${args.chat_id}/tool/update`, {
+ method: 'POST',
+ body: JSON.stringify({
+ messageId: args.messageId,
+ toolCallId: args.toolCallId,
+ args: args.args,
+ }),
+ });
+ },
+
+ /** Update a tool response. */
+ async updateToolResponse<T extends keyof ToolResponseArgs>(args: {
+ chat_id: string;
+ messageId: string;
+ toolCallId: string;
+ response: ToolResponseArgs[T];
+ }) {
+ return await dcsFetch(`/chats/${args.chat_id}/tool/response/update`, {
+ method: 'POST',
+ body: JSON.stringify({
+ messageId: args.messageId,
+ toolCallId: args.toolCallId,
+ response: args.response,
+ }),
+ });
+ },
+
+ /** Execute a pending tool call, optionally with updated arguments. */
+ async callTool<T extends keyof ToolCallArgs>(args: {
+ chat_id: string;
+ messageId: string;
+ toolCallId: string;
+ args?: ToolCallArgs[T];
+ }) {
+ return mapOk(
+ await dcsFetch<{ result: unknown }>(`/chats/${args.chat_id}/tool/call`, {
+ method: 'POST',
+ body: JSON.stringify({
+ messageId: args.messageId,
+ toolCallId: args.toolCallId,
+ args: args.args,
+ }),
+ }),
+ (result) => result.result
+ );
+ },
+
+ /** Reject a pending tool call. */
+ async rejectToolCall(args: {
+ chat_id: string;
+ messageId: string;
+ toolCallId: string;
+ }) {
+ return await dcsFetch(`/chats/${args.chat_id}/tool/reject`, {
+ method: 'POST',
+ body: JSON.stringify({
+ messageId: args.messageId,
+ toolCallId: args.toolCallId,
+ }),
+ });
+ },
+
/** Send a chat message via HTTP stream API. Response chunks arrive via connection_gateway. */
async sendStreamChatMessage(args: HttpSendChatMessageRequest) {
return mapOk(
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.ts
index 6c58c8a38a..edf063ec11 100644
--- a/js/app/packages/service-clients/service-cognition/generated/client.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts
@@ -5,6 +5,8 @@
* OpenAPI spec version: 1.0.0
*/
import type {
+ CallToolRequest,
+ CallToolResponse,
ChatHistory,
ChatHistoryBatchMessagesRequest,
ChatMessageError,
@@ -20,8 +22,11 @@ import type {
MemoryErrorBody,
MemoryResponse,
PatchChatRequest,
+ RejectToolCallRequest,
SendChatMessageResponse,
StringIDResponse,
+ UpdateToolCallRequest,
+ UpdateToolResponseRequest,
} from './schemas';
export type getChatsForAttachmentHandlerResponse200 = {
@@ -658,6 +663,245 @@ export const revertDeleteChat = async (
} as revertDeleteChatResponse;
};
+/**
+ * @summary Execute a pending tool call, optionally with updated arguments.
+ */
+export type callToolResponse200 = {
+ data: CallToolResponse;
+ status: 200;
+};
+
+export type callToolResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type callToolResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type callToolResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type callToolResponseSuccess = callToolResponse200 & {
+ headers: Headers;
+};
+export type callToolResponseError = (
+ | callToolResponse400
+ | callToolResponse404
+ | callToolResponse500
+) & {
+ headers: Headers;
+};
+
+export type callToolResponse = callToolResponseSuccess | callToolResponseError;
+
+export const getCallToolUrl = (chatId: string) => {
+ return `/chats/${chatId}/tool/call`;
+};
+
+export const callTool = async (
+ chatId: string,
+ callToolRequest: CallToolRequest,
+ options?: RequestInit
+): Promise<callToolResponse> => {
+ const res = await fetch(getCallToolUrl(chatId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(callToolRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: callToolResponse['data'] = body ? JSON.parse(body) : {};
+ return { data, status: res.status, headers: res.headers } as callToolResponse;
+};
+
+/**
+ * @summary Reject a pending tool call.
+ */
+export type rejectToolCallResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type rejectToolCallResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type rejectToolCallResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type rejectToolCallResponseSuccess = rejectToolCallResponse200 & {
+ headers: Headers;
+};
+export type rejectToolCallResponseError = (
+ | rejectToolCallResponse404
+ | rejectToolCallResponse500
+) & {
+ headers: Headers;
+};
+
+export type rejectToolCallResponse =
+ | rejectToolCallResponseSuccess
+ | rejectToolCallResponseError;
+
+export const getRejectToolCallUrl = (chatId: string) => {
+ return `/chats/${chatId}/tool/reject`;
+};
+
+export const rejectToolCall = async (
+ chatId: string,
+ rejectToolCallRequest: RejectToolCallRequest,
+ options?: RequestInit
+): Promise<rejectToolCallResponse> => {
+ const res = await fetch(getRejectToolCallUrl(chatId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(rejectToolCallRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: rejectToolCallResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as rejectToolCallResponse;
+};
+
+/**
+ * @summary Update a tool response.
+ */
+export type updateToolResponseResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type updateToolResponseResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type updateToolResponseResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type updateToolResponseResponseSuccess =
+ updateToolResponseResponse200 & {
+ headers: Headers;
+ };
+export type updateToolResponseResponseError = (
+ | updateToolResponseResponse404
+ | updateToolResponseResponse500
+) & {
+ headers: Headers;
+};
+
+export type updateToolResponseResponse =
+ | updateToolResponseResponseSuccess
+ | updateToolResponseResponseError;
+
+export const getUpdateToolResponseUrl = (chatId: string) => {
+ return `/chats/${chatId}/tool/response/update`;
+};
+
+export const updateToolResponse = async (
+ chatId: string,
+ updateToolResponseRequest: UpdateToolResponseRequest,
+ options?: RequestInit
+): Promise<updateToolResponseResponse> => {
+ const res = await fetch(getUpdateToolResponseUrl(chatId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(updateToolResponseRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: updateToolResponseResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as updateToolResponseResponse;
+};
+
+/**
+ * @summary Update a tool call's arguments after validation.
+ */
+export type updateToolCallResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type updateToolCallResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type updateToolCallResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type updateToolCallResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type updateToolCallResponseSuccess = updateToolCallResponse200 & {
+ headers: Headers;
+};
+export type updateToolCallResponseError = (
+ | updateToolCallResponse400
+ | updateToolCallResponse404
+ | updateToolCallResponse500
+) & {
+ headers: Headers;
+};
+
+export type updateToolCallResponse =
+ | updateToolCallResponseSuccess
+ | updateToolCallResponseError;
+
+export const getUpdateToolCallUrl = (chatId: string) => {
+ return `/chats/${chatId}/tool/update`;
+};
+
+export const updateToolCall = async (
+ chatId: string,
+ updateToolCallRequest: UpdateToolCallRequest,
+ options?: RequestInit
+): Promise<updateToolCallResponse> => {
+ const res = await fetch(getUpdateToolCallUrl(chatId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(updateToolCallRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: updateToolCallResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as updateToolCallResponse;
+};
+
export type getCitationHandlerResponse200 = {
data: DocumentTextPart;
status: 200;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/callToolRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/callToolRequest.ts
new file mode 100644
index 0000000000..dbdc5ac05d
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/callToolRequest.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for executing a pending tool call.
+ */
+export interface CallToolRequest {
+ /** Optional updated arguments. Uses original args if omitted. */
+ args?: unknown;
+ /** The message ID containing the tool call. */
+ messageId: string;
+ /** The tool call ID to execute. */
+ toolCallId: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/callToolResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/callToolResponse.ts
new file mode 100644
index 0000000000..f0b8d94e70
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/callToolResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Response body for a successful tool call.
+ */
+export interface CallToolResponse {
+ /** The tool execution result. */
+ result: unknown;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
index 03f166145d..d23677c43b 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
@@ -28,6 +28,8 @@ export * from './attachmentMetadataOneOfThree';
export * from './attachmentMetadataOneOfThreeType';
export * from './attachmentMetadataOneOfType';
export * from './attachmentType';
+export * from './callToolRequest';
+export * from './callToolResponse';
export * from './channelSharePermission';
export * from './channelType';
export * from './chat';
@@ -152,6 +154,7 @@ export * from './patchChatRequestName';
export * from './patchChatRequestProjectId';
export * from './patchChatRequestSharePermission';
export * from './provider';
+export * from './rejectToolCallRequest';
export * from './role';
export * from './sendChatMessagePayload';
export * from './sendChatMessagePayloadAllOf';
@@ -183,7 +186,11 @@ export * from './updateSharePermissionRequestV2';
export * from './updateSharePermissionRequestV2ChannelSharePermissions';
export * from './updateSharePermissionRequestV2IsPublic';
export * from './updateSharePermissionRequestV2PublicAccessLevel';
+export * from './updateToolCallRequest';
+export * from './updateToolResponseRequest';
export * from './userPdfRect';
+export * from './userToolResponseValue';
+export * from './userToolResponseValueOneOf';
export * from './webCitation';
export * from './webCitationDescription';
export * from './webCitationFaviconUrl';
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/rejectToolCallRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/rejectToolCallRequest.ts
new file mode 100644
index 0000000000..fbd0f5a131
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/rejectToolCallRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for rejecting a pending tool call.
+ */
+export interface RejectToolCallRequest {
+ /** The message ID containing the tool call. */
+ messageId: string;
+ /** The tool call ID to reject. */
+ toolCallId: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolCallRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolCallRequest.ts
new file mode 100644
index 0000000000..dad5340991
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolCallRequest.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for updating a tool call's arguments.
+ */
+export interface UpdateToolCallRequest {
+ /** The new arguments for the tool call. */
+ args: unknown;
+ /** The message ID containing the tool call. */
+ messageId: string;
+ /** The tool call ID to update. */
+ toolCallId: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolResponseRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolResponseRequest.ts
new file mode 100644
index 0000000000..2560666589
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/updateToolResponseRequest.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { UserToolResponseValue } from './userToolResponseValue';
+
+/**
+ * Request body for updating a tool response.
+ */
+export interface UpdateToolResponseRequest {
+ /** The message ID containing the tool response. */
+ messageId: string;
+ /** The new user tool response. */
+ response: UserToolResponseValue;
+ /** The tool call ID whose response should be updated. */
+ toolCallId: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValue.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValue.ts
new file mode 100644
index 0000000000..f114b7b94c
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValue.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { UserToolResponseValueOneOf } from './userToolResponseValueOneOf';
+
+/**
+ * User tools are pending until a user executes them
+ */
+export type UserToolResponseValue =
+ | 'PendingUserExecution'
+ | 'Rejected'
+ | UserToolResponseValueOneOf;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValueOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValueOneOf.ts
new file mode 100644
index 0000000000..1dd765b163
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/userToolResponseValueOneOf.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Tool is executed and has whatever return type the wrapped tool returns
+ */
+export type UserToolResponseValueOneOf = {
+ UserAction: unknown;
+};
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 2562c9ed32..e508d8dc26 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
@@ -369,6 +369,48 @@ export const GetEntityPropertiesResponse = z.object({
summary: z.string(),
});
+export const GetThread = z
+ .object({
+ limit: z.union([z.number().int(), z.null()]).default(null),
+ threadId: z.string().uuid(),
+ })
+ .strict();
+
+export const GetThreadResponse = z.object({
+ isRead: z.boolean(),
+ messages: z.array(
+ z.object({
+ bodyParsed: z.union([z.string(), z.null()]).optional(),
+ cc: z.array(
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ })
+ ),
+ date: z.union([z.string(), z.null()]).optional(),
+ from: z
+ .union([
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ }),
+ z.null(),
+ ])
+ .optional(),
+ id: z.string().uuid(),
+ subject: z.union([z.string(), z.null()]).optional(),
+ to: z.array(
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ })
+ ),
+ })
+ ),
+ summary: z.string(),
+ threadId: z.string().uuid(),
+});
+
export const ListEntities = z
.object({
includeTypes: z.union([
@@ -513,8 +555,6 @@ export const ReadThread = z
'channel-message',
'chat-thread',
'chat-message',
- 'email-thread',
- 'email-message',
'project',
]),
ids: z.array(z.string()),
@@ -549,24 +589,6 @@ export const ReadResponse = z.object({
),
type: z.literal('chat'),
}),
- z.object({
- messages: z.array(
- z.object({
- bcc: z.array(z.string()),
- cc: z.array(z.string()),
- content: z.string(),
- messageId: z.string(),
- recipients: z.array(z.string()),
- sender: z.string(),
- sentAt: z
- .union([z.string().datetime({ offset: true }), z.null()])
- .optional(),
- })
- ),
- subject: z.union([z.string(), z.null()]).optional(),
- thread_id: z.string(),
- type: z.literal('email'),
- }),
z.object({
formatted_preview: z.string(),
type: z.literal('itemPreviews'),
@@ -590,6 +612,97 @@ export const ReadResponse = z.object({
}),
});
+export const SendEmail = z
+ .object({
+ bcc: z.array(
+ z
+ .object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).default(null),
+ })
+ .strict()
+ ),
+ body: z.string(),
+ cc: z.array(
+ z
+ .object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).default(null),
+ })
+ .strict()
+ ),
+ replyingToId: z.union([z.string().uuid(), z.null()]).default(null),
+ subject: z.string(),
+ to: z.array(
+ z
+ .object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).default(null),
+ })
+ .strict()
+ ),
+ })
+ .strict();
+
+export const UserToolResponse = z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('PendingUserExecution'),
+ z.literal('Rejected'),
+ z
+ .object({
+ UserAction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('userEdited'),
+ z
+ .object({
+ sent: z.object({
+ message_id: z.string().uuid(),
+ thread_id: z.string().uuid(),
+ }),
+ })
+ .strict(),
+ z
+ .object({
+ convertedToDraft: z.object({ draft_id: z.string().uuid() }),
+ })
+ .strict(),
+ ];
+ 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',
+ });
+ }
+ }),
+ })
+ .strict(),
+ ];
+ 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',
+ });
+ }
+});
+
export const SetEntityProperty = z
.object({
boolean_value: z.union([z.boolean(), z.null()]).default(null),
@@ -771,6 +884,20 @@ export const TextEditorCodeExecutionResponse = z.object({
tool_use_id: z.string(),
});
+export const UpdateThreadLabels = z
+ .object({
+ add: z.boolean(),
+ label_id: z.string().uuid(),
+ thread_id: z.string().uuid(),
+ })
+ .strict();
+
+export const UpdateThreadLabelsResponse = z.object({
+ failedCount: z.number().int().gte(0),
+ successfulCount: z.number().int().gte(0),
+ summary: z.string(),
+});
+
export const WebFetchToolCall = z.object({ url: z.string() });
export const WebFetchResponse = z.object({
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 aba994b096..471e90421e 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
@@ -25,6 +25,7 @@ type ToolParserMap = {
call: types.GetEntityProperties;
response: types.GetEntityPropertiesResponse;
};
+ GetThread: { call: types.GetThread; response: types.GetThreadResponse };
ListEntities: {
call: types.ListEntities;
response: types.ListEntitiesResponse;
@@ -36,6 +37,7 @@ type ToolParserMap = {
response: types.ReadMetadataResponse;
};
ReadThread: { call: types.ReadThread; response: types.ReadResponse };
+ SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
SetEntityProperty: {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
@@ -44,6 +46,10 @@ type ToolParserMap = {
call: types.TextEditorCodeExecutionToolCall;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateThreadLabels: {
+ call: types.UpdateThreadLabels;
+ response: types.UpdateThreadLabelsResponse;
+ };
web_fetch: { call: types.WebFetchToolCall; response: types.WebFetchResponse };
web_search: {
call: types.WebSearchToolCall;
@@ -68,6 +74,7 @@ const toolParserMap = {
call: schemas.GetEntityProperties,
response: schemas.GetEntityPropertiesResponse,
},
+ GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },
ListEntities: {
call: schemas.ListEntities,
response: schemas.ListEntitiesResponse,
@@ -85,6 +92,7 @@ const toolParserMap = {
response: schemas.ReadMetadataResponse,
},
ReadThread: { call: schemas.ReadThread, response: schemas.ReadResponse },
+ SendEmail: { call: schemas.SendEmail, response: schemas.UserToolResponse },
SetEntityProperty: {
call: schemas.SetEntityProperty,
response: schemas.SetEntityPropertyResponse,
@@ -93,6 +101,10 @@ const toolParserMap = {
call: schemas.TextEditorCodeExecutionToolCall,
response: schemas.TextEditorCodeExecutionResponse,
},
+ UpdateThreadLabels: {
+ call: schemas.UpdateThreadLabels,
+ response: schemas.UpdateThreadLabelsResponse,
+ },
web_fetch: {
call: schemas.WebFetchToolCall,
response: schemas.WebFetchResponse,
@@ -128,6 +140,7 @@ type ToolDataMap = {
call: types.GetEntityProperties;
response: types.GetEntityPropertiesResponse;
};
+ GetThread: { call: types.GetThread; response: types.GetThreadResponse };
ListEntities: {
call: types.ListEntities;
response: types.ListEntitiesResponse;
@@ -139,6 +152,7 @@ type ToolDataMap = {
response: types.ReadMetadataResponse;
};
ReadThread: { call: types.ReadThread; response: types.ReadResponse };
+ SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
SetEntityProperty: {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
@@ -147,6 +161,10 @@ type ToolDataMap = {
call: types.TextEditorCodeExecutionToolCall;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateThreadLabels: {
+ call: types.UpdateThreadLabels;
+ response: types.UpdateThreadLabelsResponse;
+ };
web_fetch: { call: types.WebFetchToolCall; response: types.WebFetchResponse };
web_search: {
call: types.WebSearchToolCall;
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 c6464fc4b0..b1ecf8f474 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
@@ -708,6 +708,112 @@ export interface GetEntityPropertiesResponse {
summary: string;
}
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * 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;
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Response from the GetThread tool.
+ */
+export interface GetThreadResponse {
+ /**
+ * Whether the thread has been read.
+ */
+ isRead: boolean;
+ /**
+ * The messages in the thread (most recent first).
+ */
+ messages: {
+ /**
+ * The parsed plaintext body (reply/forwarded content stripped, HTML converted).
+ */
+ bodyParsed?: string | null;
+ /**
+ * The Cc recipients.
+ */
+ cc: {
+ /**
+ * The contact's email address.
+ */
+ email: string;
+ /**
+ * The contact's display name.
+ */
+ name?: string | null;
+ }[];
+ /**
+ * When the message was received/sent.
+ */
+ date?: string | null;
+ /**
+ * The sender's email and name.
+ */
+ from?: {
+ /**
+ * The contact's email address.
+ */
+ email: string;
+ /**
+ * The contact's display name.
+ */
+ name?: string | null;
+ } | null;
+ /**
+ * The message's unique identifier.
+ */
+ id: string;
+ /**
+ * The message subject.
+ */
+ subject?: string | null;
+ /**
+ * The To recipients.
+ */
+ to: {
+ /**
+ * The contact's email address.
+ */
+ email: string;
+ /**
+ * The contact's display name.
+ */
+ name?: string | null;
+ }[];
+ }[];
+ /**
+ * A human-readable summary.
+ */
+ summary: string;
+ /**
+ * The thread's unique identifier.
+ */
+ threadId: string;
+}
+
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
@@ -964,7 +1070,7 @@ export interface ReadMetadataResponse {
*/
/**
- * Read threaded content by ID(s). Supports reading channels, chats, emails, 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.
+ * 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.
*/
export interface ReadThread {
@@ -976,11 +1082,9 @@ export interface ReadThread {
| 'channel-message'
| 'chat-thread'
| 'chat-message'
- | 'email-thread'
- | 'email-message'
| 'project';
/**
- * ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id.
+ * ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and content types support MULTIPLE ids! For all other content types (channel, chat-thread) provide a single id.
*/
ids: string[];
/**
@@ -1016,26 +1120,115 @@ export interface ReadResponse {
}[];
type: 'chat';
}
- | {
- messages: {
- bcc: string[];
- cc: string[];
- content: string;
- messageId: string;
- recipients: string[];
- sender: string;
- sentAt?: string | null;
- }[];
- subject?: string | null;
- thread_id: string;
- type: 'email';
- }
| {
formatted_preview: string;
type: 'itemPreviews';
};
}
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Compose and send an email. Creates the message and immediately queues it for delivery. To reply to an existing message, provide the replying_to_id. The body must be plain text only — do not use HTML, Markdown, or any formatting syntax (no **bold**, *italics*, headings, etc.). Just write natural prose with line breaks.
+ */
+export interface SendEmail {
+ /**
+ * Blind carbon copy recipients (optional).
+ */
+ bcc: {
+ /**
+ * The recipient's email address.
+ */
+ email: string;
+ /**
+ * The recipient's display name (optional).
+ */
+ name: string | null;
+ }[];
+ /**
+ * The plain text body of the email.
+ */
+ body: string;
+ /**
+ * Carbon copy recipients (optional).
+ */
+ cc: {
+ /**
+ * The recipient's email address.
+ */
+ email: string;
+ /**
+ * The recipient's display name (optional).
+ */
+ name: string | null;
+ }[];
+ /**
+ * The ID of a message to reply to (optional). When set, the email is
+ * sent as a reply within the same thread.
+ */
+ replyingToId: string | null;
+ /**
+ * The subject line of the email.
+ */
+ subject: string;
+ /**
+ * The primary recipients (To field).
+ */
+ to: {
+ /**
+ * The recipient's email address.
+ */
+ email: string;
+ /**
+ * The recipient's display name (optional).
+ */
+ name: string | null;
+ }[];
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * User tools are pending until a user executes them
+ */
+export type UserToolResponse =
+ | 'PendingUserExecution'
+ | 'Rejected'
+ | {
+ /**
+ * Response from the SendEmail tool.
+ */
+ UserAction:
+ | 'userEdited'
+ | {
+ sent: {
+ /**
+ * The database ID of the sent message.
+ */
+ message_id: string;
+ /**
+ * The thread ID the message belongs to.
+ */
+ thread_id: string;
+ };
+ }
+ | {
+ convertedToDraft: {
+ draft_id: string;
+ };
+ };
+ };
+
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
@@ -1265,6 +1458,56 @@ export interface TextEditorCodeExecutionToolError {
error_code: CodeExecutionErrorCode;
}
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Add or remove a label from all messages in an email thread. Use ListLabels first to get valid label IDs. Set `add` to true to apply the label, or false to remove it.
+ */
+export interface UpdateThreadLabels {
+ /**
+ * Whether to add (true) or remove (false) the label.
+ */
+ add: boolean;
+ /**
+ * The ID of the label to add or remove. Use ListLabels to get valid label IDs.
+ */
+ label_id: string;
+ /**
+ * The ID of the email thread to modify.
+ */
+ thread_id: string;
+}
+
+/* eslint-disable */
+/**
+ * This file was automatically generated by json-schema-to-typescript.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run json-schema-to-typescript to regenerate this file.
+ */
+
+/**
+ * Response from the UpdateThreadLabels tool.
+ */
+export interface UpdateThreadLabelsResponse {
+ /**
+ * The number of messages that failed to update.
+ */
+ failedCount: number;
+ /**
+ * The number of messages successfully updated.
+ */
+ successfulCount: number;
+ /**
+ * A human-readable summary of the operation.
+ */
+ summary: string;
+}
+
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 205cc9de93..a61b8dc46d 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -578,6 +578,245 @@
}
}
},
+ "/chats/{chat_id}/tool/call": {
+ "post": {
+ "tags": ["chats"],
+ "summary": "Execute a pending tool call, optionally with updated arguments.",
+ "operationId": "call_tool",
+ "parameters": [
+ {
+ "name": "chat_id",
+ "in": "path",
+ "description": "ID of the chat",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CallToolRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Tool executed successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CallToolResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Validation or execution failed",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Tool call not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/chats/{chat_id}/tool/reject": {
+ "post": {
+ "tags": ["chats"],
+ "summary": "Reject a pending tool call.",
+ "operationId": "reject_tool_call",
+ "parameters": [
+ {
+ "name": "chat_id",
+ "in": "path",
+ "description": "ID of the chat",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RejectToolCallRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Tool call rejected"
+ },
+ "404": {
+ "description": "Tool call not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/chats/{chat_id}/tool/response/update": {
+ "post": {
+ "tags": ["chats"],
+ "summary": "Update a tool response.",
+ "operationId": "update_tool_response",
+ "parameters": [
+ {
+ "name": "chat_id",
+ "in": "path",
+ "description": "ID of the chat",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateToolResponseRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Tool response updated"
+ },
+ "404": {
+ "description": "Tool call not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/chats/{chat_id}/tool/update": {
+ "post": {
+ "tags": ["chats"],
+ "summary": "Update a tool call's arguments after validation.",
+ "operationId": "update_tool_call",
+ "parameters": [
+ {
+ "name": "chat_id",
+ "in": "path",
+ "description": "ID of the chat",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateToolCallRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Tool call args updated"
+ },
+ "400": {
+ "description": "Validation failed",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Tool call not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/citations/{id}": {
"get": {
"tags": ["citations"],
@@ -975,6 +1214,34 @@
"type": "string",
"enum": ["document", "image", "channel", "email", "project"]
},
+ "CallToolRequest": {
+ "type": "object",
+ "description": "Request body for executing a pending tool call.",
+ "required": ["messageId", "toolCallId"],
+ "properties": {
+ "args": {
+ "description": "Optional updated arguments. Uses original args if omitted."
+ },
+ "messageId": {
+ "type": "string",
+ "description": "The message ID containing the tool call."
+ },
+ "toolCallId": {
+ "type": "string",
+ "description": "The tool call ID to execute."
+ }
+ }
+ },
+ "CallToolResponse": {
+ "type": "object",
+ "description": "Response body for a successful tool call.",
+ "required": ["result"],
+ "properties": {
+ "result": {
+ "description": "The tool execution result."
+ }
+ }
+ },
"ChannelSharePermission": {
"type": "object",
"description": "The channel share permission",
@@ -2549,6 +2816,21 @@
"type": "string",
"enum": ["openai", "google", "anthropic", "googleanthropic", "xai"]
},
+ "RejectToolCallRequest": {
+ "type": "object",
+ "description": "Request body for rejecting a pending tool call.",
+ "required": ["messageId", "toolCallId"],
+ "properties": {
+ "messageId": {
+ "type": "string",
+ "description": "The message ID containing the tool call."
+ },
+ "toolCallId": {
+ "type": "string",
+ "description": "The tool call ID to reject."
+ }
+ }
+ },
"Role": {
"type": "string",
"enum": ["user", "assistant", "system"]
@@ -2818,6 +3100,43 @@
}
}
},
+ "UpdateToolCallRequest": {
+ "type": "object",
+ "description": "Request body for updating a tool call's arguments.",
+ "required": ["messageId", "toolCallId", "args"],
+ "properties": {
+ "args": {
+ "description": "The new arguments for the tool call."
+ },
+ "messageId": {
+ "type": "string",
+ "description": "The message ID containing the tool call."
+ },
+ "toolCallId": {
+ "type": "string",
+ "description": "The tool call ID to update."
+ }
+ }
+ },
+ "UpdateToolResponseRequest": {
+ "type": "object",
+ "description": "Request body for updating a tool response.",
+ "required": ["messageId", "toolCallId", "response"],
+ "properties": {
+ "messageId": {
+ "type": "string",
+ "description": "The message ID containing the tool response."
+ },
+ "response": {
+ "$ref": "#/components/schemas/UserToolResponse_Value",
+ "description": "The new user tool response."
+ },
+ "toolCallId": {
+ "type": "string",
+ "description": "The tool call ID whose response should be updated."
+ }
+ }
+ },
"UserPdfRect": {
"type": "object",
"description": "UserPdfRect is in UserSpace\n(0,0) top left\npercent page units\n1-based page index",
@@ -2846,6 +3165,29 @@
}
}
},
+ "UserToolResponse_Value": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Tool has not yet been executed",
+ "enum": ["PendingUserExecution"]
+ },
+ {
+ "type": "string",
+ "description": "User rejected suggested tool execution",
+ "enum": ["Rejected"]
+ },
+ {
+ "type": "object",
+ "description": "Tool is executed and has whatever return type the wrapped tool returns",
+ "required": ["UserAction"],
+ "properties": {
+ "UserAction": {}
+ }
+ }
+ ],
+ "description": "User tools are pending until a user executes them"
+ },
"WebCitation": {
"type": "object",
"description": "A web citation associated with a chat message.",
diff --git a/js/app/scripts/generate-api-schema.ts b/js/app/scripts/generate-api-schema.ts
index abc541a9a4..dc34ebad6d 100644
--- a/js/app/scripts/generate-api-schema.ts
+++ b/js/app/scripts/generate-api-schema.ts
@@ -6,241 +6,283 @@
// This script generates OpenAPI schemas by running the local Rust binaries
// instead of fetching from deployed services.
-import * as path from 'node:path';
-import { $, write } from 'bun';
-import { type Service, services } from './services';
+import * as path from "node:path";
+import { $, write } from "bun";
+import { type Service, services } from "./services";
-const elapsed = (start: number) => `${((performance.now() - start) / 1000).toFixed(1)}s`;
+const elapsed = (start: number) =>
+ `${((performance.now() - start) / 1000).toFixed(1)}s`;
// Map service names to Rust crate names
const serviceToCrate: Record<string, string> = {
- 'cloud-storage': 'document_storage_service',
- 'comms-service': 'comms_service',
- 'properties-service': 'properties_service',
- 'document-cognition': 'document_cognition_service',
- 'auth-service': 'authentication_service',
- 'notification-service': 'notification_service',
- 'static-files': 'static_file_service',
- 'connection-gateway': 'connection_gateway',
- 'contacts-service': 'contacts_service',
- 'unfurl-service': 'unfurl_service',
- 'email-service': 'email_service',
- 'search-service': 'search_service',
+ "cloud-storage": "document_storage_service",
+ "comms-service": "comms_service",
+ "properties-service": "properties_service",
+ "document-cognition": "document_cognition_service",
+ "auth-service": "authentication_service",
+ "notification-service": "notification_service",
+ "static-files": "static_file_service",
+ "connection-gateway": "connection_gateway",
+ "contacts-service": "contacts_service",
+ "unfurl-service": "unfurl_service",
+ "email-service": "email_service",
+ "search-service": "search_service",
};
-const getRustCloudStorageDir = () => path.resolve(import.meta.dirname, '../../../rust/cloud-storage');
-const getServiceClientsDir = () => path.resolve(import.meta.dirname, '../packages/service-clients');
+const getRustCloudStorageDir = () =>
+ path.resolve(import.meta.dirname, "../../../rust/cloud-storage");
+const getServiceClientsDir = () =>
+ path.resolve(import.meta.dirname, "../packages/service-clients");
// Parse arguments
-const getTargetServices = () => process.argv.slice(2).filter(arg => arg !== '--check');
+const getTargetServices = () =>
+ process.argv.slice(2).filter((arg) => arg !== "--check");
// Build all OpenAPI binaries in a single cargo invocation (cargo parallelizes internally).
-async function buildOpenApiBinaries(crateNames: string[], { rustCloudStorageDir = getRustCloudStorageDir() } = {}): Promise<void> {
- if (crateNames.length === 0) return;
-
- const binArgs = crateNames.flatMap(crate => ['--bin', `${crate}_openapi`]);
-
- // Also build the DCS models + tools binaries if document_cognition_service is included
- if (crateNames.includes('document_cognition_service')) {
- binArgs.push('--bin', 'document_cognition_service_models');
- binArgs.push('--bin', 'gen_tool_schemas');
- }
-
- console.log(`Building ${crateNames.length} OpenAPI binaries...`);
- console.log(`cargo build args: ${binArgs.join(' ')}`);
- await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build ${binArgs}`;
- console.log('Build complete.\n');
+async function buildOpenApiBinaries(
+ crateNames: string[],
+ { rustCloudStorageDir = getRustCloudStorageDir() } = {},
+): Promise<void> {
+ if (crateNames.length === 0) return;
+
+ const binArgs = crateNames.flatMap((crate) => ["--bin", `${crate}_openapi`]);
+
+ // Also build the DCS models + tools binaries if document_cognition_service is included
+ if (crateNames.includes("document_cognition_service")) {
+ binArgs.push("--bin", "document_cognition_service_models");
+ binArgs.push("--bin", "gen_tool_schemas");
+ }
+
+ console.log(`Building ${crateNames.length} OpenAPI binaries...`);
+ console.log(`cargo build args: ${binArgs.join(" ")}`);
+ await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build ${binArgs}`;
+ console.log("Build complete.\n");
}
// Run pre-built binary directly (no cargo lock needed)
-async function runOpenApiBinary(crateName: string, rustCloudStorageDir = getRustCloudStorageDir()): Promise<string> {
- const binaryPath = path.join(rustCloudStorageDir, 'target', 'debug', `${crateName}_openapi`);
- const result = await $`${binaryPath}`.text();
- return result;
+async function runOpenApiBinary(
+ crateName: string,
+ rustCloudStorageDir = getRustCloudStorageDir(),
+): Promise<string> {
+ const binaryPath = path.join(
+ rustCloudStorageDir,
+ "target",
+ "debug",
+ `${crateName}_openapi`,
+ );
+ const result = await $`${binaryPath}`.text();
+ return result;
}
// Run a named binary from the debug directory
-async function runBinary(binaryName: string, rustCloudStorageDir = getRustCloudStorageDir()): Promise<string> {
- const binaryPath = path.join(rustCloudStorageDir, 'target', 'debug', binaryName);
- const result = await $`${binaryPath}`.text();
- return result;
+async function runBinary(
+ binaryName: string,
+ rustCloudStorageDir = getRustCloudStorageDir(),
+): Promise<string> {
+ const binaryPath = path.join(
+ rustCloudStorageDir,
+ "target",
+ "debug",
+ binaryName,
+ );
+ const result = await $`${binaryPath}`.text();
+ return result;
}
// Recursively sort all object keys in JSON to ensure deterministic output
function sortJsonKeys(obj: unknown): unknown {
- if (Array.isArray(obj)) {
- return obj.map(sortJsonKeys);
- }
- if (obj !== null && typeof obj === 'object') {
- const sorted: Record<string, unknown> = {};
- for (const key of Object.keys(obj).sort()) {
- sorted[key] = sortJsonKeys((obj as Record<string, unknown>)[key]);
- }
- return sorted;
- }
- return obj;
+ if (Array.isArray(obj)) {
+ return obj.map(sortJsonKeys);
+ }
+ if (obj !== null && typeof obj === "object") {
+ const sorted: Record<string, unknown> = {};
+ for (const key of Object.keys(obj).sort()) {
+ sorted[key] = sortJsonKeys((obj as Record<string, unknown>)[key]);
+ }
+ return sorted;
+ }
+ return obj;
}
const getServicesToProcess = (targetServices: string[]) => {
- // Figure out which services to process
- let servicesToProcess: Service[];
- if (targetServices.length > 0) {
- // Filter only those whose names match the arguments
- servicesToProcess = services.filter((service) =>
- targetServices.includes(service.name)
- );
-
- // If none matched, bail out
- if (servicesToProcess.length === 0) {
- console.error(
- `Error: No matching services found for [${targetServices.join(', ')}].
- Valid options are: ${services.map((s) => s.name).join(', ')}`
- );
- process.exit(1);
- }
- } else {
- // If no arguments, process all
- servicesToProcess = services;
- }
-
- return servicesToProcess
-}
-
+ // Figure out which services to process
+ let servicesToProcess: Service[];
+ if (targetServices.length > 0) {
+ // Filter only those whose names match the arguments
+ servicesToProcess = services.filter((service) =>
+ targetServices.includes(service.name),
+ );
+
+ // If none matched, bail out
+ if (servicesToProcess.length === 0) {
+ console.error(
+ `Error: No matching services found for [${targetServices.join(", ")}].
+ Valid options are: ${services.map((s) => s.name).join(", ")}`,
+ );
+ process.exit(1);
+ }
+ } else {
+ // If no arguments, process all
+ servicesToProcess = services;
+ }
+
+ return servicesToProcess;
+};
// Process a single service (assumes binary is already built)
-const processService = async (service: Service, { serviceClientsDir }: { serviceClientsDir: string }) => {
- const crateName = serviceToCrate[service.name];
- if (!crateName) {
- console.error(`[${service.name}] No crate mapping found, skipping`);
- return { service: service.name, status: 'skipped' as const };
- }
-
- try {
- const outputDir = path.resolve(import.meta.dirname, service.output);
- const generatedDir = path.resolve(outputDir, 'generated');
- const openApiPath = path.join(outputDir, 'openapi.json');
-
- const serviceStart = performance.now();
-
- console.log(`[${service.name}] Running OpenAPI binary...`);
- let stepStart = performance.now();
- const openApiJson = await runOpenApiBinary(crateName);
- console.log(`[${service.name}] OpenAPI binary finished (${elapsed(stepStart)})`);
-
- // Remove existing generated dir
- await $`rm -rf ${generatedDir}`.quiet();
-
- // Write the OpenAPI JSON
- await write(openApiPath, openApiJson);
- console.log(`[${service.name}] Saved OpenAPI spec`);
-
- // Run orval to generate types
- stepStart = performance.now();
- await $`cd ${serviceClientsDir} && bun run orval --config orval.config.ts --project ${service.orvalKey}`.quiet();
- console.log(`[${service.name}] Orval finished (${elapsed(stepStart)})`);
-
- // Special handling for document-cognition
- if (service.name === 'document-cognition') {
- stepStart = performance.now();
- const rustCloudStorageDir = getRustCloudStorageDir();
- const modelsJson = await runBinary('document_cognition_service_models', rustCloudStorageDir);
- console.log(`[${service.name}] Models binary finished (${elapsed(stepStart)})`);
- const modelsJsonPath = path.join(import.meta.dirname, '.models.json');
- await write(modelsJsonPath, modelsJson);
-
- stepStart = performance.now();
- const appDir = path.resolve(import.meta.dirname, '..');
- try {
- await $`cd ${appDir} && MODELS_JSON=${modelsJsonPath} bun scripts/generate-dcs-types.ts`.quiet();
- } finally {
- await $`rm -f ${modelsJsonPath}`.quiet();
- }
- console.log(`[${service.name}] DCS types generation finished (${elapsed(stepStart)})`);
- }
-
- console.log(`[${service.name}] ✓ Done (total: ${elapsed(serviceStart)})`);
- return { service: service.name, status: 'success' as const };
- } catch (error) {
- console.error(`[${service.name}] Failed:`, error);
- return { service: service.name, status: 'failed' as const, error };
- }
+const processService = async (
+ service: Service,
+ { serviceClientsDir }: { serviceClientsDir: string },
+) => {
+ const crateName = serviceToCrate[service.name];
+ if (!crateName) {
+ console.error(`[${service.name}] No crate mapping found, skipping`);
+ return { service: service.name, status: "skipped" as const };
+ }
+
+ try {
+ const outputDir = path.resolve(import.meta.dirname, service.output);
+ const generatedDir = path.resolve(outputDir, "generated");
+ const openApiPath = path.join(outputDir, "openapi.json");
+
+ const serviceStart = performance.now();
+
+ console.log(`[${service.name}] Running OpenAPI binary...`);
+ let stepStart = performance.now();
+ const openApiJson = await runOpenApiBinary(crateName);
+ console.log(
+ `[${service.name}] OpenAPI binary finished (${elapsed(stepStart)})`,
+ );
+
+ // Remove existing generated dir
+ await $`rm -rf ${generatedDir}`.quiet();
+
+ // Write the OpenAPI JSON
+ await write(openApiPath, openApiJson);
+ console.log(`[${service.name}] Saved OpenAPI spec`);
+
+ // Run orval to generate types
+ stepStart = performance.now();
+ await $`cd ${serviceClientsDir} && bun run orval --config orval.config.ts --project ${service.orvalKey}`.quiet();
+ console.log(`[${service.name}] Orval finished (${elapsed(stepStart)})`);
+
+ // Special handling for document-cognition
+ if (service.name === "document-cognition") {
+ stepStart = performance.now();
+ const rustCloudStorageDir = getRustCloudStorageDir();
+ const modelsJson = await runBinary(
+ "document_cognition_service_models",
+ rustCloudStorageDir,
+ );
+ console.log(
+ `[${service.name}] Models binary finished (${elapsed(stepStart)})`,
+ );
+ const modelsJsonPath = path.join(import.meta.dirname, ".models.json");
+ await write(modelsJsonPath, modelsJson);
+
+ stepStart = performance.now();
+ const appDir = path.resolve(import.meta.dirname, "..");
+ try {
+ await $`cd ${appDir} && MODELS_JSON=${modelsJsonPath} bun scripts/generate-dcs-types.ts`.quiet();
+ } finally {
+ await $`rm -f ${modelsJsonPath}`.quiet();
+ }
+ console.log(
+ `[${service.name}] DCS types generation finished (${elapsed(stepStart)})`,
+ );
+ }
+
+ console.log(`[${service.name}] ✓ Done (total: ${elapsed(serviceStart)})`);
+ return { service: service.name, status: "success" as const };
+ } catch (error) {
+ console.error(`[${service.name}] Failed:`, error);
+ return { service: service.name, status: "failed" as const, error };
+ }
};
-
async function main() {
- const serviceClientsDir = getServiceClientsDir();
- const checkMode = process.argv.includes('--check');
- const targetServices = getTargetServices();
- const servicesToProcess = getServicesToProcess(targetServices);
-
- // Get crate names for services that have mappings
- const crateNames = servicesToProcess
- .map(s => serviceToCrate[s.name])
- .filter((crate): crate is string => !!crate);
-
- console.log(`\nProcessing ${servicesToProcess.length} service(s)...\n`);
-
- // Phase 1: Build all binaries in a single cargo invocation (parallelized by cargo)
- const buildStart = performance.now();
- await buildOpenApiBinaries(crateNames);
- console.log(`Phase 1 (cargo build) total: ${elapsed(buildStart)}`);
-
- // Phase 2: Run binaries and generate TypeScript in parallel
- console.log('\nGenerating TypeScript clients...\n');
- const results = await Promise.all(
- servicesToProcess.map(service => processService(service, { serviceClientsDir }))
- );
-
- // Summary report
- console.log('\nProcessing Summary:');
- const succeeded = results.filter((r) => r.status === 'success');
- const failed = results.filter((r) => r.status === 'failed');
- const skipped = results.filter((r) => r.status === 'skipped');
-
-
- console.log(`Succeeded: ${succeeded.length}/${servicesToProcess.length}`);
- if (skipped.length > 0) {
- console.log(`Skipped: ${skipped.length}/${servicesToProcess.length}`);
- }
- if (failed.length > 0) {
- console.log(`Failed: ${failed.length}/${servicesToProcess.length}`);
- failed.forEach((result) => {
- console.error(` - ${result.service}:`, result.error);
- });
- process.exit(1);
- }
- // On NixOS, the npm-installed biome binary doesn't work due to dynamic linking issues.
- // We detect NixOS and use the system biome instead.
- const isNixOS = process.env.NIX_PATH !== undefined || (await Bun.file("/etc/os-release").exists() && (await Bun.file("/etc/os-release").text()).includes("NixOS"));
- const biomeStart = performance.now();
- console.log('\nRunning biome check...');
- if (isNixOS) {
- const systemBiomePath = await $`bash -c 'PATH=$(echo "$PATH" | tr ":" "\n" | grep -v node_modules | tr "\n" ":") which biome'`.text();
- await $`${systemBiomePath.trim()} check --write --unsafe packages/service-clients/`;
- } else {
- await $`biome check --write --unsafe packages/service-clients/`;
- }
- console.log(`Biome check finished (${elapsed(biomeStart)})`);
-
- // In check mode, verify no uncommitted changes
- if (checkMode) {
- const diff = await $`git diff --ignore-blank-lines ${serviceClientsDir}`.text();
- const untrackedFiles = await $`git ls-files --others --exclude-standard ${serviceClientsDir}`.text();
-
- if (diff.trim() || untrackedFiles.trim()) {
- console.error('\n❌ Generated types are out of sync with Rust API definitions!');
- console.error('The following files have changed:');
- if (diff.trim()) console.error(diff);
- if (untrackedFiles.trim()) console.error('Untracked:\n' + untrackedFiles);
- const gitStatus = await $`git status`.text();
- console.error('`git status` output:')
- console.error(gitStatus.trim());
- console.error('\nPlease run: bun run scripts/generate-api-schema.ts');
- console.error('Then commit the changes.');
- process.exit(1);
- }
-
- console.log('\n✓ Generated types are up to date');
- }
+ const serviceClientsDir = getServiceClientsDir();
+ const checkMode = process.argv.includes("--check");
+ const targetServices = getTargetServices();
+ const servicesToProcess = getServicesToProcess(targetServices);
+
+ // Get crate names for services that have mappings
+ const crateNames = servicesToProcess
+ .map((s) => serviceToCrate[s.name])
+ .filter((crate): crate is string => !!crate);
+
+ console.log(`\nProcessing ${servicesToProcess.length} service(s)...\n`);
+
+ // Phase 1: Build all binaries in a single cargo invocation (parallelized by cargo)
+ const buildStart = performance.now();
+ await buildOpenApiBinaries(crateNames);
+ console.log(`Phase 1 (cargo build) total: ${elapsed(buildStart)}`);
+
+ // Phase 2: Run binaries and generate TypeScript in parallel
+ console.log("\nGenerating TypeScript clients...\n");
+ const results = await Promise.all(
+ servicesToProcess.map((service) =>
+ processService(service, { serviceClientsDir }),
+ ),
+ );
+
+ // Summary report
+ console.log("\nProcessing Summary:");
+ const succeeded = results.filter((r) => r.status === "success");
+ const failed = results.filter((r) => r.status === "failed");
+ const skipped = results.filter((r) => r.status === "skipped");
+
+ console.log(`Succeeded: ${succeeded.length}/${servicesToProcess.length}`);
+ if (skipped.length > 0) {
+ console.log(`Skipped: ${skipped.length}/${servicesToProcess.length}`);
+ }
+ if (failed.length > 0) {
+ console.log(`Failed: ${failed.length}/${servicesToProcess.length}`);
+ failed.forEach((result) => {
+ console.error(` - ${result.service}:`, result.error);
+ });
+ process.exit(1);
+ }
+ // On NixOS, the npm-installed biome binary doesn't work due to dynamic linking issues.
+ // We detect NixOS and use the system biome instead.
+ const isNixOS =
+ process.env.NIX_PATH !== undefined ||
+ ((await Bun.file("/etc/os-release").exists()) &&
+ (await Bun.file("/etc/os-release").text()).includes("NixOS"));
+ const biomeStart = performance.now();
+ console.log("\nRunning biome check...");
+ if (isNixOS) {
+ const systemBiomePath =
+ await $`bash -c 'PATH=$(echo "$PATH" | tr ":" "\n" | grep -v node_modules | tr "\n" ":") which biome'`.text();
+ await $`${systemBiomePath.trim()} check --write --unsafe packages/service-clients/`;
+ } else {
+ await $`biome check --write --unsafe packages/service-clients/`;
+ }
+ console.log(`Biome check finished (${elapsed(biomeStart)})`);
+
+ // In check mode, verify no uncommitted changes
+ if (checkMode) {
+ const diff =
+ await $`git diff --ignore-blank-lines ${serviceClientsDir}`.text();
+ const untrackedFiles =
+ await $`git ls-files --others --exclude-standard ${serviceClientsDir}`.text();
+
+ if (diff.trim() || untrackedFiles.trim()) {
+ console.error(
+ "\n❌ Generated types are out of sync with Rust API definitions!",
+ );
+ console.error("The following files have changed:");
+ if (diff.trim()) console.error(diff);
+ if (untrackedFiles.trim()) console.error("Untracked:\n" + untrackedFiles);
+ const gitStatus = await $`git status`.text();
+ console.error("`git status` output:");
+ console.error(gitStatus.trim());
+ console.error("\nPlease run: bun run scripts/generate-api-schema.ts");
+ console.error("Then commit the changes.");
+ process.exit(1);
+ }
+
+ console.log("\n✓ Generated types are up to date");
+ }
}
await main();
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 76b398da36..e45699bdf9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1837,6 +1837,7 @@ name = "chat"
version = "0.1.0"
dependencies = [
"ai",
+ "ai_toolset",
"anyhow",
"axum",
"chrono",
@@ -6276,6 +6277,7 @@ dependencies = [
"macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
+ "macro_env",
"macro_user_id",
"macro_uuid",
"model_user",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 5b1dc22c39..4ce487dd63 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -19,7 +19,7 @@ connection = { path = "../connection", default-features = false, features = [
"ports",
] }
documents = { path = "../documents", features = ["ai_tools"] }
-email = { path = "../email", features = ["ai_schema", "axum", "outbound"] }
+email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }
email_service_client = { path = "../email_service_client" }
entity_access = { path = "../entity_access" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index b582eefeea..e48e84030e 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -15,6 +15,7 @@ use code_execution::{
anthropic_bash_code_execution_tool, anthropic_text_editor_code_execution_tool,
};
use documents::inbound::toolset::document_toolset;
+use email::inbound::toolset::email_toolset;
use properties::inbound::toolset::properties_toolset;
use search::web::anthropic_web_search::anthropic_web_search_tool;
use soup::inbound::toolset::{ListEntities, SoupToolContext};
@@ -44,7 +45,8 @@ pub fn all_tools() -> ToolSetWithPrompt {
.add_tool::<ListEntities, SoupToolContext<ToolSoupService>>()
.add_tool::<read::ReadThread, Arc<ToolScribe>>()
.add_subtoolset::<ToolDocumentToolContext>(document_toolset())
- .add_subtoolset::<ToolPropertiesToolContext>(properties_toolset());
+ .add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
+ .add_subtoolset::<ToolEmailToolContext>(email_toolset());
let prompt = prompts::TOOLS_PROMPT;
let toolset = Arc::new(toolset);
ToolSetWithPrompt { toolset, prompt }
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index b1f381d80e..3fcf67ec5c 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -5,7 +5,6 @@ use anyhow::anyhow;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use model::chat::ChatHistory;
-use models_email::email::service::message::ParsedMessage;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -34,11 +33,6 @@ pub enum ReadContent {
#[serde(flatten)]
history: ChatHistory,
},
- Email {
- thread_id: String,
- subject: Option<String>,
- messages: Vec<EmailMessage>,
- },
ItemPreviews {
formatted_preview: String,
},
@@ -54,44 +48,10 @@ pub struct DocumentMetadata {
pub deleted: bool,
}
-#[derive(Debug, JsonSchema, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EmailMessage {
- pub message_id: String,
- pub sender: String,
- pub recipients: Vec<String>,
- pub cc: Vec<String>,
- pub bcc: Vec<String>,
- pub content: String,
- pub sent_at: Option<DateTime<Utc>>,
-}
-
-impl From<ParsedMessage> for EmailMessage {
- fn from(msg: ParsedMessage) -> Self {
- Self {
- message_id: msg.db_id.to_string(),
- sender: msg
- .from
- .as_ref()
- .map(|f| f.email.clone())
- .unwrap_or_default(),
- recipients: msg.to.iter().map(|contact| contact.email.clone()).collect(),
- cc: msg.cc.iter().map(|contact| contact.email.clone()).collect(),
- bcc: msg
- .bcc
- .iter()
- .map(|contact| contact.email.clone())
- .collect(),
- content: msg.body_parsed.clone().unwrap_or_default(),
- sent_at: msg.internal_date_ts,
- }
- }
-}
-
#[derive(Debug, JsonSchema, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
- description = "Read threaded content by ID(s). Supports reading channels, chats, emails, 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.
+ description = "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.",
title = "ReadThread"
)]
@@ -101,7 +61,7 @@ pub struct ReadThread {
)]
pub content_type: ContentType,
#[schemars(
- description = "ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and email-message content types support MULTIPLE ids! For all other content types (channel, chat-thread, email-thread) provide a single id."
+ description = "ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and content types support MULTIPLE ids! For all other content types (channel, chat-thread) provide a single id."
)]
pub ids: Vec<String>,
#[schemars(
@@ -119,8 +79,6 @@ pub enum ContentType {
ChannelMessage,
ChatThread,
ChatMessage,
- EmailThread,
- EmailMessage,
Project,
}
@@ -148,8 +106,6 @@ impl AsyncTool<Arc<ToolScribe>> for ReadThread {
ContentType::ChannelMessage => self.read_channel_message(&scribe).await?,
ContentType::ChatThread => self.read_chat_thread(&scribe).await?,
ContentType::ChatMessage => self.read_chat_messages(&scribe).await?,
- ContentType::EmailThread => self.read_email_thread(&scribe).await?,
- ContentType::EmailMessage => self.read_email_message(&scribe).await?,
ContentType::Project => self.read_project(&scribe, &request_context).await?,
};
@@ -312,68 +268,6 @@ impl ReadThread {
Ok(ReadContent::Chat { history })
}
-
- async fn read_email_thread(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {
- let id = self.provide_single_id()?;
- let messages = scribe
- .email
- .get_email_messages_by_thread_id(&id, 0, 100)
- .await
- .map_err(|e| ToolCallError {
- description: format!("failed to fetch email thread messages: {}", e),
- internal_error: e,
- })?;
-
- let subject = messages.first().and_then(|msg| msg.subject.clone());
- let email_messages = messages.into_iter().map(EmailMessage::from).collect();
-
- Ok(ReadContent::Email {
- thread_id: id,
- subject,
- messages: email_messages,
- })
- }
-
- async fn read_email_message(&self, scribe: &ToolScribe) -> Result<ReadContent, ToolCallError> {
- let mut email_messages = Vec::new();
- let mut subject = None;
- let mut thread_id = String::new();
-
- for id in &self.ids {
- let parsed_message = match scribe.email.get_email_message_by_id(id).await {
- Ok(msg) => msg,
- Err(e) => {
- tracing::warn!("failed to fetch email message {}: {}", id, e);
- continue; // Skip failed messages instead of failing the entire request
- }
- };
-
- // Use the subject from the first message
- if subject.is_none() {
- subject = parsed_message.subject.clone();
- }
-
- // Use the thread_id from the first message
- if thread_id.is_empty() {
- thread_id = id.clone();
- }
-
- email_messages.push(EmailMessage::from(parsed_message));
- }
-
- if email_messages.is_empty() {
- return Err(ToolCallError {
- description: "failed to fetch any email messages".to_string(),
- internal_error: anyhow::anyhow!("all email message fetches failed"),
- });
- }
-
- Ok(ReadContent::Email {
- thread_id,
- subject,
- messages: email_messages,
- })
- }
}
#[cfg(test)]
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 560f43cd0d..f20946bee3 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -11,6 +11,7 @@ use documents::{
};
use email::{
domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},
+ inbound::toolset::EmailToolContext,
outbound::EmailPgRepo,
};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -128,6 +129,9 @@ pub type ToolPropertiesService = properties::PropertiesServiceImpl<
/// Type alias for the properties tool context
pub type ToolPropertiesToolContext = PropertiesToolContext<ToolPropertiesService>;
+/// Type alias for the email tool context
+pub type ToolEmailToolContext = EmailToolContext<ToolEmailService>;
+
/// The full service context containing all API clients.
/// Individual tools should extract only the clients they need via `FromRef`.
#[derive(Clone, FromRef)]
@@ -138,6 +142,7 @@ pub struct ToolServiceContext {
pub soup_service: Arc<ToolSoupService>,
pub document_tool_context: ToolDocumentToolContext,
pub properties_tool_context: ToolPropertiesToolContext,
+ pub email_tool_context: ToolEmailToolContext,
}
impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
diff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rs
index 19c98bcf8b..19809d3030 100644
--- a/rust/cloud-storage/ai_toolset/src/context.rs
+++ b/rust/cloud-storage/ai_toolset/src/context.rs
@@ -23,7 +23,7 @@ impl<S> DerefMut for ServiceContext<S> {
}
/// Request context passed into tool calls, containing per-request data like user identity.
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct RequestContext {
/// The ID of the user making the request.
pub user_id: MacroUserIdStr<'static>,
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
index 7de3514ce1..00400f36e3 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs
@@ -74,7 +74,8 @@ where
}
/// Trait object type for tools callable with `ToolSetContext`.
-type AsyncToolTraitObject<ToolSetContext> = Box<dyn ToolSetCallable<ToolSetContext> + Send + Sync>;
+pub(crate) type AsyncToolTraitObject<ToolSetContext> =
+ Box<dyn ToolSetCallable<ToolSetContext> + Send + Sync>;
/// Adapter that wraps a `ToolSetCallable<SubContext>` to work with `ParentContext`.
///
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs
index 3d36a626da..3a56c44b64 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs
@@ -8,6 +8,7 @@ use crate::{RequestContext, ServiceContext};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
/// User tool wrapper type that implements stubs [`AsyncTool`]
#[derive(Serialize, Deserialize)]
@@ -24,14 +25,14 @@ impl<T: JsonSchema> JsonSchema for UserTool<T> {
}
/// User tools are pending until a user executes them
-#[derive(Serialize, JsonSchema)]
-pub enum UserToolResult<T: Serialize + 'static> {
+#[derive(Serialize, Deserialize, JsonSchema, ToSchema, Debug, Clone, PartialEq)]
+pub enum UserToolResponse<T> {
/// Tool has not yet been executed
PendingUserExecution,
- /// Tool is executed and has whatever return type the wrapped tool returns
- Executed(T),
/// User rejected suggested tool execution
Rejected,
+ /// Tool is executed and has whatever return type the wrapped tool returns
+ UserAction(T),
}
#[async_trait]
@@ -41,7 +42,7 @@ where
T: Send + Sync + 'static + for<'de> Deserialize<'de>,
Context: Send + Sync + 'static,
{
- type Output = UserToolResult<T::Output>;
+ type Output = UserToolResponse<T::Output>;
/// Calling a user tool doesn't do anything
async fn call(
@@ -49,6 +50,6 @@ where
_service_context: ServiceContext<Context>,
_request_context: RequestContext,
) -> ToolResult<Self::Output> {
- ToolResult::Ok(UserToolResult::PendingUserExecution)
+ ToolResult::Ok(UserToolResponse::PendingUserExecution)
}
}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
index fb717290a8..020bcdc59d 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
@@ -1,5 +1,5 @@
//! types
-use super::tool_object::{AsyncToolObject, UserTool, ValidationError};
+use super::tool_object::{AsyncToolObject, UserTool, UserToolResponse, ValidationError};
use crate::RequestContext;
use crate::{AsyncTool, ToolResult};
use axum::extract::FromRef;
@@ -88,7 +88,13 @@ impl<T> ToolSet<T> {
panic!("{}", ToolSetCreationError::NameConflict(name.clone()));
}
}
+ for (name, _) in toolset.user_tools.iter() {
+ if self.user_tools.contains_key(name) {
+ panic!("{}", ToolSetCreationError::NameConflict(name.clone()));
+ }
+ }
self.tools.extend(toolset.tools);
+ self.user_tools.extend(toolset.user_tools);
self
}
}
@@ -180,7 +186,7 @@ where
request_context: RequestContext,
tool_name: &str,
json: &serde_json::Value,
- ) -> Result<ToolResult<serde_json::Value>, ToolSetError> {
+ ) -> Result<ToolResult<UserToolResponse<serde_json::Value>>, ToolSetError> {
let tool = self
.user_tools
.get(tool_name)
@@ -189,7 +195,24 @@ where
tool.try_deserialize(json)
.map_err(ToolSetError::Deserialization)
})?;
- Ok(tool.call(context, request_context).await)
+ Ok(tool
+ .call(context, request_context)
+ .await
+ .map(UserToolResponse::UserAction))
+ }
+
+ /// check if json + name matches a known tool in the toolset
+ #[tracing::instrument(skip(self))]
+ pub fn is_valid_tool(&self, tool_name: &str, json: &serde_json::Value) -> bool {
+ let Some(tool) = self
+ .user_tools
+ .get(tool_name)
+ .or_else(|| self.tools.get(tool_name))
+ else {
+ return false;
+ };
+
+ tool.try_deserialize(json).is_ok()
}
/// Merges a subtoolset with a narrower context into this toolset.
@@ -257,6 +280,14 @@ where
let widened = tool.widen::<ToolSetContext>();
self.tools.insert(name, widened);
}
+
+ for (name, tool) in subtoolset.user_tools {
+ if self.user_tools.contains_key(&name) {
+ panic!("{}", ToolSetCreationError::NameConflict(name));
+ }
+ let widened = tool.widen::<ToolSetContext>();
+ self.user_tools.insert(name, widened);
+ }
self
}
}
diff --git a/rust/cloud-storage/chat/.sqlx/query-2434f8a0e387b85009c8857ab719928f6e922ecf302228837e4d0686866ac515.json b/rust/cloud-storage/chat/.sqlx/query-2434f8a0e387b85009c8857ab719928f6e922ecf302228837e4d0686866ac515.json
new file mode 100644
index 0000000000..2b787b4f2b
--- /dev/null
+++ b/rust/cloud-storage/chat/.sqlx/query-2434f8a0e387b85009c8857ab719928f6e922ecf302228837e4d0686866ac515.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"ChatMessage\"\n SET \"content\" = $1, \"updatedAt\" = NOW()\n WHERE \"id\" = $2 AND \"chatId\" = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Jsonb",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2434f8a0e387b85009c8857ab719928f6e922ecf302228837e4d0686866ac515"
+}
diff --git a/rust/cloud-storage/chat/.sqlx/query-6343ce39e05b97056a1e0f7d24f929f7aac2269af2ec0830f98558045826576f.json b/rust/cloud-storage/chat/.sqlx/query-6343ce39e05b97056a1e0f7d24f929f7aac2269af2ec0830f98558045826576f.json
new file mode 100644
index 0000000000..c06bc55385
--- /dev/null
+++ b/rust/cloud-storage/chat/.sqlx/query-6343ce39e05b97056a1e0f7d24f929f7aac2269af2ec0830f98558045826576f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT content\n FROM \"ChatMessage\"\n WHERE \"id\" = $1 AND \"chatId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "content",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6343ce39e05b97056a1e0f7d24f929f7aac2269af2ec0830f98558045826576f"
+}
diff --git a/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json b/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json
index f77b255645..9bfa5673f3 100644
--- a/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json
+++ b/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json
@@ -14,9 +14,9 @@
"kind": {
"Enum": [
"view",
+ "comment",
"edit",
- "owner",
- "comment"
+ "owner"
]
}
}
diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.toml
index 92922e62b9..9f3f7222c6 100644
--- a/rust/cloud-storage/chat/Cargo.toml
+++ b/rust/cloud-storage/chat/Cargo.toml
@@ -18,6 +18,7 @@ ports = []
[dependencies]
# Domain (always included)
ai = { path = "../ai" }
+ai_toolset = { path = "../ai_toolset" }
anyhow = { workspace = true }
chrono = { workspace = true }
entity_access = { path = "../entity_access", default-features = false }
diff --git a/rust/cloud-storage/chat/src/domain/models.rs b/rust/cloud-storage/chat/src/domain/models.rs
index bf863dd6dc..6721fea82a 100644
--- a/rust/cloud-storage/chat/src/domain/models.rs
+++ b/rust/cloud-storage/chat/src/domain/models.rs
@@ -1,6 +1,7 @@
//! Types and errors used by the chat domain ports.
-use ai::types::Model;
+use ai::types::{ChatMessageContent, Model};
+use entity_access::domain::models::AccessError;
use model::chat::{ChatAttachmentWithName, ChatMessageWithAttachments};
use models_permissions::share_permission::access_level::AccessLevel;
use serde::{Deserialize, Serialize};
@@ -19,6 +20,32 @@ pub enum ChatErr {
/// Bad request
#[error("bad request: {0}")]
BadRequest(String),
+ /// Access denied.
+ #[error(transparent)]
+ Access(#[from] AccessError),
+}
+
+#[cfg(feature = "inbound")]
+impl axum::response::IntoResponse for ChatErr {
+ fn into_response(self) -> axum::response::Response {
+ use axum::http::StatusCode;
+
+ let (status, msg) = match &self {
+ ChatErr::NotFound => (StatusCode::NOT_FOUND, "Not found"),
+ ChatErr::BadRequest(_) => (StatusCode::BAD_REQUEST, "Bad request"),
+ ChatErr::Access(
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),
+ ) => (StatusCode::FORBIDDEN, "Forbidden"),
+ ChatErr::Access(AccessError::NotFound(_)) => (StatusCode::NOT_FOUND, "Not found"),
+ ChatErr::Access(AccessError::BadRequest(_)) => (StatusCode::BAD_REQUEST, "Bad request"),
+ ChatErr::Unknown(_) | ChatErr::Access(_) => {
+ tracing::error!(error=?self, "chat handler error");
+ (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
+ }
+ };
+
+ (status, msg.to_string()).into_response()
+ }
}
/// Arguments for creating a new chat.
@@ -111,3 +138,12 @@ pub struct ChatResponse {
/// Whether the chat is persistent or not.
pub is_persistent: bool,
}
+
+/// Arguments for patching a chat message's content.
+#[derive(Debug)]
+pub struct PatchChatMessageArgs {
+ /// The message ID to patch.
+ pub message_id: String,
+ /// The new content for the message.
+ pub content: ChatMessageContent,
+}
diff --git a/rust/cloud-storage/chat/src/domain/ports.rs b/rust/cloud-storage/chat/src/domain/ports.rs
index ae1c9b45da..563ee43b6b 100644
--- a/rust/cloud-storage/chat/src/domain/ports.rs
+++ b/rust/cloud-storage/chat/src/domain/ports.rs
@@ -1,6 +1,9 @@
use crate::domain::models::{
ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs,
+ PatchChatMessageArgs,
};
+use ai::types::ChatMessageContent;
+use ai_toolset::tool_object::UserToolResponse;
use entity_access::domain::models::{
EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
@@ -77,6 +80,28 @@ pub trait ChatRepo: Send + Sync + 'static {
chat_id: &str,
args: PatchChatArgs,
) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
+
+ /// Patch a message's content.
+ fn patch_message(
+ &self,
+ chat_id: &str,
+ args: PatchChatMessageArgs,
+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
+
+ /// Get the content of a single message by ID
+ fn get_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ ) -> impl std::future::Future<Output = Result<ChatMessageContent, ChatErr>> + Send;
+
+ /// Update the content of a specific message.
+ fn update_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
}
/// Service trait for chat business logic.
@@ -133,4 +158,39 @@ pub trait ChatService: Send + Sync + 'static {
&self,
entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,
) -> impl std::future::Future<Output = Result<SharePermissionV2, ChatErr>> + Send;
+
+ /// Update a tool call's arguments after validation.
+ fn update_tool_call(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ new_args: serde_json::Value,
+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
+
+ /// Update a tool response.
+ fn update_tool_response(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ response: UserToolResponse<serde_json::Value>,
+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
+
+ /// Execute a pending tool call. Optionally update its arguments first.
+ fn call_tool(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ args: Option<serde_json::Value>,
+ ) -> impl std::future::Future<Output = Result<serde_json::Value, ChatErr>> + Send;
+
+ /// Reject a pending tool call.
+ fn reject_tool_call(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;
}
diff --git a/rust/cloud-storage/chat/src/domain/service.rs b/rust/cloud-storage/chat/src/domain/service.rs
index 04c0c4ed55..3eb51e8395 100644
--- a/rust/cloud-storage/chat/src/domain/service.rs
+++ b/rust/cloud-storage/chat/src/domain/service.rs
@@ -4,36 +4,49 @@ use crate::domain::{
models::{ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs},
ports::{ChatRepo, ChatService},
};
+use ai::types::{AssistantMessagePart, ChatMessageContent};
+use ai_toolset::{AsyncToolSet, RequestContext, tool_object::UserToolResponse};
use entity_access::domain::models::{
- EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::SharePermissionV2;
+use std::sync::Arc;
use unicode_segmentation::UnicodeSegmentation;
-/// Concrete service implementation that delegates to a [`ChatRepo`].
-pub struct ChatServiceImpl<R> {
+/// Concrete service implementation that delegates to a [`ChatRepo`]
+pub struct ChatServiceImpl<R, ToolSetContext>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+{
+ // toolset should be replaced with trait;
+ toolset: Arc<AsyncToolSet<ToolSetContext>>,
+ context: ToolSetContext,
repo: R,
}
-impl<R: ChatRepo> ChatServiceImpl<R> {
- /// Create a new [`ChatServiceImpl`] wrapping the given repo.
- pub fn new(repo: R) -> Self {
- Self { repo }
- }
-}
-
-/// Extract an authenticated user ID from an [`EntityAccessReceipt`], or return an error.
-fn extract_user_id<T: entity_access::domain::models::RequiredPermission>(
- receipt: &EntityAccessReceipt<T>,
-) -> Result<MacroUserIdStr<'static>, ChatErr> {
- match receipt.auth() {
- EntityAccessAuth::Authenticated(id) => Ok(id.clone()),
- _ => Err(ChatErr::Unknown(anyhow::anyhow!("unauthenticated"))),
+impl<R: ChatRepo, ToolSetContext> ChatServiceImpl<R, ToolSetContext>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+{
+ /// Create a new [`ChatServiceImpl`] wrapping the given repo and tool executor.
+ pub fn new(
+ repo: R,
+ toolset: Arc<AsyncToolSet<ToolSetContext>>,
+ context: ToolSetContext,
+ ) -> Self {
+ Self {
+ repo,
+ toolset,
+ context,
+ }
}
}
-impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {
+impl<R: ChatRepo, ToolSetContext> ChatService for ChatServiceImpl<R, ToolSetContext>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+{
#[tracing::instrument(err, skip(self))]
async fn create(
&self,
@@ -52,12 +65,12 @@ impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {
&self,
entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> Result<GetChatResponse, ChatErr> {
- let user_id = extract_user_id(&entity_access_receipt)?;
+ let user_id = entity_access_receipt.get_authenticated_user()?;
let chat_id = &entity_access_receipt.entity().entity_id;
let (chat, access_level) = tokio::join!(
self.repo.get_chat(chat_id),
- self.repo.get_access_level(user_id, chat_id),
+ self.repo.get_access_level(user_id.to_owned(), chat_id),
);
Ok(GetChatResponse {
@@ -71,13 +84,13 @@ impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {
&self,
entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> Result<String, ChatErr> {
- let user_id = extract_user_id(&entity_access_receipt)?;
+ let user_id = entity_access_receipt.get_authenticated_user()?;
let chat_id = &entity_access_receipt.entity().entity_id;
let chat = self.repo.get_metadata(chat_id).await?;
self.repo
.copy_chat(
- user_id,
+ user_id.to_owned(),
chat_id,
CopyChatArgs {
name: format!("{} Copy", chat.name),
@@ -116,10 +129,9 @@ impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {
{
return Err(ChatErr::BadRequest("name too long".to_string()));
}
-
- let user_id = extract_user_id(&entity_access_receipt)?;
+ let user_id = entity_access_receipt.get_authenticated_user()?;
let chat_id = &entity_access_receipt.entity().entity_id;
- self.repo.patch(user_id, chat_id, args).await
+ self.repo.patch(user_id.to_owned(), chat_id, args).await
}
#[tracing::instrument(err, skip(self))]
@@ -142,4 +154,218 @@ impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {
let chat_id = &entity_access_receipt.entity().entity_id;
self.repo.get_permissions(chat_id).await
}
+
+ #[tracing::instrument(err, skip(self, new_args))]
+ async fn update_tool_call(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ new_args: serde_json::Value,
+ ) -> Result<(), ChatErr> {
+ let chat_id = &entity_access_receipt.entity().entity_id;
+
+ let mut parts = self
+ .get_tool_call_parts(chat_id, message_id, tool_call_id)
+ .await?;
+
+ let Some((name, _)) = find_tool_call(&parts, tool_call_id) else {
+ return Err(ChatErr::NotFound);
+ };
+
+ if !self.toolset.is_valid_tool(name, &new_args) {
+ return Err(ChatErr::BadRequest("Invalid tool".into()));
+ }
+
+ update_tool_call_args(&mut parts, tool_call_id, new_args);
+
+ let content = ChatMessageContent::AssistantMessageParts(parts);
+ self.repo
+ .update_message_content(chat_id, message_id, &content)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, response))]
+ async fn update_tool_response(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ response: UserToolResponse<serde_json::Value>,
+ ) -> Result<(), ChatErr> {
+ let chat_id = &entity_access_receipt.entity().entity_id;
+ let mut parts = self
+ .get_tool_call_parts(chat_id, message_id, tool_call_id)
+ .await?;
+
+ let response_json = serde_json::to_value(response).map_err(anyhow::Error::from)?;
+ update_tool_response_json(&mut parts, tool_call_id, response_json);
+
+ let content = ChatMessageContent::AssistantMessageParts(parts);
+ self.repo
+ .update_message_content(chat_id, message_id, &content)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, args))]
+ async fn call_tool(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value, ChatErr> {
+ let user_id = entity_access_receipt.get_authenticated_user()?.to_owned();
+ let chat_id = entity_access_receipt.entity().entity_id.clone();
+
+ let parts = self
+ .get_tool_call_parts(&chat_id, message_id, tool_call_id)
+ .await?;
+
+ let Some((tool_name, stored_args)) = find_tool_call(&parts, tool_call_id) else {
+ return Err(ChatErr::NotFound);
+ };
+ let tool_name = tool_name.to_owned();
+ let args = match args {
+ Some(args) => {
+ self.update_tool_call(
+ entity_access_receipt,
+ message_id,
+ tool_call_id,
+ args.clone(),
+ )
+ .await?;
+ args
+ }
+ None => stored_args.clone(),
+ };
+
+ let request_context = RequestContext { user_id };
+
+ let outcome = self
+ .toolset
+ .try_user_tool_call(self.context.clone(), request_context, &tool_name, &args)
+ .await
+ // this should never happen (validation prevents)
+ .map_err(anyhow::Error::from)?;
+
+ let response_json = match outcome {
+ Ok(user_response) => {
+ serde_json::to_value(user_response).map_err(anyhow::Error::from)?
+ }
+ Err(tool_err) => serde_json::json!({ "error": tool_err.description }),
+ };
+
+ // re-fetch parts since update_tool_call modified them
+ let mut parts = self
+ .get_tool_call_parts(&chat_id, message_id, tool_call_id)
+ .await?;
+
+ update_tool_response_json(&mut parts, tool_call_id, response_json.clone());
+
+ let content = ChatMessageContent::AssistantMessageParts(parts);
+ self.repo
+ .update_message_content(&chat_id, message_id, &content)
+ .await?;
+
+ Ok(response_json)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn reject_tool_call(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ message_id: &str,
+ tool_call_id: &str,
+ ) -> Result<(), ChatErr> {
+ let rejected_json =
+ serde_json::to_value(UserToolResponse::Rejected::<()>).map_err(anyhow::Error::from)?;
+
+ let chat_id = &entity_access_receipt.entity().entity_id;
+ let mut parts = self
+ .get_tool_call_parts(chat_id, message_id, tool_call_id)
+ .await?;
+
+ update_tool_response_json(&mut parts, tool_call_id, rejected_json);
+
+ let content = ChatMessageContent::AssistantMessageParts(parts);
+ self.repo
+ .update_message_content(chat_id, message_id, &content)
+ .await
+ }
+}
+
+impl<R: ChatRepo, ToolSetContext> ChatServiceImpl<R, ToolSetContext>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+{
+ /// Fetch a message's content and extract its AssistantMessageParts,
+ /// verifying the tool_call_id exists within it.
+ async fn get_tool_call_parts(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ tool_call_id: &str,
+ ) -> Result<Vec<AssistantMessagePart>, ChatErr> {
+ let content = self.repo.get_message_content(chat_id, message_id).await?;
+ match content {
+ ChatMessageContent::AssistantMessageParts(parts) => {
+ let has_tool = parts.iter().any(|part| {
+ matches!(part, AssistantMessagePart::ToolCall { id, .. } if id == tool_call_id)
+ });
+ if has_tool {
+ Ok(parts)
+ } else {
+ Err(ChatErr::NotFound)
+ }
+ }
+ _ => Err(ChatErr::BadRequest(
+ "message does not contain tool calls".to_string(),
+ )),
+ }
+ }
+}
+
+fn find_tool_call<'a>(
+ parts: &'a [AssistantMessagePart],
+ tool_call_id: &str,
+) -> Option<(&'a str, &'a serde_json::Value)> {
+ parts.iter().find_map(|part| match part {
+ AssistantMessagePart::ToolCall { id, name, json } if id == tool_call_id => {
+ Some((name.as_str(), json))
+ }
+ _ => None,
+ })
+}
+
+/// Update the json field of the ToolCall part matching the given tool_call_id.
+fn update_tool_call_args(
+ parts: &mut [AssistantMessagePart],
+ tool_call_id: &str,
+ new_args: serde_json::Value,
+) {
+ for part in parts.iter_mut() {
+ if let AssistantMessagePart::ToolCall { id, json, .. } = part
+ && id == tool_call_id
+ {
+ *json = new_args;
+ return;
+ }
+ }
+}
+
+/// Update the json field of the ToolCallResponseJson part matching the given tool_call_id.
+fn update_tool_response_json(
+ parts: &mut [AssistantMessagePart],
+ tool_call_id: &str,
+ new_json: serde_json::Value,
+) {
+ for part in parts.iter_mut() {
+ if let AssistantMessagePart::ToolCallResponseJson { id, json, .. } = part
+ && id == tool_call_id
+ {
+ *json = new_json;
+ return;
+ }
+ }
}
diff --git a/rust/cloud-storage/chat/src/inbound/http/router.rs b/rust/cloud-storage/chat/src/inbound/http/router.rs
index c674df6015..c28a3bcc25 100644
--- a/rust/cloud-storage/chat/src/inbound/http/router.rs
+++ b/rust/cloud-storage/chat/src/inbound/http/router.rs
@@ -2,11 +2,11 @@
use std::sync::Arc;
+use ai_toolset::tool_object::UserToolResponse;
use axum::{
Json, Router,
extract::{FromRef, Path, State},
http::StatusCode,
- response::IntoResponse,
routing::{delete, get, post, put},
};
use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};
@@ -15,13 +15,16 @@ use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;
use model::response::StringIDResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::SharePermissionV2;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::domain::models::{ChatErr, CreateChatArgs, GetChatResponse, PatchChatArgs};
use crate::domain::ports::ChatService;
use crate::inbound::http::extractors::ChatModelAccess;
+/// Type alias for handler results using [`ChatErr`] as the error type.
+type ChatResult<T> = Result<T, ChatErr>;
+
/// Shared state for the chat router, wrapping a [`ChatService`] implementation
/// and an [`EntityAccessService`] for authorization.
pub struct ChatRouterState<S, Svc> {
@@ -93,48 +96,22 @@ pub fn chat_id_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync +
"/{chat_id}/permissions",
get(get_chat_permissions_handler::<S, Svc>),
)
+ .route(
+ "/{chat_id}/tool/update",
+ post(update_tool_call_handler::<S, Svc>),
+ )
+ .route(
+ "/{chat_id}/tool/response/update",
+ post(update_tool_response_handler::<S, Svc>),
+ )
+ .route("/{chat_id}/tool/call", post(call_tool_handler::<S, Svc>))
+ .route(
+ "/{chat_id}/tool/reject",
+ post(reject_tool_call_handler::<S, Svc>),
+ )
.with_state(state)
}
-/// HTTP error type for chat handlers, mapped from [`ChatErr`].
-#[derive(Debug)]
-pub enum ChatHandlerErr {
- /// Something went wrong internally.
- Internal,
- /// The requested resource was not found.
- NotFound,
- /// The request was bad
- BadRequest(String),
-}
-
-impl From<ChatErr> for ChatHandlerErr {
- fn from(err: ChatErr) -> Self {
- match err {
- ChatErr::BadRequest(e) => ChatHandlerErr::BadRequest(e),
- ChatErr::NotFound => ChatHandlerErr::NotFound,
- ChatErr::Unknown(e) => {
- tracing::error!(error=?e, "chat handler error");
- ChatHandlerErr::Internal
- }
- }
- }
-}
-
-impl IntoResponse for ChatHandlerErr {
- fn into_response(self) -> axum::response::Response {
- let (status, msg) = match self {
- ChatHandlerErr::Internal => (
- StatusCode::INTERNAL_SERVER_ERROR,
- "Internal server error".to_string(),
- ),
- ChatHandlerErr::NotFound => (StatusCode::NOT_FOUND, "Not found".to_string()),
- ChatHandlerErr::BadRequest(e) => (StatusCode::BAD_REQUEST, e),
- };
-
- (status, msg).into_response()
- }
-}
-
/// Request body for creating a chat.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -157,14 +134,14 @@ pub struct CreateChatRequest {
)
)]
/// Create a new chat.
-#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id))]
+#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id), err(Debug))]
pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(
State(state): State<ChatRouterState<S, Svc>>,
user: MacroUserExtractor,
// 402 on no perms
_model_access: ChatModelAccess,
Json(req): Json<CreateChatRequest>,
-) -> Result<Json<StringIDResponse>, ChatHandlerErr> {
+) -> ChatResult<Json<StringIDResponse>> {
let id = state
.inner
.create(
@@ -193,12 +170,12 @@ pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(
)
)]
/// Get a chat by ID with messages and web citations.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<Json<GetChatResponse>, ChatHandlerErr> {
+) -> ChatResult<Json<GetChatResponse>> {
let response = state.inner.get_chat(access.entity_access_receipt).await?;
Ok(Json(response))
@@ -217,12 +194,12 @@ pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(
)
)]
/// Soft-delete a chat.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<StatusCode, ChatHandlerErr> {
+) -> ChatResult<StatusCode> {
state.inner.delete(access.entity_access_receipt).await?;
Ok(StatusCode::OK)
}
@@ -240,12 +217,12 @@ pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
)
)]
/// Permanently delete a chat and all associated data.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<StatusCode, ChatHandlerErr> {
+) -> ChatResult<StatusCode> {
state
.inner
.permanently_delete(access.entity_access_receipt)
@@ -279,13 +256,13 @@ pub struct PatchChatRequest {
)
)]
/// Patch a chat's name, project, or share permissions.
-#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id), err(Debug))]
pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
Json(req): Json<PatchChatRequest>,
-) -> Result<StatusCode, ChatHandlerErr> {
+) -> ChatResult<StatusCode> {
state
.inner
.patch(
@@ -315,12 +292,12 @@ pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(
)
)]
/// Copy a chat and its messages into a new chat.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<Json<StringIDResponse>, ChatHandlerErr> {
+) -> ChatResult<Json<StringIDResponse>> {
let id = state.inner.copy_chat(access.entity_access_receipt).await?;
Ok(Json(StringIDResponse { id }))
}
@@ -338,12 +315,12 @@ pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(
)
)]
/// Revert a soft-deleted chat.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn revert_delete_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<StatusCode, ChatHandlerErr> {
+) -> ChatResult<StatusCode> {
state
.inner
.revert_delete(access.entity_access_receipt)
@@ -372,15 +349,219 @@ pub struct GetChatPermissionsResponse {
)
)]
/// Get the share permissions for a chat.
-#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]
+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id), err(Debug))]
pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessService>(
access: ChatAccessLevelExtractor<EditAccessLevel, Svc>,
State(state): State<ChatRouterState<S, Svc>>,
Path(chat_id): Path<String>,
-) -> Result<Json<GetChatPermissionsResponse>, ChatHandlerErr> {
+) -> ChatResult<Json<GetChatPermissionsResponse>> {
let permissions = state
.inner
.get_permissions(access.entity_access_receipt)
.await?;
Ok(Json(GetChatPermissionsResponse { permissions }))
}
+
+// --- Tool handlers ---
+
+/// Request body for updating a tool call's arguments.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateToolCallRequest {
+ /// The message ID containing the tool call.
+ pub message_id: String,
+ /// The tool call ID to update.
+ pub tool_call_id: String,
+ /// The new arguments for the tool call.
+ pub args: serde_json::Value,
+}
+
+/// Request body for updating a tool response.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateToolResponseRequest {
+ /// The message ID containing the tool response.
+ pub message_id: String,
+ /// The tool call ID whose response should be updated.
+ pub tool_call_id: String,
+ /// The new user tool response.
+ pub response: UserToolResponse<serde_json::Value>,
+}
+
+/// Request body for executing a pending tool call.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CallToolRequest {
+ /// The message ID containing the tool call.
+ pub message_id: String,
+ /// The tool call ID to execute.
+ pub tool_call_id: String,
+ /// Optional updated arguments. Uses original args if omitted.
+ pub args: Option<serde_json::Value>,
+}
+
+/// Response body for a successful tool call.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct CallToolResponse {
+ /// The tool execution result.
+ pub result: serde_json::Value,
+}
+
+/// Request body for rejecting a pending tool call.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RejectToolCallRequest {
+ /// The message ID containing the tool call.
+ pub message_id: String,
+ /// The tool call ID to reject.
+ pub tool_call_id: String,
+}
+
+#[utoipa::path(
+ post,
+ path = "/chats/{chat_id}/tool/update",
+ tag = "chats",
+ operation_id = "update_tool_call",
+ params(("chat_id" = String, Path, description = "ID of the chat")),
+ request_body = UpdateToolCallRequest,
+ responses(
+ (status = 200, description = "Tool call args updated"),
+ (status = 400, body = String, description = "Validation failed"),
+ (status = 404, body = String, description = "Tool call not found"),
+ (status = 500, body = String),
+ )
+)]
+/// Update a tool call's arguments after validation.
+#[tracing::instrument(
+ skip(state, access, req),
+ fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
+ err(Debug)
+)]
+pub async fn update_tool_call_handler<S: ChatService, Svc: EntityAccessService>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
+ State(state): State<ChatRouterState<S, Svc>>,
+ Path(chat_id): Path<String>,
+ Json(req): Json<UpdateToolCallRequest>,
+) -> ChatResult<StatusCode> {
+ state
+ .inner
+ .update_tool_call(
+ access.entity_access_receipt,
+ &req.message_id,
+ &req.tool_call_id,
+ req.args,
+ )
+ .await?;
+ Ok(StatusCode::OK)
+}
+
+#[utoipa::path(
+ post,
+ path = "/chats/{chat_id}/tool/response/update",
+ tag = "chats",
+ operation_id = "update_tool_response",
+ params(("chat_id" = String, Path, description = "ID of the chat")),
+ request_body = UpdateToolResponseRequest,
+ responses(
+ (status = 200, description = "Tool response updated"),
+ (status = 404, body = String, description = "Tool call not found"),
+ (status = 500, body = String),
+ )
+)]
+/// Update a tool response.
+#[tracing::instrument(
+ skip(state, access, req),
+ fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
+ err(Debug)
+)]
+pub async fn update_tool_response_handler<S: ChatService, Svc: EntityAccessService>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
+ State(state): State<ChatRouterState<S, Svc>>,
+ Path(chat_id): Path<String>,
+ Json(req): Json<UpdateToolResponseRequest>,
+) -> ChatResult<StatusCode> {
+ state
+ .inner
+ .update_tool_response(
+ access.entity_access_receipt,
+ &req.message_id,
+ &req.tool_call_id,
+ req.response,
+ )
+ .await?;
+ Ok(StatusCode::OK)
+}
+
+#[utoipa::path(
+ post,
+ path = "/chats/{chat_id}/tool/call",
+ tag = "chats",
+ operation_id = "call_tool",
+ params(("chat_id" = String, Path, description = "ID of the chat")),
+ request_body = CallToolRequest,
+ responses(
+ (status = 200, body = CallToolResponse, description = "Tool executed successfully"),
+ (status = 400, body = String, description = "Validation or execution failed"),
+ (status = 404, body = String, description = "Tool call not found"),
+ (status = 500, body = String),
+ )
+)]
+/// Execute a pending tool call, optionally with updated arguments.
+#[tracing::instrument(
+ skip(state, access, req),
+ fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
+ err(Debug)
+)]
+pub async fn call_tool_handler<S: ChatService, Svc: EntityAccessService>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
+ State(state): State<ChatRouterState<S, Svc>>,
+ Path(chat_id): Path<String>,
+ Json(req): Json<CallToolRequest>,
+) -> ChatResult<Json<CallToolResponse>> {
+ let result = state
+ .inner
+ .call_tool(
+ access.entity_access_receipt,
+ &req.message_id,
+ &req.tool_call_id,
+ req.args,
+ )
+ .await?;
+ Ok(Json(CallToolResponse { result }))
+}
+
+#[utoipa::path(
+ post,
+ path = "/chats/{chat_id}/tool/reject",
+ tag = "chats",
+ operation_id = "reject_tool_call",
+ params(("chat_id" = String, Path, description = "ID of the chat")),
+ request_body = RejectToolCallRequest,
+ responses(
+ (status = 200, description = "Tool call rejected"),
+ (status = 404, body = String, description = "Tool call not found"),
+ (status = 500, body = String),
+ )
+)]
+/// Reject a pending tool call.
+#[tracing::instrument(
+ skip(state, access, req),
+ fields(chat_id = %chat_id, message_id = %req.message_id, tool_call_id = %req.tool_call_id),
+ err(Debug)
+)]
+pub async fn reject_tool_call_handler<S: ChatService, Svc: EntityAccessService>(
+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,
+ State(state): State<ChatRouterState<S, Svc>>,
+ Path(chat_id): Path<String>,
+ Json(req): Json<RejectToolCallRequest>,
+) -> ChatResult<StatusCode> {
+ state
+ .inner
+ .reject_tool_call(
+ access.entity_access_receipt,
+ &req.message_id,
+ &req.tool_call_id,
+ )
+ .await?;
+ Ok(StatusCode::OK)
+}
diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rs
index 387e2d08e0..f625e43260 100644
--- a/rust/cloud-storage/chat/src/inbound/test.rs
+++ b/rust/cloud-storage/chat/src/inbound/test.rs
@@ -14,6 +14,7 @@ use crate::domain::models::{
ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs,
};
use crate::domain::ports::ChatService;
+use ai_toolset::tool_object::UserToolResponse;
use entity_access::domain::models::{
AccessError, AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType,
OwnerAccessLevel, ViewAccessLevel,
@@ -101,6 +102,48 @@ impl ChatService for MockService {
) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {
Err(ChatErr::Unknown(anyhow::anyhow!("not implemented")))
}
+
+ async fn update_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _new_args: serde_json::Value,
+ ) -> Result<(), ChatErr> {
+ Ok(())
+ }
+
+ async fn update_tool_response(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _response: UserToolResponse<serde_json::Value>,
+ ) -> Result<(), ChatErr> {
+ Ok(())
+ }
+
+ async fn call_tool(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value, ChatErr> {
+ Ok(serde_json::json!({
+ "argsWasProvided": _args.is_some(),
+ "args": _args,
+ }))
+ }
+
+ async fn reject_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ ) -> Result<(), ChatErr> {
+ Ok(())
+ }
}
struct ErrorService;
@@ -163,6 +206,45 @@ impl ChatService for ErrorService {
) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {
Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
}
+
+ async fn update_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _new_args: serde_json::Value,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
+ }
+
+ async fn update_tool_response(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _response: UserToolResponse<serde_json::Value>,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
+ }
+
+ async fn call_tool(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value, ChatErr> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
+ }
+
+ async fn reject_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
+ }
}
struct NotFoundService;
@@ -225,6 +307,45 @@ impl ChatService for NotFoundService {
) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {
Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
}
+
+ async fn update_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _new_args: serde_json::Value,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::NotFound)
+ }
+
+ async fn update_tool_response(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _response: UserToolResponse<serde_json::Value>,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::NotFound)
+ }
+
+ async fn call_tool(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value, ChatErr> {
+ Err(ChatErr::NotFound)
+ }
+
+ async fn reject_tool_call(
+ &self,
+ _receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ _message_id: &str,
+ _tool_call_id: &str,
+ ) -> Result<(), ChatErr> {
+ Err(ChatErr::NotFound)
+ }
}
#[derive(Clone)]
@@ -535,3 +656,104 @@ async fn get_permissions_repo_error_returns_500() {
let res = error_id_router().oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
+
+// -- tool handler tests --
+
+#[tokio::test]
+async fn update_tool_call_returns_ok() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/some-chat-id/tool/update")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"messageId":"message-1","toolCallId":"tool-1","args":{"x":1}}"#,
+ ))
+ .unwrap();
+
+ let res = mock_id_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+}
+
+#[tokio::test]
+async fn update_tool_response_returns_ok() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/some-chat-id/tool/response/update")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"messageId":"message-1","toolCallId":"tool-1","response":{"UserAction":{"draftId":"draft-1"}}}"#,
+ ))
+ .unwrap();
+
+ let res = mock_id_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+}
+
+#[tokio::test]
+async fn call_tool_returns_result() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/some-chat-id/tool/call")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"messageId":"message-1","toolCallId":"tool-1","args":{"x":1}}"#,
+ ))
+ .unwrap();
+
+ let res = mock_id_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body = res.into_body().collect().await.unwrap().to_bytes();
+ let response: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ response,
+ serde_json::json!({
+ "result": {
+ "argsWasProvided": true,
+ "args": { "x": 1 },
+ }
+ })
+ );
+}
+
+#[tokio::test]
+async fn call_tool_forwards_missing_args() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/some-chat-id/tool/call")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"messageId":"message-1","toolCallId":"tool-1"}"#,
+ ))
+ .unwrap();
+
+ let res = mock_id_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let body = res.into_body().collect().await.unwrap().to_bytes();
+ let response: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ response,
+ serde_json::json!({
+ "result": {
+ "argsWasProvided": false,
+ "args": null,
+ }
+ })
+ );
+}
+
+#[tokio::test]
+async fn reject_tool_call_returns_ok() {
+ let req = Request::builder()
+ .method("POST")
+ .uri("/some-chat-id/tool/reject")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"messageId":"message-1","toolCallId":"tool-1"}"#,
+ ))
+ .unwrap();
+
+ let res = mock_id_router().oneshot(req).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+}
diff --git a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs
index 41372d59fa..65678e2019 100644
--- a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs
+++ b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs
@@ -5,10 +5,11 @@ mod queries;
mod test;
use crate::domain::models::{
- ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatArgs, WebCitation,
+ ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatArgs, PatchChatMessageArgs,
+ WebCitation,
};
use crate::domain::ports::ChatRepo;
-use ai::types::Model;
+use ai::types::{ChatMessageContent, Model};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::ChatMessageWithAttachments;
@@ -307,4 +308,45 @@ impl ChatRepo for PgChatRepo {
tx.commit().await.map_err(|e| ChatErr::Unknown(e.into()))?;
Ok(())
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn patch_message(
+ &self,
+ chat_id: &str,
+ args: PatchChatMessageArgs,
+ ) -> Result<(), ChatErr> {
+ queries::update_message_content::update_message_content(
+ &self.pool,
+ chat_id,
+ &args.message_id,
+ &args.content,
+ )
+ .await
+ .map_err(to_chat_err)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ ) -> Result<ChatMessageContent, ChatErr> {
+ queries::get_message_content::get_message_content(&self.pool, chat_id, message_id)
+ .await
+ .map_err(to_chat_err)
+ }
+
+ #[tracing::instrument(err, skip(self, content))]
+ async fn update_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+ ) -> Result<(), ChatErr> {
+ queries::update_message_content::update_message_content(
+ &self.pool, chat_id, message_id, content,
+ )
+ .await
+ .map_err(to_chat_err)
+ }
}
diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_message_content.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_message_content.rs
new file mode 100644
index 0000000000..5a422b1d78
--- /dev/null
+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_message_content.rs
@@ -0,0 +1,27 @@
+//! Query to fetch a single message's content by ID, scoped to a chat.
+
+use ai::types::ChatMessageContent;
+use sqlx::PgPool;
+
+/// Fetch the content of a single message by ID, scoped to the given chat.
+#[tracing::instrument(err, skip(pool))]
+pub(crate) async fn get_message_content(
+ pool: &PgPool,
+ chat_id: &str,
+ message_id: &str,
+) -> anyhow::Result<ChatMessageContent> {
+ let row = sqlx::query!(
+ r#"
+ SELECT content
+ FROM "ChatMessage"
+ WHERE "id" = $1 AND "chatId" = $2
+ "#,
+ message_id,
+ chat_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ let content = serde_json::from_value::<ChatMessageContent>(row.content)?;
+ Ok(content)
+}
diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs
index c9df3f517d..e434dd2d30 100644
--- a/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs
+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs
@@ -5,6 +5,7 @@ pub(crate) mod create_chat_permission;
pub(crate) mod edit_share_permission;
pub(crate) mod get_access_level;
pub(crate) mod get_chat;
+pub(crate) mod get_message_content;
pub(crate) mod get_messages;
pub(crate) mod get_permissions;
pub(crate) mod get_web_citations;
@@ -14,5 +15,6 @@ pub(crate) mod patch_chat;
pub(crate) mod permanently_delete_chat;
pub(crate) mod revert_delete_chat;
pub(crate) mod soft_delete_chat;
+pub(crate) mod update_message_content;
pub(crate) mod upsert_item_last_accessed;
pub(crate) mod upsert_user_history;
diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/update_message_content.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/update_message_content.rs
new file mode 100644
index 0000000000..0c6c1a0e07
--- /dev/null
+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/update_message_content.rs
@@ -0,0 +1,30 @@
+//! Query to update a chat message's content.
+
+use ai::types::ChatMessageContent;
+use sqlx::PgPool;
+
+/// Update the content of a specific message, scoped to the chat.
+#[tracing::instrument(err, skip(pool, content))]
+pub(crate) async fn update_message_content(
+ pool: &PgPool,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+) -> anyhow::Result<()> {
+ let content_json = serde_json::to_value(content)?;
+
+ sqlx::query!(
+ r#"
+ UPDATE "ChatMessage"
+ SET "content" = $1, "updatedAt" = NOW()
+ WHERE "id" = $2 AND "chatId" = $3
+ "#,
+ content_json,
+ message_id,
+ chat_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs
index 166a117e5b..5210c5e940 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs
@@ -1,6 +1,5 @@
pub mod chat_history;
pub mod chat_history_batch_messages;
-pub mod tool;
use super::context::ApiContext;
use axum::{
@@ -18,7 +17,12 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
let access_repo = PgAccessRepository::new(state.db.clone());
let access_service = EntityAccessServiceImpl::new(access_repo);
let chat_repo = PgChatRepo::new(state.db.clone());
- let chat_service = ChatServiceImpl::new(chat_repo);
+
+ let chat_service = ChatServiceImpl::new(
+ chat_repo,
+ state.all_tools.clone(),
+ state.tool_service_context.clone(),
+ );
let chat_state = ChatRouterState::new(chat_service, access_service);
let ensure_chat_exists = axum::middleware::from_fn_with_state(
@@ -55,16 +59,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.layer(ensure_chat_exists.clone()),
),
)
- .nest(
- "/{chat_id}/tool",
- tool::router().layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(ensure_chat_exists.clone()),
- ),
- )
// History routes — remain in DCS
.route(
"/history/{chat_id}",
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rs
deleted file mode 100644
index 6a4a4f3982..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-mod post;
-
-use crate::api::context::ApiContext;
-use axum::{Router, routing::post};
-
-pub fn router() -> Router<ApiContext> {
- Router::new().route("/", post(post::handler))
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs
deleted file mode 100644
index ce30190935..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs
+++ /dev/null
@@ -1,277 +0,0 @@
-// This API is designed to suppot "user tools". These are tools that give the user
-// the choice to accept/reject as well as the option to edit a tool before it's executed.
-//
-// The AI will generate a tool call and stub it's response with "pending" then continue
-// executing.
-//
-// If a user likes the tool result and wants to execute the tool they'll hit this API.
-// This API will execute the tool. It will use the message chain as the source of truth / storage
-// which will be a bit of an ugly implementation. This means that if the user chooses to reject
-// the response should be update fromp pending -> rejected. If the user chooses to execute the tool
-// the response should be appropriately updated to reflect the result.
-//
-// The API supports edits by taking an optional "args" field that must match the shape of the named tool.
-// The toolset will validate this shape for you. In the case that args are provided _both_ the response
-// and call need to be updated
-//
-// You'll need to write some SQLX queries to do all of this. Put each query in it's own function. Put queries
-// in the service module of this crate.
-//
-use crate::api::context::ApiContext;
-use crate::service::tool::{get_chat_messages, update_message_content};
-use ai::types::{AssistantMessagePart, ChatMessageContent};
-use ai_tools::{RequestContext, ToolServiceContext, all_tools};
-use ai_toolset::tool_object::UserToolResult;
-use axum::extract::{Json, Path, State};
-use axum::http::StatusCode;
-use axum::response::{IntoResponse, Response};
-use entity_access::domain::models::OwnerAccessLevel;
-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;
-use model::user::axum_extractor::MacroUserExtractor;
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(tag = "action", rename_all = "lowercase")]
-pub enum ToolPostRequest {
- Reject {
- tool_id: String,
- },
- Accept {
- tool_id: String,
- args: Option<Value>,
- },
-}
-
-impl ToolPostRequest {
- pub fn tool_id(&self) -> &str {
- match self {
- Self::Accept { tool_id, .. } | Self::Reject { tool_id, .. } => tool_id,
- }
- }
-}
-
-#[derive(Serialize)]
-struct ToolPostResponse {
- result: Value,
-}
-
-/// execute a saved tool
-#[utoipa::path(
- post,
- path = "/chats/{chat_id}/tool",
- request_body = Value,
- responses(
- (status = 200, body = Value),
- (status = 404, body = String),
- (status = 500, body = String),
- ),
- params(
- ("chat_id" = String, Path, description = "Chat id")
- )
-)]
-#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.macro_user_id))]
-pub async fn handler(
- _access: ChatAccessLevelExtractor<OwnerAccessLevel>,
- State(state): State<ApiContext>,
- user: MacroUserExtractor,
- Path(chat_id): Path<String>,
- Json(request): Json<ToolPostRequest>,
-) -> Result<Response, Response> {
- let messages = get_chat_messages(&state.db, &chat_id)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to fetch chat messages"))
- .map_err(|_| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to fetch chat messages",
- )
- .into_response()
- })?;
-
- let tool_id = request.tool_id().to_owned();
-
- // Find the message containing the tool call with this ID
- let (message_id, mut parts) = messages
- .into_iter()
- .find_map(|msg| match msg.content {
- ChatMessageContent::AssistantMessageParts(parts) => {
- let has_tool = parts.iter().any(|part| {
- matches!(
- part,
- AssistantMessagePart::ToolCall { id, .. } if *id == tool_id
- )
- });
- if has_tool {
- Some((msg.id, parts))
- } else {
- None
- }
- }
- _ => None,
- })
- .ok_or_else(|| (StatusCode::NOT_FOUND, "tool call not found").into_response())?;
-
- // Extract tool name and original args from the tool call
- let (tool_name, original_args) = parts
- .iter()
- .find_map(|part| match part {
- AssistantMessagePart::ToolCall { name, json, id } if *id == tool_id => {
- Some((name.clone(), json.clone()))
- }
- _ => None,
- })
- .expect("tool call must exist since we found the message above");
-
- match request {
- ToolPostRequest::Reject { .. } => {
- // Update the tool response from Pending -> Rejected
- let rejected = serde_json::to_value(UserToolResult::<Value>::Rejected)
- .expect("UserToolResult serialization cannot fail");
- update_tool_response(&mut parts, &tool_id, rejected);
-
- let content = ChatMessageContent::AssistantMessageParts(parts);
- update_message_content(&state.db, &message_id, &content)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to update message content"))
- .map_err(|_| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to update message",
- )
- .into_response()
- })?;
-
- Ok(StatusCode::OK.into_response())
- }
- ToolPostRequest::Accept { args, .. } => {
- let exec_args = args.as_ref().unwrap_or(&original_args);
-
- // If user provided custom args, update the tool call args
- if let Some(ref custom_args) = args {
- update_tool_call_args(&mut parts, &tool_id, custom_args.clone());
- }
-
- // Construct toolset and execute
- let toolset = all_tools().toolset;
-
- let tool_context = ToolServiceContext {
- email_service_client: state.email_service_client_external.clone(),
- search_service_client: state.search_service_client.clone(),
- scribe: state.scribe.clone(),
- soup_service: state.soup_service.clone(),
- document_tool_context: state.document_tool_context.clone(),
- properties_tool_context: state.properties_tool_context.clone(),
- };
-
- let request_context = RequestContext {
- user_id: user.macro_user_id,
- };
-
- let tool_result = toolset
- .try_user_tool_call(tool_context, request_context, &tool_name, exec_args)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "toolset error");
- (StatusCode::BAD_REQUEST, e.to_string()).into_response()
- })?;
-
- let response_json = match tool_result {
- Ok(result) => serde_json::to_value(UserToolResult::Executed(result))
- .expect("UserToolResult serialization cannot fail"),
- Err(tool_err) => {
- tracing::error!(error=?tool_err.internal_error, "tool execution failed");
-
- // Replace the response with a ToolCallErr
- replace_tool_response_with_err(
- &mut parts,
- &tool_id,
- &tool_name,
- &tool_err.description,
- );
-
- let content = ChatMessageContent::AssistantMessageParts(parts);
- update_message_content(&state.db, &message_id, &content)
- .await
- .inspect_err(
- |e| tracing::error!(error=?e, "failed to update message after tool error"),
- )
- .map_err(|_| {
- (StatusCode::INTERNAL_SERVER_ERROR, "failed to update message")
- .into_response()
- })?;
-
- return Err(
- (StatusCode::UNPROCESSABLE_ENTITY, tool_err.description).into_response()
- );
- }
- };
-
- update_tool_response(&mut parts, &tool_id, response_json.clone());
-
- let content = ChatMessageContent::AssistantMessageParts(parts);
- update_message_content(&state.db, &message_id, &content)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to update message content"))
- .map_err(|_| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to update message",
- )
- .into_response()
- })?;
-
- Ok((
- StatusCode::OK,
- Json(ToolPostResponse {
- result: response_json,
- }),
- )
- .into_response())
- }
- }
-}
-
-/// Updates the json field of the ToolCallResponseJson part matching the given tool_id.
-fn update_tool_response(parts: &mut [AssistantMessagePart], tool_id: &str, new_json: Value) {
- for part in parts.iter_mut() {
- if let AssistantMessagePart::ToolCallResponseJson { id, json, .. } = part
- && id == tool_id
- {
- *json = new_json;
- return;
- }
- }
-}
-
-/// Updates the json (args) field of the ToolCall part matching the given tool_id.
-fn update_tool_call_args(parts: &mut [AssistantMessagePart], tool_id: &str, new_args: Value) {
- for part in parts.iter_mut() {
- if let AssistantMessagePart::ToolCall { id, json, .. } = part
- && id == tool_id
- {
- *json = new_args;
- return;
- }
- }
-}
-
-/// Replaces a ToolCallResponseJson with a ToolCallErr for the given tool_id.
-fn replace_tool_response_with_err(
- parts: &mut [AssistantMessagePart],
- tool_id: &str,
- tool_name: &str,
- description: &str,
-) {
- for part in parts.iter_mut() {
- if let AssistantMessagePart::ToolCallResponseJson { id, .. } = part
- && id == tool_id
- {
- *part = AssistantMessagePart::ToolCallErr {
- name: tool_name.to_string(),
- description: description.to_string(),
- id: tool_id.to_string(),
- };
- return;
- }
- }
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index bae25d2ac6..aab1fcfd00 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -1,5 +1,8 @@
use crate::config::Config;
-use ai_tools::{ToolDocumentToolContext, ToolPropertiesToolContext, ToolSoupService};
+use ai_tools::{
+ AiToolSet, ToolDocumentToolContext, ToolEmailToolContext, ToolPropertiesToolContext,
+ ToolServiceContext, ToolSoupService,
+};
use axum::extract::FromRef;
use connection_gateway::service::connection::ConnectionRepo;
use document_storage_service_client::DocumentStorageServiceClient;
@@ -49,6 +52,10 @@ pub struct ApiContext {
pub document_tool_context: ToolDocumentToolContext,
pub memory_service: Arc<DcsMemoryService>,
pub properties_tool_context: ToolPropertiesToolContext,
+ pub email_tool_context: ToolEmailToolContext,
+ pub tool_service_context: ToolServiceContext,
+ pub all_tools: Arc<AiToolSet>,
+ pub all_tools_prompt: &'static str,
}
pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
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 e16f292a86..2b1374a93f 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
@@ -261,20 +261,42 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let properties_tool_context =
properties::inbound::toolset::PropertiesToolContext::new(properties_service);
- let memory_tool_context = ai_tools::ToolServiceContext {
+ let email_tool_context = email::inbound::toolset::EmailToolContext::new(
+ Arc::new(email::domain::service::EmailServiceImpl::new(
+ email::outbound::EmailPgRepo::new(pool.clone()),
+ frecency::domain::services::FrecencyQueryServiceImpl::new(
+ frecency::outbound::postgres::FrecencyPgStorage::new(pool.clone()),
+ ),
+ email::domain::ports::NoOpEnqueuer,
+ 0,
+ )),
+ Arc::new(email::domain::ports::NoOpGmailTokenProvider),
+ Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ ),
+ );
+
+ let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
scribe: scribe.clone(),
soup_service: soup_service.clone(),
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
+ email_tool_context: email_tool_context.clone(),
};
+ let all_tools = ai_tools::all_tools();
+ let all_tools_toolset = all_tools.toolset.clone();
+ let all_tools_prompt = all_tools.prompt;
+
let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(
pool.clone(),
memory_repo,
- memory_tool_context,
- ai_tools::all_tools(),
+ tool_service_context.clone(),
+ all_tools,
));
let api_context = ApiContext {
@@ -295,6 +317,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
document_tool_context,
memory_service,
properties_tool_context,
+ email_tool_context,
+ tool_service_context,
+ all_tools: all_tools_toolset,
+ all_tools_prompt,
};
Arc::new(api_context)
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
index 5bda036606..9748affba6 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
@@ -1,6 +1,6 @@
//! HTTP endpoint for sending chat messages with streaming responses.
use super::util::chat_message::ai_request::build_chat_completion_request;
-use super::util::chat_message::toolset::choose_toolset;
+use super::util::chat_message::toolset::choose_tools_prompt;
use super::util::chat_message::{store_conversation_messages, store_incoming_message};
use super::util::chat_permissions;
use crate::api::context::ApiContext;
@@ -12,7 +12,7 @@ use crate::service::notification::notify;
use ai::tool::ToolLoop;
use ai::tool::types::StreamPart;
use ai::types::{AssistantMessagePart, Model};
-use ai_tools::{AiToolSet, RequestContext, ToolServiceContext};
+use ai_tools::RequestContext;
use async_stream::stream;
use axum::Json;
use axum::extract::{Extension, Request, State};
@@ -243,12 +243,12 @@ pub async fn send_chat_message(
.flatten();
// Build the completion request
- let toolset = choose_toolset(&payload);
+ let tools_prompt = choose_tools_prompt(&payload, ctx.all_tools_prompt);
let ai_request = build_chat_completion_request(
ctx.clone(),
&chat,
&payload,
- toolset.prompt,
+ tools_prompt,
&jwt_token,
user_memory.as_deref(),
(*user_id).clone(),
@@ -277,7 +277,6 @@ pub async fn send_chat_message(
stream_and_save_message(
ctx.clone(),
ai_request,
- toolset.toolset,
(*user_id).clone(),
jwt_token,
actual_chat_id.clone(),
@@ -347,11 +346,10 @@ async fn create_new_chat(
/// Creates a payload stream, publishes it via `from_async_stream`, and stores
/// the conversation messages after the stream finishes.
#[expect(clippy::too_many_arguments, reason = "matches WS handler signature")]
-#[tracing::instrument(skip(ctx, request, toolset, user_message_content))]
+#[tracing::instrument(skip(ctx, request, user_message_content))]
fn stream_and_save_message(
ctx: Arc<ApiContext>,
request: ai::types::ChatCompletionRequest,
- toolset: Arc<AiToolSet>,
user_id: MacroUserIdStr<'static>,
jwt_token: String,
chat_id: String,
@@ -365,15 +363,9 @@ fn stream_and_save_message(
durable_stream_id: StreamId,
) {
tracing::trace!(request=?request, "streaming chat request");
-
- let tool_context = ToolServiceContext {
- email_service_client: ctx.email_service_client_external.clone(),
- search_service_client: ctx.search_service_client.clone(),
- scribe: ctx.scribe.clone(),
- soup_service: ctx.soup_service.clone(),
- document_tool_context: ctx.document_tool_context.clone(),
- properties_tool_context: ctx.properties_tool_context.clone(),
- };
+ let model = Model::Claude45Haiku;
+ let tool_context = ctx.tool_service_context.clone();
+ let toolset = ctx.all_tools.clone();
let request_context = RequestContext {
user_id: user_id.clone(),
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
index 6b3fbf1f91..e9bdf535dc 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs
@@ -1,11 +1,14 @@
use crate::model::stream::ToolSet;
-use ai_tools::{ToolSetWithPrompt, all_tools, no_tools};
use crate::model::stream::SendChatMessagePayload;
-pub fn choose_toolset(request: &SendChatMessagePayload) -> ToolSetWithPrompt {
+/// Returns the appropriate system prompt for the requested toolset.
+pub fn choose_tools_prompt(
+ request: &SendChatMessagePayload,
+ all_tools_prompt: &'static str,
+) -> &'static str {
match request.toolset {
- ToolSet::All => all_tools(),
- ToolSet::None => no_tools(),
+ ToolSet::All => all_tools_prompt,
+ ToolSet::None => ai_tools::prompts::BASE_PROMPT,
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index f88d7d2741..4c8d8cabba 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -22,7 +22,9 @@ use ai::types::{ModelMetadata, Provider};
use chat::domain::models::{ChatResponse, GetChatResponse, WebCitation};
use chat::inbound::{
- self as chat_inbound, CreateChatRequest, GetChatPermissionsResponse, PatchChatRequest,
+ self as chat_inbound, CallToolRequest, CallToolResponse, CreateChatRequest,
+ GetChatPermissionsResponse, PatchChatRequest, RejectToolCallRequest, UpdateToolCallRequest,
+ UpdateToolResponseRequest,
};
use model::{
@@ -59,6 +61,10 @@ use utoipa::OpenApi;
chat_inbound::permanently_delete_chat_handler,
chat_inbound::patch_chat_handler,
chat_inbound::revert_delete_handler,
+ chat_inbound::update_tool_call_handler,
+ chat_inbound::update_tool_response_handler,
+ chat_inbound::call_tool_handler,
+ chat_inbound::reject_tool_call_handler,
get_models::get_models_handler,
get_chats_for_attachment::get_chats_for_attachment_handler,
citations::get_citation_handler,
@@ -112,6 +118,13 @@ use utoipa::OpenApi;
GetChatPermissionsResponse,
GetChatResponse,
+ // Tool Operations
+ UpdateToolCallRequest,
+ UpdateToolResponseRequest,
+ CallToolRequest,
+ CallToolResponse,
+ RejectToolCallRequest,
+
// Share Permission
UpdateOperation,
diff --git a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
index 4ce92f1a53..e30ed65066 100644
--- a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
+++ b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
@@ -234,6 +234,20 @@ async fn main() -> anyhow::Result<()> {
let properties_tool_context =
properties::inbound::toolset::PropertiesToolContext::new(properties_service);
+ // Build email tool context
+ let email_tool_context = email::inbound::toolset::EmailToolContext::new(
+ Arc::new(EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ email::domain::ports::NoOpEnqueuer,
+ 0,
+ )),
+ Arc::new(email::domain::ports::NoOpGmailTokenProvider),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
+ ))),
+ );
+
// Build the ToolServiceContext
let tool_context = ToolServiceContext {
email_service_client: Arc::new(EmailServiceClientExternal::new(
@@ -261,6 +275,7 @@ async fn main() -> anyhow::Result<()> {
soup_service,
document_tool_context,
properties_tool_context,
+ email_tool_context,
};
tracing::info!("initialized tool context");
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 8c11830057..866f49e8dc 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -274,21 +274,43 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized properties tool context");
- // Build memory service
- let memory_tool_context = ai_tools::ToolServiceContext {
+ // Build email tool context for AI tools
+ let email_tool_context = email::inbound::toolset::EmailToolContext::new(
+ Arc::new(EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ email::domain::ports::NoOpEnqueuer,
+ 0,
+ )),
+ Arc::new(email::domain::ports::NoOpGmailTokenProvider),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
+ ))),
+ );
+
+ tracing::info!("initialized email tool context");
+
+ // Build shared tool context and toolset
+ let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
scribe: scribe.clone(),
soup_service: soup_service.clone(),
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
+ email_tool_context: email_tool_context.clone(),
};
+ let all_tools = ai_tools::all_tools();
+ let all_tools_toolset = all_tools.toolset.clone();
+ let all_tools_prompt = all_tools.prompt;
+
+ // Build memory service
let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(db.clone());
let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(
db.clone(),
memory_repo,
- memory_tool_context,
- ai_tools::all_tools(),
+ tool_service_context.clone(),
+ all_tools,
));
tracing::info!("initialized memory service");
@@ -311,6 +333,10 @@ async fn main() -> anyhow::Result<()> {
document_tool_context,
memory_service,
properties_tool_context,
+ email_tool_context: email_tool_context.clone(),
+ tool_service_context,
+ all_tools: all_tools_toolset,
+ all_tools_prompt,
})
.await
.context("failed to setup and serve api")?;
diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
index addae2269f..fe3465e86c 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs
@@ -2,7 +2,6 @@ use crate::api::context::DcsScribe;
use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;
use ai::types::{Attachment, ImageData};
use ai_format::document::Document;
-use ai_tools::read::EmailMessage;
use macro_user_id::user_id::MacroUserIdStr;
use model::{
chat::{AttachmentType, ChatAttachmentWithName},
@@ -109,18 +108,11 @@ pub async fn fetchium(
.unwrap_or("No Subject")
.to_string();
- let thread = thread
- .into_iter()
- .map(EmailMessage::from)
- .collect::<Vec<_>>();
-
- let formatted_content = ai_tools::read::ReadContent::Email {
- thread_id: attachment.attachment_id.clone(),
- subject: Some(subject.clone()),
- messages: thread,
- };
-
- let content = serde_json::to_string_pretty(&formatted_content)?;
+ let content = thread
+ .iter()
+ .map(serde_json::to_string_pretty)
+ .collect::<Result<Vec<_>, _>>()?
+ .join("\n");
Ok(Attachment::Text(
Document {
diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
index c85dfe6ec2..a1b0d77854 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
@@ -2,4 +2,3 @@ pub mod attachment;
pub mod get_chat;
pub mod id_mapping;
pub mod notification;
-pub mod tool;
diff --git a/rust/cloud-storage/document_cognition_service/src/service/tool.rs b/rust/cloud-storage/document_cognition_service/src/service/tool.rs
deleted file mode 100644
index 1e4e6acef9..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/service/tool.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use ai::types::ChatMessageContent;
-use anyhow::Result;
-use sqlx::{Executor, Postgres};
-
-/// A chat message with only the fields needed for tool operations.
-pub struct ToolMessage {
- pub id: String,
- pub content: ChatMessageContent,
-}
-
-/// Fetches all messages for a chat, returning only id and content.
-#[tracing::instrument(err, skip(db))]
-pub async fn get_chat_messages<'e, T>(db: T, chat_id: &str) -> Result<Vec<ToolMessage>>
-where
- T: Executor<'e, Database = Postgres>,
-{
- let rows = sqlx::query!(
- r#"
- SELECT id, content
- FROM "ChatMessage"
- WHERE "chatId" = $1
- ORDER BY "createdAt" ASC
- "#,
- chat_id
- )
- .fetch_all(db)
- .await?;
-
- rows.into_iter()
- .map(|row| {
- let content = serde_json::from_value::<ChatMessageContent>(row.content)?;
- Ok(ToolMessage {
- id: row.id,
- content,
- })
- })
- .collect()
-}
-
-/// Updates the content of a specific chat message.
-#[tracing::instrument(err, skip(db, content))]
-pub async fn update_message_content<'e, T>(
- db: T,
- message_id: &str,
- content: &ChatMessageContent,
-) -> Result<()>
-where
- T: Executor<'e, Database = Postgres>,
-{
- let content_json = serde_json::to_value(content)?;
-
- sqlx::query!(
- r#"
- UPDATE "ChatMessage"
- SET "content" = $1, "updatedAt" = NOW()
- WHERE "id" = $2
- "#,
- content_json,
- message_id
- )
- .execute(db)
- .await?;
-
- Ok(())
-}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
index 2db9866348..392aecec37 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
@@ -68,7 +68,7 @@ where
{
type Output = ReadContentResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, document_id=?self.document_id), err)]
async fn call(
&self,
service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
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 acbba3880f..acf19ee909 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 GetThread {
+pub struct ReadThread {
/// 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 GetThread {
}
#[async_trait]
-impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for GetThread
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for ReadThread
where
T: EmailService,
G: GmailTokenProvider,
diff --git a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
index f6eca1250e..5f9bcf8823 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
@@ -57,6 +57,8 @@ pub struct ListLabelsResponse {
title = "ListLabels",
description = "List the user's email labels including system labels (INBOX, SENT, DRAFTS, etc.) and any custom user-created labels. Use this to understand how the user's email is organized before filtering or searching by label."
)]
+#[allow(unused)]
+// empty structs can't be deserialized;
pub struct ListLabels {}
#[async_trait]
diff --git a/rust/cloud-storage/email/src/inbound/toolset/mod.rs b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
index 64b011de79..75ca5e97e6 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
@@ -1,8 +1,8 @@
//! Toolset inbound adapter for the Email service.
-mod create_draft;
mod get_thread;
mod list_labels;
+mod send_email;
mod update_thread_labels;
#[cfg(test)]
@@ -17,9 +17,9 @@ use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
-pub use create_draft::{CreateDraft, CreateDraftResponse};
-pub use get_thread::{GetThread, GetThreadResponse};
+pub use get_thread::{GetThreadResponse, ReadThread};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
+pub use send_email::{SendEmail, SendEmailResponse};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
/// Service context for email AI tools.
@@ -97,8 +97,7 @@ where
E: EntityAccessService,
{
AsyncToolSet::new()
- .add_tool::<ListLabels, EmailToolContext<T, G, E>>()
.add_tool::<UpdateThreadLabels, EmailToolContext<T, G, E>>()
- .add_tool::<CreateDraft, EmailToolContext<T, G, E>>()
- .add_tool::<GetThread, EmailToolContext<T, G, E>>()
+ .add_tool::<ReadThread, EmailToolContext<T, G, E>>()
+ .add_user_tool::<SendEmail, EmailToolContext<T, G, E>>()
}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs b/rust/cloud-storage/email/src/inbound/toolset/send_email.rs
similarity index 58%
rename from rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
rename to rust/cloud-storage/email/src/inbound/toolset/send_email.rs
index 9721ad213c..cdd945f887 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/send_email.rs
@@ -1,4 +1,4 @@
-//! CreateDraft tool for composing a new email draft.
+//! SendEmail tool for composing and sending an email in one step.
use crate::domain::{
models::{ContactInfo, CreateDraftInput},
@@ -14,10 +14,10 @@ use uuid::Uuid;
use super::EmailToolContext;
-/// A recipient for an email draft.
+/// A recipient for an email.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
-pub struct DraftRecipient {
+pub struct EmailRecipient {
/// The recipient's email address.
pub email: String,
/// The recipient's display name (optional).
@@ -25,8 +25,8 @@ pub struct DraftRecipient {
pub name: Option<String>,
}
-impl From<DraftRecipient> for ContactInfo {
- fn from(r: DraftRecipient) -> Self {
+impl From<EmailRecipient> for ContactInfo {
+ fn from(r: EmailRecipient) -> Self {
ContactInfo {
email: r.email,
name: r.name,
@@ -35,52 +35,56 @@ impl From<DraftRecipient> for ContactInfo {
}
}
-/// Create a new email draft. The draft is saved but NOT sent.
+/// Compose and send an email. Creates a draft and immediately queues it for delivery.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(
- title = "CreateDraft",
- description = "Create a new email draft that is saved but NOT sent. Use this to compose emails on behalf of the user. The user can review and send the draft themselves. To reply to an existing message, provide the replying_to_id. The body must be plain text only — do not use HTML, Markdown, or any formatting syntax (no **bold**, *italics*, headings, etc.). Just write natural prose with line breaks."
+ title = "SendEmail",
+ description = "Compose and send an email. Creates the message and immediately queues it for delivery. To reply to an existing message, provide the replying_to_id. The body must be plain text only — do not use HTML, Markdown, or any formatting syntax (no **bold**, *italics*, headings, etc.). Just write natural prose with line breaks."
)]
#[serde(rename_all = "camelCase")]
-pub struct CreateDraft {
+pub struct SendEmail {
/// The subject line of the email.
pub subject: String,
/// The plain text body of the email.
pub body: String,
/// The primary recipients (To field).
- pub to: Vec<DraftRecipient>,
+ pub to: Vec<EmailRecipient>,
/// Carbon copy recipients (optional).
#[serde(default)]
- pub cc: Vec<DraftRecipient>,
+ pub cc: Vec<EmailRecipient>,
/// Blind carbon copy recipients (optional).
#[serde(default)]
- pub bcc: Vec<DraftRecipient>,
- /// The ID of a message to reply to (optional). When set, the draft is
- /// created as a reply within the same thread.
+ pub bcc: Vec<EmailRecipient>,
+ /// The ID of a message to reply to (optional). When set, the email is
+ /// sent as a reply within the same thread.
#[serde(default)]
pub replying_to_id: Option<Uuid>,
}
-/// Response from the CreateDraft tool.
+/// Response from the SendEmail tool.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
-pub struct CreateDraftResponse {
- /// The database ID of the newly created draft.
- pub draft_id: Uuid,
- /// The thread ID the draft belongs to.
- pub thread_id: Uuid,
- /// A human-readable summary of the draft.
- pub summary: String,
+pub enum SendEmailResponse {
+ Sent {
+ /// The database ID of the sent message.
+ message_id: Uuid,
+ /// The thread ID the message belongs to.
+ thread_id: Uuid,
+ },
+ ConvertedToDraft {
+ draft_id: Uuid,
+ },
+ UserEdited,
}
#[async_trait]
-impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for CreateDraft
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for SendEmail
where
T: EmailService,
G: GmailTokenProvider,
E: EntityAccessService,
{
- type Output = CreateDraftResponse;
+ type Output = SendEmailResponse;
#[tracing::instrument(skip_all, fields(
user_id=?request_context.user_id,
@@ -92,7 +96,7 @@ where
service_context: ServiceContext<EmailToolContext<T, G, E>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- tracing::info!("Create draft");
+ println!("CALL SEND EMAIL {:?}", request_context);
let link = service_context
.resolve_link(MacroUserIdStr((*request_context.user_id).clone()))
@@ -115,31 +119,18 @@ where
send_time: None,
};
- let created = service_context
+ let sent = service_context
.service
- .create_draft(&link, input)
+ .send_message(&link, input)
.await
.map_err(|e| ToolCallError {
- description: format!("Failed to create draft: {e}"),
+ description: format!("Failed to send email: {e}"),
internal_error: e.into(),
})?;
- let to_display: Vec<&str> = self.to.iter().map(|r| r.email.as_str()).collect();
- let reply_note = if self.replying_to_id.is_some() {
- " (reply)"
- } else {
- ""
- };
- let summary = format!(
- "Draft{reply_note} created with subject \"{}\" to {}.",
- self.subject,
- to_display.join(", ")
- );
-
- Ok(CreateDraftResponse {
- draft_id: created.db_id,
- thread_id: created.thread_db_id,
- summary,
+ Ok(SendEmailResponse::Sent {
+ message_id: sent.db_id,
+ thread_id: sent.thread_db_id,
})
}
}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/test.rs b/rust/cloud-storage/email/src/inbound/toolset/test.rs
index b5bc3ad310..14d121ca78 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/test.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/test.rs
@@ -3,24 +3,6 @@ use super::*;
use ai::generate_tool_input_schema;
use ai::tool::types::tool_object::validate_tool_schema;
-#[test]
-fn test_list_labels_schema_validation() {
- let schema = generate_tool_input_schema!(ListLabels);
-
- let result = validate_tool_schema(&schema);
- assert!(result.is_ok(), "{:?}", result);
-
- let (name, description) = result.unwrap();
- assert_eq!(
- name, "ListLabels",
- "Tool name should match the schemars title"
- );
- assert!(
- description.contains("email labels"),
- "Description should contain expected text"
- );
-}
-
#[test]
fn test_build_summary_empty() {
let summary = build_summary(&[]);
@@ -72,26 +54,26 @@ fn test_update_thread_labels_schema_validation() {
}
#[test]
-fn test_create_draft_schema_validation() {
- let schema = generate_tool_input_schema!(CreateDraft);
+fn test_send_email_schema_validation() {
+ let schema = generate_tool_input_schema!(SendEmail);
let result = validate_tool_schema(&schema);
assert!(result.is_ok(), "{:?}", result);
let (name, description) = result.unwrap();
assert_eq!(
- name, "CreateDraft",
+ name, "SendEmail",
"Tool name should match the schemars title"
);
assert!(
- description.contains("draft"),
+ description.contains("send"),
"Description should contain expected text"
);
}
#[test]
fn test_get_thread_schema_validation() {
- let schema = generate_tool_input_schema!(GetThread);
+ let schema = generate_tool_input_schema!(ReadThread);
let result = validate_tool_schema(&schema);
assert!(result.is_ok(), "{:?}", result);
@@ -106,11 +88,3 @@ fn test_get_thread_schema_validation() {
"Description should contain expected text"
);
}
-
-// run `cargo test -p email inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`
-#[test]
-#[ignore = "prints the input schema"]
-fn print_input_schema() {
- let schema = generate_tool_input_schema!(ListLabels);
- println!("{}", serde_json::to_string_pretty(&schema).unwrap());
-}
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index ae1ce562c9..a9668b49a9 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -196,6 +196,14 @@ pub struct EntityAccessReceipt<T: RequiredPermission> {
}
impl<T: RequiredPermission> EntityAccessReceipt<T> {
+ /// get the authenticated user or error
+ pub fn get_authenticated_user(&self) -> Result<&MacroUserIdStr<'static>, AccessError> {
+ match &self.auth {
+ EntityAccessAuth::Authenticated(user) => Ok(user),
+ _ => Err(AccessError::Unauthorized),
+ }
+ }
+
/// Getter for auth
pub fn auth(&self) -> &EntityAccessAuth {
&self.auth
diff --git a/rust/cloud-storage/macro_env/src/lib.rs b/rust/cloud-storage/macro_env/src/lib.rs
index f101ad84bf..ee0915252a 100644
--- a/rust/cloud-storage/macro_env/src/lib.rs
+++ b/rust/cloud-storage/macro_env/src/lib.rs
@@ -47,7 +47,7 @@ impl Environment {
Ok(Self::from_str(&v)?)
}
- /// attempt to create a new [Environment] falling back to local if we fail to construct
+ /// attempt to create a new [Environment] falling back to prod if we fail to construct
pub fn new_or_prod() -> Self {
Self::new_from_env().unwrap_or(Environment::Production)
}
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
index 9aa1ae46d5..484a16b80d 100644
--- a/rust/cloud-storage/memory/Cargo.toml
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -24,6 +24,7 @@ model_user = { path = "../model_user", features = ["axum"] }
tracing = { workspace = true }
utoipa = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env = { path = "../macro_env" }
# For building ToolServiceContext
comms = { path = "../comms" }
@@ -43,5 +44,5 @@ soup = { path = "../soup", features = ["all"] }
properties = { path = "../properties" }
macro_aws_config = { path = "../macro_aws_config" }
-[dev-dependencies]
+
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 51c19d63ce..17707f156b 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -145,6 +145,20 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<To
let properties_tool_context =
properties::inbound::toolset::PropertiesToolContext::new(properties_service);
+ // Email tool context
+ let email_tool_context = email::inbound::toolset::EmailToolContext::new(
+ Arc::new(EmailServiceImpl::new(
+ EmailPgRepo::new(pool.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
+ email::domain::ports::NoOpEnqueuer,
+ 0,
+ )),
+ Arc::new(email::domain::ports::NoOpGmailTokenProvider),
+ Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ );
+
Ok(ToolServiceContext {
search_service_client: search_client,
email_service_client: email_ext_client,
@@ -152,5 +166,6 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<To
soup_service,
document_tool_context,
properties_tool_context,
+ email_tool_context,
})
}
diff --git a/rust/cloud-storage/memory/src/domain/ports.rs b/rust/cloud-storage/memory/src/domain/ports.rs
index bf70e5fbfc..1fedaaffe2 100644
--- a/rust/cloud-storage/memory/src/domain/ports.rs
+++ b/rust/cloud-storage/memory/src/domain/ports.rs
@@ -23,6 +23,7 @@ pub type Result<T> = std::result::Result<T, MemoryError>;
pub type Memory = String;
/// A memory record with its creation timestamp.
+#[derive(Debug)]
pub struct MemoryRecord {
/// The memory text.
pub memory: Memory,
diff --git a/rust/cloud-storage/memory/src/domain/service.rs b/rust/cloud-storage/memory/src/domain/service.rs
index 5ab4cb42a4..5e6c4dd44b 100644
--- a/rust/cloud-storage/memory/src/domain/service.rs
+++ b/rust/cloud-storage/memory/src/domain/service.rs
@@ -6,6 +6,7 @@ use ai_tools::{ToolServiceContext, ToolSetWithPrompt};
use ai_toolset::RequestContext;
use chrono::Utc;
use futures::stream::StreamExt;
+use macro_env::Environment;
use serde::Deserialize;
static GENERATION_MODEL: Model = Model::Claude46Opus;
@@ -86,7 +87,7 @@ impl<Rpo> MemoryServiceImpl<Rpo> {
}
/// Default max age for memory freshness (7 days).
-const MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
+const MAX_AGE: std::time::Duration = std::time::Duration::from_hours(24 * 7);
impl<Rpo> MemoryService for MemoryServiceImpl<Rpo>
where
@@ -107,7 +108,8 @@ where
None => true,
};
- if needs_generation {
+ let env = Environment::new_or_prod();
+ if needs_generation && !matches!(env, Environment::Local) {
let pool = self.db.clone();
let tool_context = self.tool_context.clone();
let toolset = self.tools.toolset.clone();