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(search): index agent chat sessions (#6307)

Eric Hayese00d041ac754
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index acfe3dbc7d..fb2635c67e 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -6904,12 +6904,14 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/agent_session",
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
+ "crates/bots",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
diff --git a/.sqlx/query-04a02e2ea3a0fda139f1f1bf0398760e96a367cb525d0a551639f12e2b39ef4f.json b/.sqlx/query-04a02e2ea3a0fda139f1f1bf0398760e96a367cb525d0a551639f12e2b39ef4f.json
new file mode 100644
index 0000000000..3fe58816f6
--- /dev/null
+++ b/.sqlx/query-04a02e2ea3a0fda139f1f1bf0398760e96a367cb525d0a551639f12e2b39ef4f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT entity_id\n FROM entity_access\n WHERE entity_type = 'agent_session'\n AND source_id = ANY($1)\n AND (cardinality($2::uuid[]) = 0 OR entity_id = ANY($2))\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "04a02e2ea3a0fda139f1f1bf0398760e96a367cb525d0a551639f12e2b39ef4f"
+}
diff --git a/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json b/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json
new file mode 100644
index 0000000000..aa861305c0
--- /dev/null
+++ b/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = 'channel'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795"
+}
diff --git a/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json b/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json
new file mode 100644
index 0000000000..e027d61cf3
--- /dev/null
+++ b/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'agent_session', 'owner', 'user', 'owner'),\n ($1, 'agent_session', 'channel', 'channel', 'view'),\n ($2, 'chat', 'channel', 'channel', 'view')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4"
+}
diff --git a/.sqlx/query-80ca059d1f6c5019a24b2d3201a4f29885ab42ca675c54f30e49de5423d651fe.json b/.sqlx/query-80ca059d1f6c5019a24b2d3201a4f29885ab42ca675c54f30e49de5423d651fe.json
new file mode 100644
index 0000000000..6d9a666bb9
--- /dev/null
+++ b/.sqlx/query-80ca059d1f6c5019a24b2d3201a4f29885ab42ca675c54f30e49de5423d651fe.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, name, owner_id, bot_id, created_at, modified_at\n FROM agent_session\n WHERE id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "modified_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "80ca059d1f6c5019a24b2d3201a4f29885ab42ca675c54f30e49de5423d651fe"
+}
diff --git a/CLAUDE.md b/CLAUDE.md
index 5c0fc01b15..504499d543 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -54,6 +54,9 @@ This file is the shared entry point: `AGENTS.md` symlinks to `CLAUDE.md`. Edit
- Load Rust configuration through `macro_env_var` / `macro_config`, never
`std::env::var` or hand-rolled wrappers. Register new env vars in Doppler; never
paste secrets into chat or commit them.
+- Across domain crates, depend on the owning domain service or port; only a
+ composition root may construct that crate's outbound adapters. Never import
+ another crate's `outbound` module from an outbound adapter.
- Use `\cd` instead of `cd` to bypass repository shell aliases.
## Before handing off
diff --git a/Cargo.lock b/Cargo.lock
index e098a9aa9c..5eef846ddc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -464,6 +464,7 @@ dependencies = [
"tower 0.5.3",
"tracing",
"utoipa",
+ "uuid",
"workspace-hack",
]
@@ -5237,6 +5238,7 @@ name = "document_storage_service"
version = "0.1.0"
dependencies = [
"activity",
+ "agent_session",
"ai_tools",
"ai_usage",
"analytics_client",
@@ -14505,6 +14507,7 @@ dependencies = [
name = "search_service"
version = "0.1.0"
dependencies = [
+ "agent_session",
"anyhow",
"aws-sdk-secretsmanager",
"axum",
@@ -14537,6 +14540,7 @@ dependencies = [
"opensearch_client",
"properties",
"readonly_pool",
+ "rootcause",
"secretsmanager_client",
"serde",
"serde_json",
diff --git a/apps/docs/AI/mcp/tools/content-search.mdx b/apps/docs/AI/mcp/tools/content-search.mdx
index b4d92c80b3..74e7bd6192 100644
--- a/apps/docs/AI/mcp/tools/content-search.mdx
+++ b/apps/docs/AI/mcp/tools/content-search.mdx
@@ -13,7 +13,7 @@ Search items by their content: document body text; email subject/body/sender/rec
| --- | --- | --- | --- |
| `query` | string | Yes | The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token (or full email address) matching instead of prefix. |
| `matchType` | `"partial"` \| `"exact"` | No | How search tools match query terms. Restricted to partial/exact — the backend also supports regexp and an internal query mode, but those are not offered to the model. |
-| `entityTypes` | (`"documents"` \| `"chats"` \| `"emails"` \| `"channels"` \| `"projects"` \| `"call_records"` \| `"calendar_events"`)[] | No | Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']. Projects and calendar events carry no indexed content, so they never match here — search those by name with NameSearch instead. |
+| `entityTypes` | (`"agent_sessions"` \| `"documents"` \| `"chats"` \| `"emails"` \| `"channels"` \| `"projects"` \| `"call_records"` \| `"calendar_events"`)[] | No | Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']. Projects and calendar events carry no indexed content, so they never match here — search those by name with NameSearch instead. |
| `inbox` | string | No | Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results. |
| `tags` | TagFilter[] | No | Restrict results to items carrying the given tags — any of them by default, every one of them with tagsMatch="all". Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects, call records) can match, so channels are dropped while a tag filter is active. |
| `tagsMatch` | `"any"` \| `"all"` | No | How multiple tag filters combine when filtering items. |
diff --git a/apps/docs/AI/mcp/tools/name-search.mdx b/apps/docs/AI/mcp/tools/name-search.mdx
index 39e432b8c1..e1b15deadd 100644
--- a/apps/docs/AI/mcp/tools/name-search.mdx
+++ b/apps/docs/AI/mcp/tools/name-search.mdx
@@ -13,7 +13,7 @@ Search items by their name or title: document name, email subject, chat title, c
| --- | --- | --- | --- |
| `name` | string | Yes | The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token matching instead of prefix. |
| `matchType` | `"partial"` \| `"exact"` | No | How search tools match query terms. Restricted to partial/exact — the backend also supports regexp and an internal query mode, but those are not offered to the model. |
-| `entityTypes` | (`"documents"` \| `"chats"` \| `"emails"` \| `"channels"` \| `"projects"` \| `"call_records"` \| `"calendar_events"`)[] | No | Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']. |
+| `entityTypes` | (`"agent_sessions"` \| `"documents"` \| `"chats"` \| `"emails"` \| `"channels"` \| `"projects"` \| `"call_records"` \| `"calendar_events"`)[] | No | Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']. |
| `inbox` | string | No | Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results. |
| `tags` | TagFilter[] | No | Restrict results to items carrying the given tags — any of them by default, every one of them with tagsMatch="all". Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects, call records, calendar events) can match, so channels are dropped while a tag filter is active. |
| `tagsMatch` | `"any"` \| `"all"` | No | How multiple tag filters combine when filtering items. |
diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsx
index 42fb982b99..994494936d 100644
--- a/apps/web/src/features/block-agent/component/Block.tsx
+++ b/apps/web/src/features/block-agent/component/Block.tsx
@@ -8,8 +8,10 @@ import { LoadErrorPanel } from '@core/component/EntityLoadGate';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { LinkedConversationDrawer } from '@core/linked-conversation';
import { nativeNetworkStatus } from '@core/mobile/native-network-status';
-import { Show, useContext } from 'solid-js';
-
+import { createMethodRegistration } from '@core/orchestrator';
+import { blockHandleSignal } from '@core/signal/load';
+import { useSearchParams } from '@solidjs/router';
+import { createSignal, Show, useContext } from 'solid-js';
import {
AgentSessionProvider,
useAgentSession,
@@ -19,12 +21,23 @@ import {
sessionOriginThread,
} from '../context/origin-thread';
import { forgetPendingSession } from '../context/pending-session';
+import { parseAgentMessageTarget } from '../core/search-location';
import { AgentComposer } from './AgentComposer';
import { AgentSplitHeader } from './AgentSplitHeader';
import { AgentSidePanelSections } from './sidepanel/AgentSidePanelSections';
import { Transcript } from './Transcript';
function AgentBlockContent() {
+ const [params] = useSearchParams();
+ const [searchTarget, setSearchTarget] = createSignal(
+ parseAgentMessageTarget(params)
+ );
+ createMethodRegistration(blockHandleSignal.get, {
+ goToLocationFromParams: (params: Record<string, unknown>) => {
+ const target = parseAgentMessageTarget(params);
+ if (target) setSearchTarget(target);
+ },
+ });
const { session, metadata, loadFailed, loadRetryable, pending, retryLoad } =
useAgentSession();
const canAutofocusSplitContent = useCanAutofocusSplitContent();
@@ -63,7 +76,7 @@ function AgentBlockContent() {
title={metadata()?.title ?? undefined}
/>
<div class="size-full min-w-0 flex flex-col">
- <Transcript />
+ <Transcript searchTarget={searchTarget()} />
{/* Full-frame mobile: composer + queue float in the bottom
accessory region above the dock; desktop stays inline. */}
<FloatRegionOrInline region="accessory">
@@ -72,7 +85,11 @@ function AgentBlockContent() {
<div class="flex w-full justify-center shrink-0 px-4 pb-4.5 pointer-events-auto touch:px-(--mobile-chrome-gutter) touch:pb-0">
<div class="macro-message-width mx-auto">
<AgentComposer
- autofocus={canAutofocusSplitContent && !navigatedFromJK()}
+ autofocus={
+ canAutofocusSplitContent &&
+ !navigatedFromJK() &&
+ !searchTarget()
+ }
/>
</div>
</div>
diff --git a/apps/web/src/features/block-agent/component/Transcript.test.tsx b/apps/web/src/features/block-agent/component/Transcript.test.tsx
index 9337d6dad1..0cd5e1a72d 100644
--- a/apps/web/src/features/block-agent/component/Transcript.test.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.test.tsx
@@ -3,9 +3,11 @@ import { cleanup, render } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentMessageTarget } from '../core/search-location';
import { Transcript } from './Transcript';
const session = vi.hoisted(() => ({
+ sessionId: () => 'session',
messages: () => [] as FoldedMessage[],
quoteSelection: vi.fn(),
touch: false,
@@ -174,6 +176,88 @@ function mount(initial: FoldedMessage[]) {
}
describe('Transcript with the shared TanStack ThreadList', () => {
+ it('positions a cold-link target after the initial latest layout commits', async () => {
+ session.messages = () =>
+ Array.from({ length: 80 }, (_, turn) => message(turn));
+ const view = render(() => (
+ <Transcript searchTarget={{ messageTurn: 0, author: 'agent' }} />
+ ));
+ await settle();
+ await settle();
+ const scroller = view.container.querySelector<HTMLElement>(
+ '[data-channel-scroll]'
+ )!;
+ expect(scroller.scrollTop).toBe(0);
+ expect(
+ view.container.querySelector(
+ '[data-search-target="true"] [data-message="0:agent"]'
+ )
+ ).not.toBeNull();
+ });
+
+ it('waits for history then targets the folded author/turn, and allows repeat navigation', async () => {
+ const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
+ const [target, setTarget] = createSignal<AgentMessageTarget>({
+ messageTurn: 0,
+ author: 'user',
+ });
+ session.messages = messages;
+ const view = render(() => <Transcript searchTarget={target()} />);
+ await settle();
+ setMessages([
+ {
+ ...message(0),
+ author: { kind: 'user', userId: 'owner' },
+ } as FoldedMessage,
+ ...Array.from({ length: 80 }, (_, turn) => message(turn)),
+ ]);
+ await settle();
+ await settle();
+ const highlighted = () =>
+ view.container.querySelector('[data-search-target="true"]');
+ expect(
+ highlighted()?.querySelector('[data-message="0:user"]')
+ ).not.toBeNull();
+ setTarget({ messageTurn: 30, author: 'agent' });
+ await settle();
+ expect(
+ highlighted()?.querySelector('[data-message="30:agent"]')
+ ).not.toBeNull();
+ const scroller = view.container.querySelector<HTMLElement>(
+ '[data-channel-scroll]'
+ )!;
+ scroller.dispatchEvent(
+ new WheelEvent('wheel', { deltaY: 100, bubbles: true })
+ );
+ scroller.scrollTo({ top: 0 });
+ await settle();
+ expect(highlighted()).toBeNull();
+ setTarget({ messageTurn: 30, author: 'agent' });
+ await settle();
+ expect(
+ highlighted()?.querySelector('[data-message="30:agent"]')
+ ).not.toBeNull();
+ const offset = scroller.scrollTop;
+ setMessages((previous) => [...previous, message(80)]);
+ await settle();
+ expect(scroller.scrollTop).toBe(offset);
+ });
+
+ it('leaves latest navigation intact when a search target is absent from the log', async () => {
+ session.messages = () =>
+ Array.from({ length: 80 }, (_, turn) => message(turn));
+ const view = render(() => (
+ <Transcript searchTarget={{ messageTurn: 100, author: 'agent' }} />
+ ));
+ // ThreadList gives an unresolved initial element 1.5s before falling back.
+ await new Promise((resolve) => setTimeout(resolve, 1600));
+ expect(
+ view.container.querySelector('[data-search-target="true"]')
+ ).toBeNull();
+ expect(
+ view.container.querySelector('[data-message="79:agent"]')
+ ).not.toBeNull();
+ });
it('reveals the overlay on downward thumb drag and refreshes the unpinned thumb range', async () => {
const view = mount(Array.from({ length: 50 }, (_, i) => message(i)));
await settle();
diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsx
index ef3c55e577..7acf6c6a87 100644
--- a/apps/web/src/features/block-agent/component/Transcript.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.tsx
@@ -8,17 +8,28 @@ import {
import { FloatRegions } from '@components/app/mobile/float-regions/float-region-state';
import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { createMemo, createSignal, Show } from 'solid-js';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ Show,
+} from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
+import type { AgentMessageTarget } from '../core/search-location';
import { Message } from './AgentMessage';
import { ReplyToSelection } from './ReplyToSelection';
-export function Transcript() {
- const { messages, quoteSelection } = useAgentSession();
+export function Transcript(props: { searchTarget?: AgentMessageTarget }) {
+ const { messages, quoteSelection, sessionId } = useAgentSession();
+ const initialTarget = props.searchTarget;
+ const initialSessionId = sessionId();
const splitPanel = useSplitPanel();
const [transcriptEl, setTranscriptEl] = createSignal<HTMLDivElement>();
const [scrollState, setScrollState] = createSignal<ThreadListScrollState>();
- let navigation: ThreadListNavigation | undefined;
+ const [navigation, setNavigation] = createSignal<ThreadListNavigation>();
+ const [highlightedId, setHighlightedId] = createSignal<string>();
// Object identity and array positions can change as the live fold reconciles.
const messageById = createMemo(
@@ -31,6 +42,37 @@ export function Transcript() {
)
);
const keys = createMemo(() => [...messageById().keys()]);
+ let positionedTarget: AgentMessageTarget | undefined;
+ // Navigation is an external effect. Wait for both log hydration and the
+ // virtual list's layout; subsequent live folds must not repeat the jump.
+ createEffect(
+ on(
+ [() => props.searchTarget, messageById, navigation, scrollState],
+ ([target, byId, handle, state]) => {
+ if (
+ !target ||
+ target === positionedTarget ||
+ !handle ||
+ !state?.didInitialScroll
+ )
+ return;
+ const entry = [...byId].find(
+ ([, message]) =>
+ message.turn === target.messageTurn &&
+ message.author.kind === target.author
+ );
+ if (!entry) return;
+ // The ready notification can run within initial layout, before its
+ // scroll-to-latest finishes. Navigate after that layout has committed.
+ const frame = requestAnimationFrame(() => {
+ if (!handle.scrollToMessage(entry[0])) return;
+ positionedTarget = target;
+ setHighlightedId(entry[0]);
+ });
+ onCleanup(() => cancelAnimationFrame(frame));
+ }
+ )
+ );
// Insets belong in virtual measurements, not CSS padding outside the sizer.
// ThreadList preserves the end pin across keyboard/viewport and inset resizes.
const insets = () =>
@@ -45,12 +87,21 @@ export function Transcript() {
<div class="relative flex-1 min-h-0" ref={setTranscriptEl}>
<ThreadList
keys={keys}
- initialPosition={{ type: 'latest' }}
+ initialPosition={
+ initialTarget && initialSessionId
+ ? {
+ type: 'element',
+ id: `${initialSessionId}:${initialTarget.messageTurn}:${initialTarget.author}`,
+ }
+ : { type: 'latest' }
+ }
insets={insets()}
+ targetId={highlightedId()}
+ onUserNavigation={() => setHighlightedId(undefined)}
onReady={(handle) => {
- navigation = handle;
+ setNavigation(handle);
return () => {
- navigation = undefined;
+ setNavigation(undefined);
};
}}
onScroll={(state) => setScrollState(state)}
@@ -58,7 +109,11 @@ export function Transcript() {
{({ id }) => (
<Show when={messageById().get(id)}>
{(message) => (
- <div class="macro-message-width mx-auto px-4 pb-4 min-w-0">
+ <div
+ class="macro-message-width mx-auto px-4 pb-4 min-w-0 rounded-lg"
+ classList={{ 'bg-accent/10': highlightedId() === id }}
+ data-search-target={highlightedId() === id ? 'true' : undefined}
+ >
<Message message={message()} />
</div>
)}
@@ -67,7 +122,10 @@ export function Transcript() {
</ThreadList>
<ScrollToBottomOverlay
scrollState={scrollState}
- onScrollToBottom={() => navigation?.scrollToLatest()}
+ onScrollToBottom={() => {
+ setHighlightedId(undefined);
+ navigation()?.scrollToLatest();
+ }}
class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
/>
<ReplyToSelection container={transcriptEl()} onReply={quoteSelection} />
diff --git a/apps/web/src/features/block-agent/core/search-location.test.ts b/apps/web/src/features/block-agent/core/search-location.test.ts
new file mode 100644
index 0000000000..4ef242259e
--- /dev/null
+++ b/apps/web/src/features/block-agent/core/search-location.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+import { agentMessageParams, parseAgentMessageTarget } from './search-location';
+
+describe('agent search locations', () => {
+ it.each(['user', 'agent'] as const)(
+ 'round trips turn zero for %s',
+ (author) => {
+ const target = { messageTurn: 0, author };
+ expect(parseAgentMessageTarget(agentMessageParams(target))).toEqual(
+ target
+ );
+ }
+ );
+ it.each([
+ undefined,
+ '',
+ '-1',
+ '1.5',
+ 'Infinity',
+ '1e2',
+ '9007199254740992',
+ ['0'],
+ ])('ignores invalid turns: %s', (turn) => {
+ expect(
+ parseAgentMessageTarget({
+ agent_message_turn: turn,
+ agent_message_author: 'agent',
+ })
+ ).toBeUndefined();
+ });
+ it.each([undefined, 'assistant', ['agent']])(
+ 'ignores invalid authors: %s',
+ (author) => {
+ expect(
+ parseAgentMessageTarget({
+ agent_message_turn: '0',
+ agent_message_author: author,
+ })
+ ).toBeUndefined();
+ }
+ );
+});
diff --git a/apps/web/src/features/block-agent/core/search-location.ts b/apps/web/src/features/block-agent/core/search-location.ts
new file mode 100644
index 0000000000..603f38196d
--- /dev/null
+++ b/apps/web/src/features/block-agent/core/search-location.ts
@@ -0,0 +1,30 @@
+export type AgentMessageTarget = {
+ messageTurn: number;
+ author: 'user' | 'agent';
+};
+
+export const AGENT_SEARCH_PARAMS = {
+ messageTurn: 'agent_message_turn',
+ author: 'agent_message_author',
+} as const;
+
+export function agentMessageParams(
+ target: AgentMessageTarget
+): Record<string, string> {
+ return {
+ [AGENT_SEARCH_PARAMS.messageTurn]: String(target.messageTurn),
+ [AGENT_SEARCH_PARAMS.author]: target.author,
+ };
+}
+
+export function parseAgentMessageTarget(
+ params: Record<string, unknown>
+): AgentMessageTarget | undefined {
+ const turn = params[AGENT_SEARCH_PARAMS.messageTurn];
+ const author = params[AGENT_SEARCH_PARAMS.author];
+ if (typeof turn !== 'string' || !/^\d+$/.test(turn)) return;
+ const messageTurn = Number(turn);
+ if (!Number.isSafeInteger(messageTurn)) return;
+ if (author !== 'user' && author !== 'agent') return;
+ return { messageTurn, author };
+}
diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsx
index f186acbd41..1500db1f28 100644
--- a/apps/web/src/features/entity/composed/ListEntity.tsx
+++ b/apps/web/src/features/entity/composed/ListEntity.tsx
@@ -289,7 +289,7 @@ export function ListEntity(props: ListEntityProps) {
<Entity.Search.ContentHits
entity={props.entity}
onClick={props.onContentHitClick}
- visibleCount={0}
+ visibleCount={props.entity.type === 'agent_session' ? 1 : 0}
/>
</div>
</div>
diff --git a/apps/web/src/features/entity/extractors-search/search-content-hit-row.tsx b/apps/web/src/features/entity/extractors-search/search-content-hit-row.tsx
index 68f288dd64..dc4f7f57a4 100644
--- a/apps/web/src/features/entity/extractors-search/search-content-hit-row.tsx
+++ b/apps/web/src/features/entity/extractors-search/search-content-hit-row.tsx
@@ -49,7 +49,7 @@ export function SearchContentHitRow(props: SearchContentHitRowProps) {
</span>
</div>
</Show>
- <Show when={props.hit.type === 'pdf'}>
+ <Show when={props.hit.type === 'pdf' || props.hit.type === 'agent'}>
<SearchLoc hit={props.hit} />
</Show>
<SearchContent hit={props.hit} />
diff --git a/apps/web/src/features/entity/extractors-search/search-location.tsx b/apps/web/src/features/entity/extractors-search/search-location.tsx
index 6fe7733ab2..acda76e566 100644
--- a/apps/web/src/features/entity/extractors-search/search-location.tsx
+++ b/apps/web/src/features/entity/extractors-search/search-location.tsx
@@ -12,6 +12,11 @@ interface SearchLocationProps {
function getLocationDescription(hit: ContentHitData): string | undefined {
return match(hit)
.with({ type: 'pdf' }, (h) => `Page ${h.location.searchPage}`)
+ .with(
+ { type: 'agent' },
+ (h) =>
+ `${h.location.author === 'user' ? 'User' : 'Agent'} · Turn ${h.location.messageTurn + 1}`
+ )
.otherwise(() => undefined);
}
diff --git a/apps/web/src/features/entity/types/search.ts b/apps/web/src/features/entity/types/search.ts
index a45f887511..924f976e36 100644
--- a/apps/web/src/features/entity/types/search.ts
+++ b/apps/web/src/features/entity/types/search.ts
@@ -33,12 +33,25 @@ type CallRecordSegmentHighlightLocation = {
};
export type SearchLocation =
+ | AgentMessageHighlightLocation
| MarkdownHighlightLocation
| PdfHighlightLocation
| ChannelMessageHighlightLocation
| EmailMessageHighlightLocation
| CallRecordSegmentHighlightLocation;
+type AgentMessageHighlightLocation = {
+ type: 'agent';
+ messageTurn: number;
+ author: 'user' | 'agent';
+};
+
+type AgentContentHitData = {
+ type: 'agent';
+ content: string;
+ location: AgentMessageHighlightLocation;
+};
+
export type ChannelContentHitData = {
type: 'channel';
id: string;
@@ -91,6 +104,7 @@ export type DocumentContentHitData =
| GenericContentHitData;
export type ContentHitData =
+ | AgentContentHitData
| DocumentContentHitData
| ChannelContentHitData
| EmailContentHitData
diff --git a/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.test.ts b/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.test.ts
new file mode 100644
index 0000000000..9e9780fb05
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { agentSessionSearchFilters } from './agent-session-search-filters';
+
+const nil = '00000000-0000-0000-0000-000000000000';
+describe('agent session search scope', () => {
+ it('includes sessions in All and Agents and preserves owner narrowing', () => {
+ expect(agentSessionSearchFilters({}).include).toBe(true);
+ expect(
+ agentSessionSearchFilters({ chatOwnerId: ['owner'] }).owners
+ ).toEqual(['owner']);
+ });
+ it.each([
+ { chatId: [nil] },
+ { chatId: ['legacy-id'] },
+ { chatProjectId: ['project'] },
+ ])(
+ 'excludes sessions from other entity and legacy-only scopes: %j',
+ (include) => {
+ expect(agentSessionSearchFilters(include).ids).toEqual([nil]);
+ }
+ );
+});
diff --git a/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.ts b/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.ts
new file mode 100644
index 0000000000..1012c4b9ef
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/agent-session-search-filters.ts
@@ -0,0 +1,19 @@
+import type { AgentSessionFilters } from '@service-search/generated/models';
+import { NIL_UUID } from '../filters/filter-store';
+import type { FieldFilters } from '../filters/filter-store/types';
+
+/** The Agents facet includes both conversation systems, with distinct IDs.
+ * NIL-filled chat IDs exclude the facet; explicit legacy IDs and project
+ * membership must not accidentally admit unrelated ACP sessions either. */
+export function agentSessionSearchFilters(
+ include: Pick<FieldFilters, 'chatId' | 'chatOwnerId' | 'chatProjectId'>
+): AgentSessionFilters {
+ return {
+ include: !include.chatId?.length && !include.chatProjectId?.length,
+ ids:
+ include.chatId?.length || include.chatProjectId?.length
+ ? [NIL_UUID]
+ : undefined,
+ owners: include.chatOwnerId,
+ };
+}
diff --git a/apps/web/src/features/next-soup/soup-view/create-search-state.ts b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
index e341879a3b..920e27f8c9 100644
--- a/apps/web/src/features/next-soup/soup-view/create-search-state.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
@@ -18,6 +18,7 @@ import type {
UnifiedSearchRequest,
} from '@service-search/generated/models';
import { type Accessor, createMemo, type Setter } from 'solid-js';
+import { agentSessionSearchFilters } from './agent-session-search-filters';
// Map the tasks-view property filters (status/priority/assignee/custom) into the
// search request shape, mirroring the soup path so search and soup agree. Values
@@ -47,6 +48,7 @@ function includePropertiesToFilters(
function filterDataToQueryFilters(data: QueryState): EntityFilters {
const filters: EntityFilters = {};
const { include } = data;
+ filters.agent_session_filters = agentSessionSearchFilters(include);
// Calendar events are searchable by title, so they are scoped like every
// other entity type: a view that names ids gets them, one that names none
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 986bd557c6..b918438181 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -119,6 +119,73 @@ afterEach(() => {
vi.clearAllMocks();
});
+describe('agent session search navigation', () => {
+ const entity = {
+ type: 'agent_session' as const,
+ id: 'session',
+ name: 'Investigation',
+ ownerId: 'owner',
+ botId: 'bot',
+ status: 'event',
+ search: {
+ nameHighlight: null,
+ senderHighlightTerms: null,
+ source: 'service' as const,
+ contentHitData: [
+ {
+ type: 'agent' as const,
+ content: 'match',
+ location: {
+ type: 'agent' as const,
+ messageTurn: 0,
+ author: 'user' as const,
+ },
+ },
+ ],
+ },
+ };
+ it('uses the first folded hit for row clicks, but not title-only hits', () => {
+ expect(getRowClickFallbackLocation(entity)).toEqual({
+ type: 'agent',
+ messageTurn: 0,
+ author: 'user',
+ });
+ const titleOnly = {
+ ...entity,
+ search: { ...entity.search, contentHitData: null },
+ };
+ expect(getRowClickFallbackLocation(titleOnly)).toBeUndefined();
+ });
+ it('opens the agent block with durable params and retargets it on each snippet click', async () => {
+ const openWithSplit = vi.fn();
+ const goToLocationFromParams = vi.fn();
+ const getBlockHandle = vi.fn(async () => ({ goToLocationFromParams }));
+ setGlobalSplitManager({
+ activeSplit: () => undefined,
+ getOrchestrator: () => ({ getBlockHandle }),
+ getSplitByContent: vi.fn(),
+ openWithSplit,
+ } as unknown as SplitManager);
+ await openEntityInSplitFromUnifiedList(entity, {});
+ expect(openWithSplit).toHaveBeenCalledWith(
+ {
+ type: 'agent',
+ id: 'session',
+ params: { agent_message_turn: '0', agent_message_author: 'user' },
+ },
+ expect.any(Object)
+ );
+ await openEntityInSplitFromUnifiedList(entity, {
+ location: { type: 'agent', messageTurn: 4, author: 'agent' },
+ });
+ expect(getBlockHandle).toHaveBeenCalledWith('session');
+ expect(goToLocationFromParams).toHaveBeenLastCalledWith({
+ agent_message_turn: '4',
+ agent_message_author: 'agent',
+ });
+ });
+});
+
const sendNotification = (id: string, messageId: string): UnifiedNotification =>
({
id,
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index c35d460bed..35883fc10d 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -223,6 +223,7 @@ export const openEntityInNewTab = ({
entity: EntityData;
location?: SearchLocation;
}) => {
+ location ??= getRowClickFallbackLocation(entity);
// A reminder opens its own editor — a `reminder-view` component split with a
// URL of its own — the same as the split paths, even a standalone one that
// references nothing.
@@ -263,6 +264,13 @@ export const openEntityInNewTab = ({
}
} else if (location) {
switch (location.type) {
+ case 'agent':
+ for (const [key, value] of Object.entries(
+ agentMessageParams(location)
+ )) {
+ entityUrl.searchParams.set(key, value);
+ }
+ break;
case 'channel':
if (location.messageId) {
entityUrl.searchParams.set(
@@ -560,9 +568,11 @@ export async function navigateCalendarEntityToTarget(
export const getRowClickFallbackLocation = (
entity: EntityData
): SearchLocation | undefined =>
- isHitSnippetEntity(entity) && !isEmailEntity(entity)
- ? getSnippetHit(entity)?.location
- : undefined;
+ entity.type === 'agent_session' && isSearchEntity(entity)
+ ? entity.search.contentHitData?.[0]?.location
+ : isHitSnippetEntity(entity) && !isEmailEntity(entity)
+ ? getSnippetHit(entity)?.location
+ : undefined;
/**
* Opens an entity in a split, handling navigation to specific locations within the entity.
@@ -698,7 +708,9 @@ export const openEntityInSplitFromUnifiedList = async (
}
let params: Record<string, string> | undefined;
- if (entity.type === 'channel' && location?.type === 'channel') {
+ if (entity.type === 'agent_session' && location?.type === 'agent') {
+ params = agentMessageParams(location);
+ } else if (entity.type === 'channel' && location?.type === 'channel') {
params = getChannelParams(location.messageId, location.threadId);
} else if (channelMessageTarget) {
params = getChannelParams(
@@ -946,6 +958,10 @@ async function navigateToLocation(
if (!blockHandle) return;
switch (location.type) {
+ case 'agent': {
+ await blockHandle.goToLocationFromParams(agentMessageParams(location));
+ break;
+ }
case 'channel': {
// NOTE: this is handled by the channel block params but this can be used to re-flash an open channel
await blockHandle.goToLocationFromParams(
@@ -1588,3 +1604,5 @@ export async function executeMarkEntitiesUndone(args: {
),
]);
}
+
+import { agentMessageParams } from '@app/features/block-agent/core/search-location';
diff --git a/apps/web/src/lib/core/constant/allBlocks.ts b/apps/web/src/lib/core/constant/allBlocks.ts
index ebc95b79f9..480dda2342 100644
--- a/apps/web/src/lib/core/constant/allBlocks.ts
+++ b/apps/web/src/lib/core/constant/allBlocks.ts
@@ -237,7 +237,13 @@ export function blockNameToDefaultFile(block?: BlockName | string | null) {
}
export type ItemLike = {
- type: ItemType | 'call' | 'crm_company' | 'reminder' | 'calendar_event';
+ type:
+ | ItemType
+ | 'agent'
+ | 'call'
+ | 'crm_company'
+ | 'reminder'
+ | 'calendar_event';
fileType?: BasicDocumentFileType;
subType?: SubType | BasicDocumentSubTypeProperty;
name?: string;
diff --git a/apps/web/src/lib/queries/soup/agent-session-search.test.ts b/apps/web/src/lib/queries/soup/agent-session-search.test.ts
new file mode 100644
index 0000000000..adca86b3a8
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/agent-session-search.test.ts
@@ -0,0 +1,76 @@
+import type { AgentSessionSearchResponseItem } from '@service-search/generated/models';
+import { describe, expect, it } from 'vitest';
+import { mapAgentSessionSearchResult } from './agent-session-search';
+
+const session: AgentSessionSearchResponseItem = {
+ id: 'session',
+ name: 'Investigation',
+ owner_id: 'owner',
+ bot_id: 'bot',
+ created_at: '2026-09-11T12:00:00Z',
+ updated_at: '2026-09-11T13:00:00Z',
+ agent_session_search_results: [],
+};
+
+describe('agent session search projection', () => {
+ it('keeps agent identity separate from legacy chats and supports name-only matches', () => {
+ const result = mapAgentSessionSearchResult({
+ ...session,
+ agent_session_search_results: [
+ {
+ goto: null,
+ score: null,
+ highlight: { name: '<macro_em>Investigation</macro_em>' },
+ },
+ ],
+ });
+ expect(result).toMatchObject({
+ type: 'agent_session',
+ id: 'session',
+ botId: 'bot',
+ ownerId: 'owner',
+ });
+ expect(result.search.nameHighlight).toBe(
+ '<macro_em>Investigation</macro_em>'
+ );
+ expect(result.search.contentHitData).toBeNull();
+ });
+
+ it('preserves each folded message target including turn zero and both authors', () => {
+ const result = mapAgentSessionSearchResult({
+ ...session,
+ agent_session_search_results: [
+ {
+ goto: { message_turn: 0, author: 'user' },
+ score: 2,
+ highlight: {
+ content: [
+ 'Find <macro_em>quokka</macro_em>',
+ 'Another <macro_em>quokka</macro_em>',
+ ],
+ },
+ },
+ {
+ goto: { message_turn: 0, author: 'agent' },
+ score: 1,
+ highlight: { content: ['Found <macro_em>quokka</macro_em>'] },
+ },
+ {
+ goto: { message_turn: 7, author: 'agent' },
+ score: null,
+ highlight: { content: ['Later <macro_em>quokka</macro_em>'] },
+ },
+ ],
+ });
+ expect(result.search.contentHitData?.map((hit) => hit.location)).toEqual([
+ { type: 'agent', messageTurn: 0, author: 'user' },
+ { type: 'agent', messageTurn: 0, author: 'user' },
+ { type: 'agent', messageTurn: 0, author: 'agent' },
+ { type: 'agent', messageTurn: 7, author: 'agent' },
+ ]);
+ expect(result.search.contentHitData?.[0].content).toBe(
+ 'Find <macro_em>quokka</macro_em>'
+ );
+ expect(result.search.source).toBe('service');
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/agent-session-search.ts b/apps/web/src/lib/queries/soup/agent-session-search.ts
new file mode 100644
index 0000000000..5bf046d0f1
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/agent-session-search.ts
@@ -0,0 +1,45 @@
+import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
+import type { AgentSessionEntity } from '@entity/types/entity';
+import type { WithSearch } from '@entity/types/search';
+import type { AgentSessionSearchResponseItem } from '@service-search/generated/models';
+
+/** Search is a projection of the server-folded transcript, not raw ACP logs. */
+export function mapAgentSessionSearchResult(
+ result: AgentSessionSearchResponseItem
+): WithSearch<AgentSessionEntity> {
+ const matches = result.agent_session_search_results;
+ const nameHighlight = matches.find((hit) => hit.highlight.name)?.highlight
+ .name;
+ const contentHitData = matches.flatMap((hit) => {
+ const target = hit.goto;
+ if (!target) return [];
+ return (hit.highlight.content ?? []).map((content) => ({
+ type: 'agent' as const,
+ content: mergeAdjacentMacroEmTags(content),
+ location: {
+ type: 'agent' as const,
+ messageTurn: target.message_turn,
+ author: target.author,
+ },
+ }));
+ });
+ return {
+ type: 'agent_session',
+ id: result.id,
+ name: result.name,
+ ownerId: result.owner_id,
+ botId: result.bot_id,
+ // Search only returns sessions that were materialized from a folded event.
+ status: 'event',
+ createdAt: result.created_at,
+ updatedAt: result.updated_at,
+ search: {
+ nameHighlight: nameHighlight
+ ? mergeAdjacentMacroEmTags(nameHighlight)
+ : null,
+ contentHitData: contentHitData.length ? contentHitData : null,
+ senderHighlightTerms: null,
+ source: 'service',
+ },
+ };
+}
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index d29bc04275..01bbc61ab9 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -449,6 +449,29 @@ describe('removeSoupEntitiesFromDoneFilteredQueries', () => {
});
describe('removeSearchEntities', () => {
+ it('handles agent-session results without treating them as legacy chats', () => {
+ const session = {
+ type: 'agentSession',
+ id: 'session-1',
+ name: 'Search verification',
+ owner_id: 'macro|[email protected]',
+ bot_id: 'bot-1',
+ created_at: '2026-09-11T00:00:00Z',
+ updated_at: '2026-09-11T00:00:00Z',
+ agent_session_search_results: [],
+ } satisfies UnifiedSearchResponseItem;
+ seedSearchQuery(
+ mockSearchCache([[session, mockSearchResult('chat', 'chat-1')]])
+ );
+
+ const tx = removeSearchEntities(new Set(['session-1']));
+ expect(getSearchQuery()!.pages[0].results).toEqual([
+ mockSearchResult('chat', 'chat-1'),
+ ]);
+ tx.rollback();
+ expect(getSearchQuery()!.pages[0].results[0]).toEqual(session);
+ });
+
it('filters matching IDs from search results', () => {
seedSearchQuery(
mockSearchCache([
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index e44624ed21..fa39654e0d 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -1012,6 +1012,7 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {
.with({ type: 'call' }, (r) => r.call_id)
.with({ type: 'company' }, (r) => r.id)
.with({ type: 'calendarEvent' }, (r) => r.id)
+ .with({ type: 'agentSession' }, (r) => r.id)
.exhaustive();
}
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 14301e4094..9a39407bce 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -55,6 +55,7 @@ import { formatDocumentName } from '@service-storage/util/filename';
import type { UseQueryResult } from '@tanstack/solid-query';
import { differenceInMilliseconds } from 'date-fns';
import { match, P } from 'ts-pattern';
+import { mapAgentSessionSearchResult } from './agent-session-search';
type InnerSearchResult =
| DocumentSearchResult
@@ -315,6 +316,8 @@ export const useSearchResponseItemMapper = () => {
searchQuery: string
): (WithSearch<EntityData> | undefined)[] => {
switch (result.type) {
+ case 'agentSession':
+ return [mapAgentSessionSearchResult(result)];
case 'company': {
const primaryDomain = result.domains[0]?.domain;
const nameHighlight = result.nameHighlighted
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index c647cce6b1..8e5fa9dfe3 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -174,6 +174,7 @@ export const ContentSearch = z.object({
entityTypes: z
.array(
z.enum([
+ 'agent_sessions',
'documents',
'chats',
'emails',
@@ -792,6 +793,62 @@ export const SearchToolResponse = z.object({
}),
z.object({ type: z.literal('calendarEvent') })
),
+ z.intersection(
+ z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ owner_id: z.string(),
+ bot_id: z.string().uuid(),
+ created_at: z.string().datetime({ offset: true }),
+ updated_at: z.string().datetime({ offset: true }),
+ agent_session_search_results: z.array(
+ z.object({
+ goto: z
+ .union([
+ z.object({
+ message_turn: z.number().int().gte(0),
+ author: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('user'),
+ z.literal('agent'),
+ ];
+ 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',
+ });
+ }
+ }),
+ }),
+ z.null(),
+ ])
+ .optional(),
+ highlight: z.object({
+ name: z.union([z.string(), z.null()]).optional(),
+ content: z.array(z.string()).optional(),
+ user_id: z.union([z.string(), z.null()]).optional(),
+ sender: z.union([z.string(), z.null()]).optional(),
+ recipients: z.array(z.string()).optional(),
+ cc: z.array(z.string()).optional(),
+ bcc: z.array(z.string()).optional(),
+ }),
+ score: z.union([z.number(), z.null()]).optional(),
+ })
+ ),
+ }),
+ z.object({ type: z.literal('agentSession') })
+ ),
];
const errors = schemas.reduce<z.ZodError[]>(
(errors, schema) =>
@@ -2839,6 +2896,7 @@ export const NameSearch = z.object({
entityTypes: z
.array(
z.enum([
+ 'agent_sessions',
'documents',
'chats',
'emails',
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 6f2a5cce3e..60e6a91640 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -68,6 +68,7 @@ export type BotOwnerSummary =
*/
export type SearchMatchType = 'partial' | 'exact';
export type UnifiedSearchIndex =
+ | 'agent_sessions'
| 'documents'
| 'chats'
| 'emails'
@@ -119,6 +120,9 @@ export type TaggedSearchResult1 =
})
| (CalendarEventSearchResponseItemWithMetadata & {
type: 'calendarEvent';
+ })
+ | (AgentSessionSearchResponseItem & {
+ type: 'agentSession';
});
/**
* The document sub type enum represents all values of document sub types.
@@ -169,6 +173,10 @@ export type CalendarEventSearchTime =
endDate: string;
kind: 'allDay';
};
+/**
+ * Side of a folded conversation.
+ */
+export type AgentSessionAuthor = 'user' | 'agent';
/**
* The mutually exclusive time shape supplied to calendar tools.
*/
@@ -1711,6 +1719,63 @@ export interface CalendarEventSearchResult {
*/
score?: number | null;
}
+/**
+ * One accessible agent session, grouped with its matching folded messages.
+ */
+export interface AgentSessionSearchResponseItem {
+ /**
+ * Session ID.
+ */
+ id: string;
+ /**
+ * Current persisted name.
+ */
+ name: string;
+ /**
+ * Session owner.
+ */
+ owner_id: string;
+ /**
+ * Agent persona ID.
+ */
+ bot_id: string;
+ /**
+ * Session creation time.
+ */
+ created_at: string;
+ /**
+ * Current persisted modification time.
+ */
+ updated_at: string;
+ /**
+ * Name and folded-message matches.
+ */
+ agent_session_search_results: AgentSessionSearchResult[];
+}
+/**
+ * A name match or one matching folded message.
+ */
+export interface AgentSessionSearchResult {
+ /**
+ * Absent for a name-only match.
+ */
+ goto?: SearchGotoAgentSession | null;
+ highlight: SearchHighlight;
+ /**
+ * Search score.
+ */
+ score?: number | null;
+}
+/**
+ * Stable navigation target from the fold, independent of raw ACP log IDs.
+ */
+export interface SearchGotoAgentSession {
+ /**
+ * Fold-assigned turn.
+ */
+ message_turn: number;
+ author: AgentSessionAuthor;
+}
/**
* Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
*/
diff --git a/apps/web/src/lib/service-clients/service-search/generated/client.ts b/apps/web/src/lib/service-clients/service-search/generated/client.ts
index 7c6fc2c5bf..0fd2a4bdca 100644
--- a/apps/web/src/lib/service-clients/service-search/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-search/generated/client.ts
@@ -6,7 +6,7 @@
*/
import type {
ErrorResponse,
- SimpleUnifiedSearchBaseResponse,
+ SimpleSearchResponse,
SimpleUnifiedSearchParams,
UnifiedSearchParams,
UnifiedSearchRequest,
@@ -94,7 +94,7 @@ export const unifiedSearch = async (
This is a simple search where we do not group your results by entity id.
*/
export type simpleUnifiedSearchResponse200 = {
- data: SimpleUnifiedSearchBaseResponse;
+ data: SimpleSearchResponse;
status: 200;
};
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionAuthor.ts b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionAuthor.ts
new file mode 100644
index 0000000000..9339989b3c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionAuthor.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Side of a folded conversation.
+ */
+export type AgentSessionAuthor =
+ (typeof AgentSessionAuthor)[keyof typeof AgentSessionAuthor];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionAuthor = {
+ user: 'user',
+ agent: 'agent',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResponseItem.ts b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResponseItem.ts
new file mode 100644
index 0000000000..86f1e38ce6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResponseItem.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionSearchResult } from './agentSessionSearchResult';
+
+/**
+ * One accessible agent session, grouped with its matching folded messages.
+ */
+export interface AgentSessionSearchResponseItem {
+ /** Name and folded-message matches. */
+ agent_session_search_results: AgentSessionSearchResult[];
+ /** Agent persona ID. */
+ bot_id: string;
+ /** Session creation time. */
+ created_at: string;
+ /** Session ID. */
+ id: string;
+ /** Current persisted name. */
+ name: string;
+ /** Session owner. */
+ owner_id: string;
+ /** Current persisted modification time. */
+ updated_at: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResult.ts b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResult.ts
new file mode 100644
index 0000000000..f3caa0b6c2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResult.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionSearchResultGoto } from './agentSessionSearchResultGoto';
+import type { AgentSessionSearchResultScore } from './agentSessionSearchResultScore';
+import type { SearchHighlight } from './searchHighlight';
+
+/**
+ * A name match or one matching folded message.
+ */
+export interface AgentSessionSearchResult {
+ goto?: AgentSessionSearchResultGoto;
+ /** Matched name/content fragments. */
+ highlight: SearchHighlight;
+ /** Search score. */
+ score?: AgentSessionSearchResultScore;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultGoto.ts b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultGoto.ts
new file mode 100644
index 0000000000..caa03bd02b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultGoto.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoAgentSession } from './searchGotoAgentSession';
+
+export type AgentSessionSearchResultGoto = null | SearchGotoAgentSession;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultScore.ts b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultScore.ts
new file mode 100644
index 0000000000..6e8bf3481d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/agentSessionSearchResultScore.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Search score.
+ */
+export type AgentSessionSearchResultScore = number | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/highlight.ts b/apps/web/src/lib/service-clients/service-search/generated/models/highlight.ts
new file mode 100644
index 0000000000..0593545804
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/highlight.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { HighlightName } from './highlightName';
+
+/**
+ * The search service version of a highlight
+ */
+export interface Highlight {
+ /** If the match was on the entity content, this will provide a list of highlights
+for each content match */
+ content?: string[];
+ /** If the match was on the entity name, this will be present with that highlight */
+ name?: HighlightName;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/highlightName.ts b/apps/web/src/lib/service-clients/service-search/generated/models/highlightName.ts
new file mode 100644
index 0000000000..4c34e26057
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/highlightName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * If the match was on the entity name, this will be present with that highlight
+ */
+export type HighlightName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts b/apps/web/src/lib/service-clients/service-search/generated/models/index.ts
index 96763bc8be..d76dd18a42 100644
--- a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/index.ts
@@ -5,7 +5,12 @@
* OpenAPI spec version: 0.1.0
*/
+export * from './agentSessionAuthor';
export * from './agentSessionFilters';
+export * from './agentSessionSearchResponseItem';
+export * from './agentSessionSearchResult';
+export * from './agentSessionSearchResultGoto';
+export * from './agentSessionSearchResultScore';
export * from './calendarEventFilters';
export * from './calendarEventFiltersEndsAfter';
export * from './calendarEventFiltersStartsBefore';
@@ -179,6 +184,8 @@ export * from './entityType';
export * from './errorResponse';
export * from './fileType';
export * from './foreignEntityFilters';
+export * from './highlight';
+export * from './highlightName';
export * from './matchType';
export * from './notificationFilters';
export * from './notificationState';
@@ -231,6 +238,16 @@ export * from './propertyValueOneOfType';
export * from './reminderFilters';
export * from './reminderFiltersCompleted';
export * from './reminderFiltersFired';
+export * from './searchGotoAgentSession';
+export * from './searchGotoCallRecord';
+export * from './searchGotoCallRecordEndedAt';
+export * from './searchGotoChannel';
+export * from './searchGotoChat';
+export * from './searchGotoContent';
+export * from './searchGotoDocument';
+export * from './searchGotoDocumentRawContent';
+export * from './searchGotoEmail';
+export * from './searchGotoEmailSentAt';
export * from './searchHighlight';
export * from './searchHighlightName';
export * from './searchHighlightSender';
@@ -267,6 +284,10 @@ export * from './simpleEmailSearchResponseBaseItemSubject';
export * from './simpleProjectSearchResponse';
export * from './simpleProjectSearchResponseBaseItem';
export * from './simpleProjectSearchResponseBaseItemHumanReadableTimestamp';
+export * from './simpleSearchResponse';
+export * from './simpleSearchResponseItem';
+export * from './simpleSearchResponseItemGoto';
+export * from './simpleSearchResponseItemScore';
export * from './simpleUnifiedSearchBaseResponse';
export * from './simpleUnifiedSearchParams';
export * from './simpleUnifiedSearchResponseBaseItem';
@@ -344,6 +365,9 @@ export * from './unifiedSearchResponseItemOneOfOnezeroAllOfType';
export * from './unifiedSearchResponseItemOneOfSeven';
export * from './unifiedSearchResponseItemOneOfSevenAllOf';
export * from './unifiedSearchResponseItemOneOfSevenAllOfType';
+export * from './unifiedSearchResponseItemOneOfTwoeight';
+export * from './unifiedSearchResponseItemOneOfTwoeightAllOf';
+export * from './unifiedSearchResponseItemOneOfTwoeightAllOfType';
export * from './unifiedSearchResponseItemOneOfTwofive';
export * from './unifiedSearchResponseItemOneOfTwofiveAllOf';
export * from './unifiedSearchResponseItemOneOfTwofiveAllOfType';
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoAgentSession.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoAgentSession.ts
new file mode 100644
index 0000000000..9f80943c10
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoAgentSession.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionAuthor } from './agentSessionAuthor';
+
+/**
+ * Stable navigation target from the fold, independent of raw ACP log IDs.
+ */
+export interface SearchGotoAgentSession {
+ /** Author within the turn. */
+ author: AgentSessionAuthor;
+ /**
+ * Fold-assigned turn.
+ * @minimum 0
+ */
+ message_turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecord.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecord.ts
new file mode 100644
index 0000000000..a8672d55be
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecord.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoCallRecordEndedAt } from './searchGotoCallRecordEndedAt';
+
+export interface SearchGotoCallRecord {
+ channel_id: string;
+ ended_at?: SearchGotoCallRecordEndedAt;
+ participant_ids: string[];
+ sequence_num: number;
+ speaker_id: string;
+ started_at: string;
+ transcript_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecordEndedAt.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecordEndedAt.ts
new file mode 100644
index 0000000000..e582f4ef8f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoCallRecordEndedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SearchGotoCallRecordEndedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChannel.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChannel.ts
new file mode 100644
index 0000000000..36fbb215fa
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChannel.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface SearchGotoChannel {
+ /** The channel message id */
+ channel_message_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChat.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChat.ts
new file mode 100644
index 0000000000..adc034d30e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoChat.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface SearchGotoChat {
+ /** The chat message id */
+ chat_message_id: string;
+ /** The role of the chat message */
+ role: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoContent.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoContent.ts
new file mode 100644
index 0000000000..1a1683d9af
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoContent.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoAgentSession } from './searchGotoAgentSession';
+import type { SearchGotoCallRecord } from './searchGotoCallRecord';
+import type { SearchGotoChannel } from './searchGotoChannel';
+import type { SearchGotoChat } from './searchGotoChat';
+import type { SearchGotoDocument } from './searchGotoDocument';
+import type { SearchGotoEmail } from './searchGotoEmail';
+
+/**
+ * The search service version of a goto
+ */
+export type SearchGotoContent =
+ | SearchGotoAgentSession
+ | SearchGotoDocument
+ | SearchGotoChat
+ | SearchGotoEmail
+ | SearchGotoChannel
+ | SearchGotoCallRecord;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocument.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocument.ts
new file mode 100644
index 0000000000..cca1f8ee2e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocument.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoDocumentRawContent } from './searchGotoDocumentRawContent';
+
+export interface SearchGotoDocument {
+ /** The node id of the document
+This can be a stringified page number 0-indexed for pdf/docx files,
+or it can be a unique id that is used in lexical for markdown files. */
+ node_id: string;
+ /** The raw content of the document */
+ raw_content?: SearchGotoDocumentRawContent;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocumentRawContent.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocumentRawContent.ts
new file mode 100644
index 0000000000..5f3937b9f5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoDocumentRawContent.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The raw content of the document
+ */
+export type SearchGotoDocumentRawContent = string | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmail.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmail.ts
new file mode 100644
index 0000000000..c61bfdddc5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmail.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoEmailSentAt } from './searchGotoEmailSentAt';
+
+export interface SearchGotoEmail {
+ bcc: string[];
+ cc: string[];
+ /** The email message id */
+ email_message_id: string;
+ labels: string[];
+ recipients: string[];
+ sender: string;
+ sent_at?: SearchGotoEmailSentAt;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmailSentAt.ts b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmailSentAt.ts
new file mode 100644
index 0000000000..d828937fb9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/searchGotoEmailSentAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SearchGotoEmailSentAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponse.ts b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponse.ts
new file mode 100644
index 0000000000..65b8cc434d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SimpleSearchResponseItem } from './simpleSearchResponseItem';
+
+/**
+ * The response for simple search
+ */
+export interface SimpleSearchResponse {
+ results: SimpleSearchResponseItem[];
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItem.ts b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItem.ts
new file mode 100644
index 0000000000..b1a6f248d8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItem.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { Highlight } from './highlight';
+import type { SimpleSearchResponseItemGoto } from './simpleSearchResponseItemGoto';
+import type { SimpleSearchResponseItemScore } from './simpleSearchResponseItemScore';
+
+/**
+ * Simple response item to mimic what we get back from opensearch
+ */
+export interface SimpleSearchResponseItem {
+ /** ID of the chat, channel, email, or document */
+ entity_id: string;
+ entity_type: string;
+ goto?: SimpleSearchResponseItemGoto;
+ highlight: Highlight;
+ score?: SimpleSearchResponseItemScore;
+}
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemGoto.ts b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemGoto.ts
new file mode 100644
index 0000000000..319628984c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemGoto.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SearchGotoContent } from './searchGotoContent';
+
+export type SimpleSearchResponseItemGoto = null | SearchGotoContent;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemScore.ts b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemScore.ts
new file mode 100644
index 0000000000..b79ffa913f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/simpleSearchResponseItemScore.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SimpleSearchResponseItemScore = number | null;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts
index 29125d7712..bd4291a370 100644
--- a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItem.ts
@@ -11,6 +11,7 @@ import type { UnifiedSearchResponseItemOneOfOnesix } from './unifiedSearchRespon
import type { UnifiedSearchResponseItemOneOfOnethree } from './unifiedSearchResponseItemOneOfOnethree';
import type { UnifiedSearchResponseItemOneOfOnezero } from './unifiedSearchResponseItemOneOfOnezero';
import type { UnifiedSearchResponseItemOneOfSeven } from './unifiedSearchResponseItemOneOfSeven';
+import type { UnifiedSearchResponseItemOneOfTwoeight } from './unifiedSearchResponseItemOneOfTwoeight';
import type { UnifiedSearchResponseItemOneOfTwofive } from './unifiedSearchResponseItemOneOfTwofive';
import type { UnifiedSearchResponseItemOneOfTwotwo } from './unifiedSearchResponseItemOneOfTwotwo';
@@ -23,4 +24,5 @@ export type UnifiedSearchResponseItem =
| UnifiedSearchResponseItemOneOfOnesix
| UnifiedSearchResponseItemOneOfOnenine
| UnifiedSearchResponseItemOneOfTwotwo
- | UnifiedSearchResponseItemOneOfTwofive;
+ | UnifiedSearchResponseItemOneOfTwofive
+ | UnifiedSearchResponseItemOneOfTwoeight;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeight.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeight.ts
new file mode 100644
index 0000000000..dece7bd84d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeight.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionSearchResponseItem } from './agentSessionSearchResponseItem';
+import type { UnifiedSearchResponseItemOneOfTwoeightAllOf } from './unifiedSearchResponseItemOneOfTwoeightAllOf';
+
+export type UnifiedSearchResponseItemOneOfTwoeight =
+ AgentSessionSearchResponseItem & UnifiedSearchResponseItemOneOfTwoeightAllOf;
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOf.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOf.ts
new file mode 100644
index 0000000000..ba071dc849
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { UnifiedSearchResponseItemOneOfTwoeightAllOfType } from './unifiedSearchResponseItemOneOfTwoeightAllOfType';
+
+export type UnifiedSearchResponseItemOneOfTwoeightAllOf = {
+ type: UnifiedSearchResponseItemOneOfTwoeightAllOfType;
+};
diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOfType.ts b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOfType.ts
new file mode 100644
index 0000000000..0165109b8a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-search/generated/models/unifiedSearchResponseItemOneOfTwoeightAllOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type UnifiedSearchResponseItemOneOfTwoeightAllOfType =
+ (typeof UnifiedSearchResponseItemOneOfTwoeightAllOfType)[keyof typeof UnifiedSearchResponseItemOneOfTwoeightAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const UnifiedSearchResponseItemOneOfTwoeightAllOfType = {
+ agentSession: 'agentSession',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-search/openapi.json b/apps/web/src/lib/service-clients/service-search/openapi.json
index 815a639a14..1545b6a3a4 100644
--- a/apps/web/src/lib/service-clients/service-search/openapi.json
+++ b/apps/web/src/lib/service-clients/service-search/openapi.json
@@ -132,7 +132,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/SimpleUnifiedSearchBaseResponse"
+ "$ref": "#/components/schemas/SimpleSearchResponse"
}
}
}
@@ -173,6 +173,11 @@
},
"components": {
"schemas": {
+ "AgentSessionAuthor": {
+ "type": "string",
+ "description": "Side of a folded conversation.",
+ "enum": ["user", "agent"]
+ },
"AgentSessionFilters": {
"type": "object",
"description": "Filters for agent sessions.",
@@ -197,6 +202,83 @@
}
}
},
+ "AgentSessionSearchResponseItem": {
+ "type": "object",
+ "description": "One accessible agent session, grouped with its matching folded messages.",
+ "required": [
+ "id",
+ "name",
+ "owner_id",
+ "bot_id",
+ "created_at",
+ "updated_at",
+ "agent_session_search_results"
+ ],
+ "properties": {
+ "agent_session_search_results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentSessionSearchResult"
+ },
+ "description": "Name and folded-message matches."
+ },
+ "bot_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Agent persona ID."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Session creation time."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session ID."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current persisted name."
+ },
+ "owner_id": {
+ "type": "string",
+ "description": "Session owner."
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Current persisted modification time."
+ }
+ }
+ },
+ "AgentSessionSearchResult": {
+ "type": "object",
+ "description": "A name match or one matching folded message.",
+ "required": ["highlight"],
+ "properties": {
+ "goto": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoAgentSession",
+ "description": "Absent for a name-only match."
+ }
+ ]
+ },
+ "highlight": {
+ "$ref": "#/components/schemas/SearchHighlight",
+ "description": "Matched name/content fragments."
+ },
+ "score": {
+ "type": ["number", "null"],
+ "format": "double",
+ "description": "Search score."
+ }
+ }
+ },
"CalendarEventFilters": {
"type": "object",
"description": "Filters for canonical calendar-event entities.",
@@ -2622,6 +2704,23 @@
}
}
},
+ "Highlight": {
+ "type": "object",
+ "description": "The search service version of a highlight",
+ "properties": {
+ "content": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "If the match was on the entity content, this will provide a list of highlights\nfor each content match"
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "If the match was on the entity name, this will be present with that highlight"
+ }
+ }
+ },
"MatchType": {
"type": "string",
"enum": ["exact", "partial", "regexp", "query"]
@@ -3149,6 +3248,177 @@
}
}
},
+ "SearchGotoAgentSession": {
+ "type": "object",
+ "description": "Stable navigation target from the fold, independent of raw ACP log IDs.",
+ "required": ["message_turn", "author"],
+ "properties": {
+ "author": {
+ "$ref": "#/components/schemas/AgentSessionAuthor",
+ "description": "Author within the turn."
+ },
+ "message_turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Fold-assigned turn.",
+ "minimum": 0
+ }
+ }
+ },
+ "SearchGotoCallRecord": {
+ "type": "object",
+ "required": [
+ "channel_id",
+ "transcript_id",
+ "speaker_id",
+ "sequence_num",
+ "started_at",
+ "participant_ids"
+ ],
+ "properties": {
+ "channel_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "ended_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "participant_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sequence_num": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "speaker_id": {
+ "type": "string"
+ },
+ "started_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "transcript_id": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ },
+ "SearchGotoChannel": {
+ "type": "object",
+ "required": ["channel_message_id"],
+ "properties": {
+ "channel_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The channel message id"
+ }
+ }
+ },
+ "SearchGotoChat": {
+ "type": "object",
+ "required": ["chat_message_id", "role"],
+ "properties": {
+ "chat_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The chat message id"
+ },
+ "role": {
+ "type": "string",
+ "description": "The role of the chat message"
+ }
+ }
+ },
+ "SearchGotoContent": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SearchGotoAgentSession"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoDocument"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoChat"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoEmail"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoChannel"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoCallRecord"
+ }
+ ],
+ "description": "The search service version of a goto"
+ },
+ "SearchGotoDocument": {
+ "type": "object",
+ "required": ["node_id"],
+ "properties": {
+ "node_id": {
+ "type": "string",
+ "description": "The node id of the document\nThis can be a stringified page number 0-indexed for pdf/docx files,\nor it can be a unique id that is used in lexical for markdown files."
+ },
+ "raw_content": {
+ "type": ["string", "null"],
+ "description": "The raw content of the document"
+ }
+ }
+ },
+ "SearchGotoEmail": {
+ "type": "object",
+ "required": [
+ "email_message_id",
+ "bcc",
+ "cc",
+ "labels",
+ "sender",
+ "recipients"
+ ],
+ "properties": {
+ "bcc": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "cc": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "email_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The email message id"
+ },
+ "labels": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "recipients": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sender": {
+ "type": "string"
+ },
+ "sent_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ }
+ }
+ },
"SearchHighlight": {
"type": "object",
"properties": {
@@ -4023,6 +4293,51 @@
}
}
},
+ "SimpleSearchResponse": {
+ "type": "object",
+ "description": "The response for simple search",
+ "required": ["results"],
+ "properties": {
+ "results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SimpleSearchResponseItem"
+ }
+ }
+ }
+ },
+ "SimpleSearchResponseItem": {
+ "type": "object",
+ "description": "Simple response item to mimic what we get back from opensearch",
+ "required": ["entity_id", "entity_type", "highlight"],
+ "properties": {
+ "entity_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "ID of the chat, channel, email, or document"
+ },
+ "entity_type": {
+ "type": "string"
+ },
+ "goto": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoContent"
+ }
+ ]
+ },
+ "highlight": {
+ "$ref": "#/components/schemas/Highlight"
+ },
+ "score": {
+ "type": ["number", "null"],
+ "format": "double"
+ }
+ }
+ },
"SimpleUnifiedSearchBaseResponse": {
"type": "object",
"required": ["results"],
@@ -4523,6 +4838,23 @@
}
}
]
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentSessionSearchResponseItem"
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["agentSession"]
+ }
+ }
+ }
+ ]
}
]
}
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 7dd702d72c..1ab79578a9 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -62,6 +62,7 @@ macro_authorization = { path = "../macro_authorization", default-features = fals
macro_user_id = { path = "../macro_user_id" }
utoipa = { workspace = true, optional = true }
rootcause = { workspace = true }
+uuid = { workspace = true }
sqlx = { workspace = true, features = ["json"], optional = true }
chrono = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 9a00c48cd5..3f5186258d 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -5,5 +5,6 @@ pub mod lifecycle;
pub mod model;
pub mod ports;
mod sandbox_size;
+pub mod search;
pub mod service;
pub mod session;
diff --git a/crates/agent_session/src/domain/search.rs b/crates/agent_session/src/domain/search.rs
new file mode 100644
index 0000000000..e7c6ca9a6e
--- /dev/null
+++ b/crates/agent_session/src/domain/search.rs
@@ -0,0 +1,71 @@
+//! Metadata needed to present a searchable session without loading its ACP log.
+
+use std::{future::Future, pin::Pin};
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use crate::domain::error::Result;
+
+/// Current metadata for an agent-session search result.
+#[derive(Debug, Clone)]
+pub struct AgentSessionSearchMetadata {
+ /// Session identity.
+ pub id: Uuid,
+ /// User-facing name.
+ pub name: String,
+ /// Session owner.
+ pub owner_id: MacroUserIdStr<'static>,
+ /// Agent persona identity.
+ pub bot_id: Uuid,
+ /// Creation time.
+ pub created_at: DateTime<Utc>,
+ /// Last metadata update.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// Repository capability for metadata belonging to sessions already authorized
+/// by the caller's owning access boundary.
+pub trait AgentSessionSearchMetadataRepo: Send + Sync + 'static {
+ /// Fetch the current presentation metadata for the supplied session IDs.
+ fn search_metadata(
+ &self,
+ ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<AgentSessionSearchMetadata>>> + Send;
+}
+
+/// Agent-session use case for reading search-result presentation metadata.
+///
+/// Search callers must first resolve authorization. This service deliberately
+/// accepts only that resulting allowlist and never loads ACP logs.
+pub trait AgentSessionSearchMetadataService: Send + Sync + 'static {
+ /// Fetch current metadata for an already-authorized allowlist.
+ fn search_metadata(
+ &self,
+ ids: Vec<Uuid>,
+ ) -> Pin<Box<dyn Future<Output = Result<Vec<AgentSessionSearchMetadata>>> + Send + '_>>;
+}
+
+/// Default implementation of [`AgentSessionSearchMetadataService`].
+#[derive(Clone)]
+pub struct AgentSessionSearchMetadataServiceImpl<R>(pub R);
+
+impl<R> AgentSessionSearchMetadataServiceImpl<R> {
+ /// Create the service from its persistence port.
+ pub fn new(repo: R) -> Self {
+ Self(repo)
+ }
+}
+
+impl<R> AgentSessionSearchMetadataService for AgentSessionSearchMetadataServiceImpl<R>
+where
+ R: AgentSessionSearchMetadataRepo,
+{
+ fn search_metadata(
+ &self,
+ ids: Vec<Uuid>,
+ ) -> Pin<Box<dyn Future<Output = Result<Vec<AgentSessionSearchMetadata>>> + Send + '_>> {
+ Box::pin(async move { self.0.search_metadata(&ids).await })
+ }
+}
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 6bc41f0434..f7e654a890 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -2,6 +2,7 @@
//! repositories, the fold's log source, and the audience a streamed frame is
//! addressed to.
+pub mod search;
#[cfg(test)]
mod test;
diff --git a/crates/agent_session/src/outbound/postgres/search.rs b/crates/agent_session/src/outbound/postgres/search.rs
new file mode 100644
index 0000000000..c614a60694
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/search.rs
@@ -0,0 +1,48 @@
+//! Bounded-to-allowlist metadata lookup for search.
+
+use crate::{
+ domain::{
+ error::Result,
+ search::{AgentSessionSearchMetadata, AgentSessionSearchMetadataRepo},
+ },
+ outbound::postgres::PgAgentSessionRepo,
+};
+
+/// Fetch current metadata for already authorized session IDs.
+#[tracing::instrument(err, skip(pool, ids))]
+async fn search_metadata(
+ pool: &sqlx::PgPool,
+ ids: &[uuid::Uuid],
+) -> Result<Vec<AgentSessionSearchMetadata>, sqlx::Error> {
+ sqlx::query!(
+ r#"
+ SELECT id, name, owner_id, bot_id, created_at, modified_at
+ FROM agent_session
+ WHERE id = ANY($1)
+ "#,
+ ids,
+ )
+ .fetch_all(pool)
+ .await?
+ .into_iter()
+ .map(|row| {
+ Ok(AgentSessionSearchMetadata {
+ id: row.id,
+ name: row.name,
+ owner_id: macro_user_id::user_id::MacroUserIdStr::try_from(row.owner_id)
+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))?,
+ bot_id: row.bot_id,
+ created_at: row.created_at,
+ updated_at: row.modified_at,
+ })
+ })
+ .collect()
+}
+
+impl AgentSessionSearchMetadataRepo for PgAgentSessionRepo {
+ async fn search_metadata(&self, ids: &[uuid::Uuid]) -> Result<Vec<AgentSessionSearchMetadata>> {
+ Ok(search_metadata(&self.pool, ids)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
+}
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 5a265ec7b9..36dec3d097 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -1,4 +1,5 @@
use super::*;
+mod search;
use crate::domain::model::{AgentMcpServer, DEFAULT_AGENT_SESSION_NAME};
use crate::domain::ports::AgentSessionRepo;
use agent_client_protocol::RawJsonRpcMessage;
diff --git a/crates/agent_session/src/outbound/postgres/test/search.rs b/crates/agent_session/src/outbound/postgres/test/search.rs
new file mode 100644
index 0000000000..e7c1901f53
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/test/search.rs
@@ -0,0 +1,38 @@
+use super::*;
+use crate::domain::search::{
+ AgentSessionSearchMetadataService as _, AgentSessionSearchMetadataServiceImpl,
+};
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn search_metadata_is_scoped_current_and_omits_deleted_sessions(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let search_metadata = AgentSessionSearchMetadataServiceImpl::new(repo.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let other = create_session(&repo, new_session(bot, None, None)).await;
+ repo.set_name(session.id, "Updated searchable name")
+ .await
+ .unwrap();
+ let rows = search_metadata
+ .search_metadata(vec![session.id.as_uuid()])
+ .await
+ .unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].id, session.id.as_uuid());
+ assert_eq!(rows[0].name, "Updated searchable name");
+ assert_eq!(rows[0].owner_id.as_ref(), OWNER);
+ assert!(
+ search_metadata
+ .search_metadata(vec![])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ AgentSessionRepo::delete(&repo, session.id).await.unwrap();
+ let rows = search_metadata
+ .search_metadata(vec![session.id.as_uuid(), other.id.as_uuid()])
+ .await
+ .unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].id, other.id.as_uuid());
+}
diff --git a/crates/ai_tools/src/search/search_service/types.rs b/crates/ai_tools/src/search/search_service/types.rs
index ecb68b6c68..8abaaa9a8c 100644
--- a/crates/ai_tools/src/search/search_service/types.rs
+++ b/crates/ai_tools/src/search/search_service/types.rs
@@ -172,6 +172,7 @@ fn item_properties(item: &UnifiedSearchResponseItem) -> Option<&Vec<SoupProperty
UnifiedSearchResponseItem::CalendarEvent(i) => i.properties.as_ref(),
UnifiedSearchResponseItem::Channel(_)
| UnifiedSearchResponseItem::ChannelMessage(_)
+ | UnifiedSearchResponseItem::AgentSession(_)
| UnifiedSearchResponseItem::Company(_) => None,
}
}
@@ -186,6 +187,7 @@ fn item_properties_mut(item: &mut UnifiedSearchResponseItem) -> Option<&mut Vec<
UnifiedSearchResponseItem::CalendarEvent(i) => i.properties.as_mut(),
UnifiedSearchResponseItem::Channel(_)
| UnifiedSearchResponseItem::ChannelMessage(_)
+ | UnifiedSearchResponseItem::AgentSession(_)
| UnifiedSearchResponseItem::Company(_) => None,
}
}
diff --git a/crates/entity_access/src/outbound.rs b/crates/entity_access/src/outbound.rs
index a7f1a31393..f28d6c0f47 100644
--- a/crates/entity_access/src/outbound.rs
+++ b/crates/entity_access/src/outbound.rs
@@ -7,7 +7,8 @@ mod pg_access_repo;
mod pg_explain_access_repo;
pub use pg_access_repo::{
- PgAccessRepository, SourceIds, get_team_scope_source_ids, get_user_source_ids,
+ PgAccessRepository, SourceIds, accessible_session_ids, get_team_scope_source_ids,
+ get_user_source_ids,
};
#[cfg(feature = "explain_binary")]
pub use pg_explain_access_repo::PgExplainAccessRepository;
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index 52564300b2..7b3db41960 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -2,6 +2,7 @@
pub(crate) mod queries;
+pub use queries::agent_session_access::accessible_session_ids;
pub use queries::{SourceIds, get_team_scope_source_ids, get_user_source_ids};
#[cfg(test)]
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
index adae55e8ff..948669e0a1 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
@@ -10,6 +10,32 @@ use model_entity::EntityType;
use sqlx::PgPool;
use std::str::FromStr;
+#[cfg(test)]
+mod test;
+
+/// List agent sessions granted to the caller's current user/channel/team sources.
+/// Optional requested IDs narrow the allowlist before it reaches OpenSearch.
+#[tracing::instrument(err, skip(pool, source_ids, requested_ids))]
+pub async fn accessible_session_ids(
+ pool: &PgPool,
+ source_ids: &SourceIds,
+ requested_ids: &[uuid::Uuid],
+) -> Result<Vec<uuid::Uuid>, sqlx::Error> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT DISTINCT entity_id
+ FROM entity_access
+ WHERE entity_type = 'agent_session'
+ AND source_id = ANY($1)
+ AND (cardinality($2::uuid[]) = 0 OR entity_id = ANY($2))
+ "#,
+ &source_ids.0,
+ requested_ids,
+ )
+ .fetch_all(pool)
+ .await
+}
+
/// Get the highest access level a user has for an agent session.
///
/// A session's grants are written when it is created: the owner with
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs
new file mode 100644
index 0000000000..91ee0365a4
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs
@@ -0,0 +1,71 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn session_allowlist_matches_grants_and_respects_requested_ids(pool: PgPool) {
+ let session = uuid::Uuid::now_v7();
+ let unrelated = uuid::Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'agent_session', 'owner', 'user', 'owner'),
+ ($1, 'agent_session', 'channel', 'channel', 'view'),
+ ($2, 'chat', 'channel', 'channel', 'view')
+ "#,
+ session,
+ unrelated,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ for sources in [
+ vec!["owner".into()],
+ vec!["channel".into()],
+ vec!["owner".into(), "channel".into()],
+ ] {
+ assert_eq!(
+ accessible_session_ids(&pool, &SourceIds(sources), &[])
+ .await
+ .unwrap(),
+ vec![session]
+ );
+ }
+ assert!(
+ accessible_session_ids(&pool, &SourceIds(vec!["outsider".into()]), &[])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ accessible_session_ids(&pool, &SourceIds(vec![]), &[])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ accessible_session_ids(&pool, &SourceIds(vec!["channel".into()]), &[unrelated])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ accessible_session_ids(&pool, &SourceIds(vec!["channel".into()]), &[session])
+ .await
+ .unwrap(),
+ vec![session]
+ );
+ // Revocation must be reflected by the next allowlist query.
+ sqlx::query!(
+ "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = 'channel'",
+ session
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ accessible_session_ids(&pool, &SourceIds(vec!["channel".into()]), &[])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/macro_db_client/src/entity_name.rs b/crates/macro_db_client/src/entity_name.rs
index 45e67f8b6c..963e6724b7 100644
--- a/crates/macro_db_client/src/entity_name.rs
+++ b/crates/macro_db_client/src/entity_name.rs
@@ -79,7 +79,7 @@ pub async fn get_entity_name_and_owner(
.fetch_one(db)
.await?
}
- SearchEntityType::Projects => {
+ SearchEntityType::AgentSessions | SearchEntityType::Projects => {
anyhow::bail!("entity type not supported");
}
SearchEntityType::CallRecords => {
diff --git a/crates/models_opensearch/src/lib.rs b/crates/models_opensearch/src/lib.rs
index 8bd2c522ce..e3df9ed4b8 100644
--- a/crates/models_opensearch/src/lib.rs
+++ b/crates/models_opensearch/src/lib.rs
@@ -11,6 +11,8 @@
#[derive(Debug, Clone, Hash, Eq, PartialEq, strum::Display, strum::EnumString, strum::AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum SearchIndex {
+ /// The folded agent-session alias
+ AgentSessions,
/// The channel alias
Channels,
/// The chat alias
@@ -47,6 +49,8 @@ pub enum SearchIndex {
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum SearchEntityType {
+ /// Folded agent sessions.
+ AgentSessions,
/// The channel entity type (has OpenSearch index)
Channels,
/// The chat entity type (has OpenSearch index)
@@ -83,6 +87,8 @@ pub enum SearchEntityType {
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum OpenSearchEntityType {
+ /// The agent sessions index.
+ AgentSessions,
/// The channel index
Channels,
/// The chat index
@@ -105,6 +111,7 @@ impl OpenSearchEntityType {
/// without requiring a code change here.
pub fn index_name(&self) -> &'static str {
match self {
+ Self::AgentSessions => "agent_sessions",
Self::Channels => "channels",
Self::Chats => "chats",
Self::Documents => "documents",
@@ -148,6 +155,7 @@ impl OpenSearchEntityType {
impl From<OpenSearchEntityType> for SearchEntityType {
fn from(value: OpenSearchEntityType) -> Self {
match value {
+ OpenSearchEntityType::AgentSessions => SearchEntityType::AgentSessions,
OpenSearchEntityType::Channels => SearchEntityType::Channels,
OpenSearchEntityType::Chats => SearchEntityType::Chats,
OpenSearchEntityType::Documents => SearchEntityType::Documents,
@@ -162,6 +170,7 @@ impl From<OpenSearchEntityType> for SearchEntityType {
impl From<OpenSearchEntityType> for SearchIndex {
fn from(value: OpenSearchEntityType) -> Self {
match value {
+ OpenSearchEntityType::AgentSessions => SearchIndex::AgentSessions,
OpenSearchEntityType::Channels => SearchIndex::Channels,
OpenSearchEntityType::Chats => SearchIndex::Chats,
OpenSearchEntityType::Documents => SearchIndex::Documents,
diff --git a/crates/models_search/src/agent_session.rs b/crates/models_search/src/agent_session.rs
new file mode 100644
index 0000000000..3dfdbc15bb
--- /dev/null
+++ b/crates/models_search/src/agent_session.rs
@@ -0,0 +1,69 @@
+//! Public search responses for folded ACP conversations.
+
+use chrono::{DateTime, Utc};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+/// Side of a folded conversation.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentSessionAuthor {
+ /// User prompt.
+ User,
+ /// Agent response.
+ Agent,
+}
+
+/// Stable navigation target from the fold, independent of raw ACP log IDs.
+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
+pub struct SearchGotoAgentSession {
+ /// Fold-assigned turn.
+ pub message_turn: u32,
+ /// Author within the turn.
+ pub author: AgentSessionAuthor,
+}
+
+impl From<opensearch_client::search::model::SearchGotoAgentSession> for SearchGotoAgentSession {
+ fn from(value: opensearch_client::search::model::SearchGotoAgentSession) -> Self {
+ use opensearch_client::search::model::AgentSessionAuthor as Author;
+ Self {
+ message_turn: value.message_turn,
+ author: match value.author {
+ Author::User => AgentSessionAuthor::User,
+ Author::Agent => AgentSessionAuthor::Agent,
+ },
+ }
+ }
+}
+
+/// A name match or one matching folded message.
+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
+pub struct AgentSessionSearchResult {
+ /// Absent for a name-only match.
+ pub goto: Option<SearchGotoAgentSession>,
+ /// Matched name/content fragments.
+ pub highlight: crate::SearchHighlight,
+ /// Search score.
+ pub score: Option<f64>,
+}
+
+/// One accessible agent session, grouped with its matching folded messages.
+#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]
+pub struct AgentSessionSearchResponseItem {
+ /// Session ID.
+ pub id: Uuid,
+ /// Current persisted name.
+ pub name: String,
+ /// Session owner.
+ pub owner_id: String,
+ /// Agent persona ID.
+ pub bot_id: Uuid,
+ /// Session creation time.
+ pub created_at: DateTime<Utc>,
+ /// Current persisted modification time.
+ pub updated_at: DateTime<Utc>,
+ /// Name and folded-message matches.
+ pub agent_session_search_results: Vec<AgentSessionSearchResult>,
+}
diff --git a/crates/models_search/src/lib.rs b/crates/models_search/src/lib.rs
index be2a30284d..f0432d6a57 100644
--- a/crates/models_search/src/lib.rs
+++ b/crates/models_search/src/lib.rs
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use strum::{Display, EnumString};
use utoipa::ToSchema;
+pub mod agent_session;
pub mod calendar_event;
pub mod call_record;
pub mod channel;
diff --git a/crates/models_search/src/simple.rs b/crates/models_search/src/simple.rs
index 5b6bd55f6f..5112e7051e 100644
--- a/crates/models_search/src/simple.rs
+++ b/crates/models_search/src/simple.rs
@@ -65,6 +65,7 @@ pub struct SearchGotoCallRecord {
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
#[serde(untagged)]
pub enum SearchGotoContent {
+ AgentSessions(crate::agent_session::SearchGotoAgentSession),
Documents(SearchGotoDocument),
Chats(SearchGotoChat),
Emails(SearchGotoEmail),
@@ -75,6 +76,9 @@ pub enum SearchGotoContent {
impl From<opensearch_client::search::model::SearchGotoContent> for SearchGotoContent {
fn from(goto: opensearch_client::search::model::SearchGotoContent) -> Self {
match goto {
+ opensearch_client::search::model::SearchGotoContent::AgentSessions(a) => {
+ Self::AgentSessions(a.into())
+ }
opensearch_client::search::model::SearchGotoContent::Documents(a) => {
SearchGotoContent::Documents(SearchGotoDocument {
node_id: a.node_id,
diff --git a/crates/models_search/src/unified.rs b/crates/models_search/src/unified.rs
index fc6f3842ca..3ca9d1452e 100644
--- a/crates/models_search/src/unified.rs
+++ b/crates/models_search/src/unified.rs
@@ -25,6 +25,8 @@ use utoipa::ToSchema;
#[derive(Debug, Serialize, Deserialize, Clone, ToSchema, JsonSchema, Eq, PartialEq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum UnifiedSearchIndex {
+ #[serde(rename = "agent_sessions")]
+ AgentSessions,
Documents,
Chats,
Emails,
@@ -45,11 +47,18 @@ pub fn entity_filters_from_include(
include: Vec<UnifiedSearchIndex>,
base: EntityFilters,
) -> EntityFilters {
+ let mut filters = base;
if include.is_empty() {
- return base;
+ filters.agent_session_filters.include = true;
+ return filters;
}
+
let exclude = vec![NIL_UUID.to_string()];
- let mut filters = base;
+ if include.contains(&UnifiedSearchIndex::AgentSessions) {
+ filters.agent_session_filters.include = true;
+ } else {
+ filters.agent_session_filters.ids = exclude.clone();
+ }
if !include.contains(&UnifiedSearchIndex::Documents) {
filters.document_filters.document_ids = exclude.clone();
}
@@ -119,6 +128,10 @@ pub fn is_searchable_association(assoc: &FileAssociation) -> bool {
/// and expands file association prefixes (e.g. `assoc:code`) to concrete extensions.
#[derive(Debug, Clone)]
pub struct SearchEntityFilters {
+ /// Whether to include folded agent sessions.
+ pub should_include_agent_sessions: bool,
+ /// Agent-session filters.
+ pub agent_session_filters: item_filters::AgentSessionFilters,
/// Whether to include documents in search results
pub should_include_documents: bool,
/// Whether to include chats in search results
@@ -171,6 +184,12 @@ fn expand_file_types_for_search(file_types: Vec<String>) -> Vec<String> {
impl From<EntityFilters> for SearchEntityFilters {
fn from(filters: EntityFilters) -> Self {
+ let mut agent_session_filters = filters.agent_session_filters;
+ let should_include_agent_sessions = (agent_session_filters.include
+ || !agent_session_filters.ids.is_empty()
+ || !agent_session_filters.owners.is_empty())
+ && !contains_nil_uuid(&agent_session_filters.ids);
+ strip_nil_uuids(&mut agent_session_filters.ids);
let mut document_filters = filters.document_filters;
let mut chat_filters = filters.chat_filters;
let mut email_filters = filters.email_filters;
@@ -200,6 +219,8 @@ impl From<EntityFilters> for SearchEntityFilters {
document_filters.file_types = expand_file_types_for_search(document_filters.file_types);
Self {
+ should_include_agent_sessions,
+ agent_session_filters,
should_include_documents,
should_include_chats,
should_include_emails,
@@ -230,11 +251,13 @@ pub enum UnifiedSearchResponseItem {
Call(CallRecordSearchResponseItemWithMetadata),
Company(crate::crm_company::CrmCompanySearchResponseItem),
CalendarEvent(crate::calendar_event::CalendarEventSearchResponseItemWithMetadata),
+ AgentSession(crate::agent_session::AgentSessionSearchResponseItem),
}
impl UnifiedSearchResponseItem {
pub fn entity_id(&self) -> Uuid {
match self {
+ Self::AgentSession(item) => item.id,
Self::Document(item) => item.extra.id,
Self::Chat(item) => item.extra.id,
Self::Email(item) => item.extra.id,
@@ -249,6 +272,7 @@ impl UnifiedSearchResponseItem {
/// Get the updated_at timestamp for each item
pub fn updated_at(&self) -> Option<DateTime<Utc>> {
match self {
+ Self::AgentSession(item) => Some(item.updated_at),
Self::Document(item) => item.metadata.as_ref().map(|m| m.updated_at),
Self::Chat(item) => item.metadata.as_ref().map(|m| m.updated_at),
Self::Email(item) => Some(item.updated_at),
diff --git a/crates/models_search/src/unified/test.rs b/crates/models_search/src/unified/test.rs
index 2a40729c89..770cfbc835 100644
--- a/crates/models_search/src/unified/test.rs
+++ b/crates/models_search/src/unified/test.rs
@@ -1,5 +1,35 @@
use super::*;
+#[test]
+fn agent_sessions_respect_inclusion_and_nil_exclusion() {
+ let all = SearchEntityFilters::from(EntityFilters::default());
+ assert!(!all.should_include_agent_sessions);
+ let all = SearchEntityFilters::from(entity_filters_from_include(
+ vec![],
+ EntityFilters::default(),
+ ));
+ assert!(all.should_include_agent_sessions);
+ let only = SearchEntityFilters::from(entity_filters_from_include(
+ vec![UnifiedSearchIndex::AgentSessions],
+ EntityFilters::default(),
+ ));
+ assert!(only.should_include_agent_sessions);
+ assert!(!only.should_include_chats);
+ assert!(!only.should_include_documents);
+ let legacy = SearchEntityFilters::from(entity_filters_from_include(
+ vec![UnifiedSearchIndex::Chats],
+ EntityFilters::default(),
+ ));
+ assert!(!legacy.should_include_agent_sessions);
+ assert!(legacy.should_include_chats);
+ let mut filters = EntityFilters::default();
+ filters.agent_session_filters.ids = vec![
+ NIL_UUID.into(),
+ "00000000-0000-0000-0000-000000000001".into(),
+ ];
+ assert!(!SearchEntityFilters::from(filters).should_include_agent_sessions);
+}
+
#[test]
fn empty_entity_type_filter_includes_channels() {
let filters = SearchEntityFilters::from(entity_filters_from_include(
diff --git a/crates/opensearch_client/src/search/agent_sessions.rs b/crates/opensearch_client/src/search/agent_sessions.rs
new file mode 100644
index 0000000000..6a0e3f240f
--- /dev/null
+++ b/crates/opensearch_client/src/search/agent_sessions.rs
@@ -0,0 +1,175 @@
+//! Query and hit conversion for the user-visible projection of an agent session.
+
+use std::collections::{BTreeMap, HashSet};
+
+use models_opensearch::{OpenSearchEntityType, SearchEntityType};
+use opensearch_query_builder::{BoolQueryBuilder, HasChildQuery, InnerHits, QueryType};
+
+use super::{
+ builder::{SearchQueryBuilder, SearchQueryConfig},
+ chats::{
+ build_all_terms_highlight_query, build_child_content_query, inner_hits_content_highlight,
+ },
+ model::{Hit, SearchGotoAgentSession, SearchGotoContent, SearchHit, parse_highlight_hit},
+ query::Keys,
+ utils::millis_to_datetime,
+};
+use crate::Result;
+
+#[cfg(test)]
+mod test;
+
+/// Which fields of a folded conversation to search.
+#[derive(Debug, Default, Clone, Copy)]
+pub enum AgentSessionSearchMode {
+ /// Only the session name.
+ Name,
+ /// Only folded messages.
+ #[default]
+ Content,
+ /// Either the name or folded messages.
+ NameContent,
+}
+
+/// Arguments resolved by the search service from current database access.
+#[derive(Debug, Default, Clone)]
+pub struct AgentSessionSearchArgs {
+ /// Every term must match in the same session.
+ pub terms: Vec<String>,
+ /// Authorized session UUIDs. An empty list must never search all sessions.
+ pub session_ids: Vec<String>,
+ /// Name/content selection.
+ pub mode: AgentSessionSearchMode,
+}
+
+struct AgentSessionSearchConfig;
+
+impl SearchQueryConfig for AgentSessionSearchConfig {
+ const ID_KEY: &'static str = "agent_session_id";
+ const TITLE_KEY: &'static str = "name";
+ const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::AgentSessions;
+}
+
+pub(super) fn build_query(
+ args: &AgentSessionSearchArgs,
+ match_type: &str,
+) -> Result<BoolQueryBuilder<'static>> {
+ let inner = SearchQueryBuilder::<AgentSessionSearchConfig>::new(args.terms.clone())
+ .ids(args.session_ids.clone())
+ .ids_only(true)
+ .match_type(match_type);
+ if args.terms.is_empty() {
+ return Err(crate::error::OpensearchClientError::NoTermsProvided);
+ }
+ let mut query = BoolQueryBuilder::new();
+ query.filter(QueryType::term("_index", "agent_sessions"));
+ query.filter(QueryType::term("agent_session_relation", "agent_session"));
+ query.filter(inner.build_filter_query(None)?.to_owned());
+ query.minimum_should_match(1);
+ if matches!(
+ args.mode,
+ AgentSessionSearchMode::Name | AgentSessionSearchMode::NameContent
+ ) {
+ query.should(inner.build_title_term_query()?.to_owned());
+ }
+ if matches!(
+ args.mode,
+ AgentSessionSearchMode::Content | AgentSessionSearchMode::NameContent
+ ) {
+ let mut content = BoolQueryBuilder::new();
+ let highlight = build_all_terms_highlight_query(&args.terms, match_type);
+ for (index, term) in args.terms.iter().enumerate() {
+ content.must(
+ HasChildQuery::new("message", build_child_content_query(term, match_type))
+ .inner_hits(
+ InnerHits::new()
+ .name(format!("agent_term_{index}"))
+ .size(100)
+ .highlight(inner_hits_content_highlight(&highlight)),
+ )
+ .into(),
+ );
+ }
+ query.should(content.build().into());
+ }
+ Ok(query)
+}
+
+/// Only projected metadata is decoded; raw ACP logs are never queried.
+#[derive(Debug, serde::Deserialize)]
+pub(crate) struct AgentSessionIndex {
+ pub agent_session_id: uuid::Uuid,
+ pub updated_at_millis: i64,
+}
+
+#[derive(serde::Deserialize)]
+struct MessageHit {
+ #[serde(rename = "_id")]
+ id: String,
+ #[serde(rename = "_score")]
+ score: Option<f64>,
+ #[serde(rename = "_source")]
+ source: SearchGotoAgentSession,
+ #[serde(default)]
+ highlight: std::collections::HashMap<String, Vec<String>>,
+}
+
+#[derive(serde::Deserialize)]
+struct MessageHits {
+ hits: Vec<MessageHit>,
+}
+
+#[derive(serde::Deserialize)]
+struct MessageGroup {
+ hits: MessageHits,
+}
+
+const KEYS: Keys<'static> = Keys {
+ title_key: "name",
+ content_key: "content",
+};
+
+pub(super) fn expand(hit: Hit<AgentSessionIndex>) -> Vec<SearchHit> {
+ let id = hit.source.agent_session_id;
+ let updated_at = millis_to_datetime(Some(hit.source.updated_at_millis));
+ let mut out = Vec::new();
+ if let Some(highlight) = hit.highlight
+ && highlight.contains_key("name")
+ {
+ out.push(SearchHit {
+ entity_id: id,
+ entity_type: SearchEntityType::AgentSessions,
+ score: hit.score,
+ highlight: parse_highlight_hit(highlight, KEYS),
+ goto: None,
+ updated_at,
+ });
+ }
+ if let Some(inner) = hit.inner_hits {
+ // Ordered groups and ID dedup make multi-term responses deterministic.
+ let groups: BTreeMap<String, MessageGroup> = match serde_json::from_value(inner) {
+ Ok(groups) => groups,
+ Err(error) => {
+ tracing::error!(error=?error, session_id=%id, "invalid agent-session inner hits");
+ return out;
+ }
+ };
+ let mut seen = HashSet::new();
+ for group in groups.into_values() {
+ for message in group.hits.hits {
+ if !seen.insert(message.id) {
+ continue;
+ }
+ out.push(SearchHit {
+ entity_id: id,
+ entity_type: SearchEntityType::AgentSessions,
+ score: message.score,
+ highlight: parse_highlight_hit(message.highlight, KEYS),
+ goto: Some(SearchGotoContent::AgentSessions(message.source)),
+ updated_at,
+ });
+ }
+ }
+ }
+ out
+}
diff --git a/crates/opensearch_client/src/search/agent_sessions/test.rs b/crates/opensearch_client/src/search/agent_sessions/test.rs
new file mode 100644
index 0000000000..6bd5d9cf4e
--- /dev/null
+++ b/crates/opensearch_client/src/search/agent_sessions/test.rs
@@ -0,0 +1,84 @@
+use super::*;
+use opensearch_query_builder::ToOpenSearchJson;
+
+fn args(mode: AgentSessionSearchMode) -> AgentSessionSearchArgs {
+ AgentSessionSearchArgs {
+ terms: vec!["burger".into(), "fries".into()],
+ session_ids: vec!["00000000-0000-0000-0000-000000000001".into()],
+ mode,
+ }
+}
+
+#[test]
+fn access_allowlist_is_required_and_filters_parents() {
+ let mut args = args(AgentSessionSearchMode::Content);
+ let query = build_query(&args, "partial").unwrap().build().to_json();
+ let filter = query["bool"]["filter"].as_array().unwrap();
+ assert!(filter.contains(&serde_json::json!({"terms":{"agent_session_id":args.session_ids}})));
+ assert!(filter.contains(&serde_json::json!({"term":{"_index":"agent_sessions"}})));
+ assert!(
+ filter.contains(&serde_json::json!({"term":{"agent_session_relation":"agent_session"}}))
+ );
+ args.session_ids.clear();
+ assert!(build_query(&args, "partial").is_err());
+}
+
+#[test]
+fn modes_keep_names_and_folded_content_separate_and_terms_in_one_session() {
+ let content = build_query(&args(AgentSessionSearchMode::Content), "partial")
+ .unwrap()
+ .build()
+ .to_json();
+ let clauses = content["bool"]["should"].as_array().unwrap();
+ assert_eq!(clauses.len(), 1);
+ let terms = clauses[0]["bool"]["must"].as_array().unwrap();
+ assert_eq!(terms.len(), 2);
+ assert_eq!(terms[0]["has_child"]["type"], "message");
+ assert!(terms[0]["has_child"]["query"]["match_phrase_prefix"].is_object());
+ let name = build_query(&args(AgentSessionSearchMode::Name), "exact")
+ .unwrap()
+ .build()
+ .to_json();
+ assert!(!name.to_string().contains("has_child"));
+ let both = build_query(&args(AgentSessionSearchMode::NameContent), "exact")
+ .unwrap()
+ .build()
+ .to_json();
+ assert_eq!(both["bool"]["should"].as_array().unwrap().len(), 2);
+ assert!(!both.to_string().contains("match_phrase_prefix"));
+}
+
+#[test]
+fn folded_hits_keep_turn_author_and_deduplicate_across_terms() {
+ let message = serde_json::json!({
+ "_id":"session:3:agent", "_score":2.0,
+ "_source":{"message_turn":3,"author":"agent"},
+ "highlight":{"content":["<macro_em>burger</macro_em> and fries"]}
+ });
+ let hit = Hit {
+ source: AgentSessionIndex {
+ agent_session_id: uuid::Uuid::from_u128(1),
+ updated_at_millis: 1_789_130_978_862,
+ },
+ index: "arbitrary-physical-index".into(),
+ matched_queries: vec!["agent_sessions".into()],
+ score: Some(1.0),
+ highlight: Some(std::collections::HashMap::from([(
+ "name".into(),
+ vec!["<macro_em>burger</macro_em>".into()],
+ )])),
+ inner_hits: Some(serde_json::json!({
+ "agent_term_0":{"hits":{"hits":[message.clone()]}},
+ "agent_term_1":{"hits":{"hits":[message]}}
+ })),
+ };
+ let hits = expand(hit);
+ assert_eq!(hits.len(), 2);
+ assert!(hits[0].goto.is_none());
+ let Some(SearchGotoContent::AgentSessions(goto)) = &hits[1].goto else {
+ panic!("missing folded target")
+ };
+ assert_eq!(goto.message_turn, 3);
+ assert_eq!(goto.author, super::super::model::AgentSessionAuthor::Agent);
+ assert_eq!(hits[1].highlight.content.len(), 1);
+}
diff --git a/crates/opensearch_client/src/search/chats.rs b/crates/opensearch_client/src/search/chats.rs
index b3b2d4980f..467d51c889 100644
--- a/crates/opensearch_client/src/search/chats.rs
+++ b/crates/opensearch_client/src/search/chats.rs
@@ -186,7 +186,9 @@ impl ChatQueryBuilder {
}
/// Highlight config attached to each `has_child` inner_hits block.
-fn inner_hits_content_highlight(highlight_query: &serde_json::Value) -> serde_json::Value {
+pub(super) fn inner_hits_content_highlight(
+ highlight_query: &serde_json::Value,
+) -> serde_json::Value {
serde_json::json!({
"require_field_match": true,
"max_analyzer_offset": super::HIGHLIGHT_MAX_ANALYZER_OFFSET,
@@ -204,7 +206,10 @@ fn inner_hits_content_highlight(highlight_query: &serde_json::Value) -> serde_js
}
/// Combined OR-of-all-terms query used as the inner_hits highlight_query.
-fn build_all_terms_highlight_query(terms: &[String], match_type: &str) -> serde_json::Value {
+pub(super) fn build_all_terms_highlight_query(
+ terms: &[String],
+ match_type: &str,
+) -> serde_json::Value {
let term_queries: Vec<serde_json::Value> = terms
.iter()
.map(|t| build_child_content_query(t, match_type).to_json())
@@ -221,7 +226,7 @@ fn build_all_terms_highlight_query(terms: &[String], match_type: &str) -> serde_
}
/// Build the per-term query that runs inside `has_child` against `content`.
-fn build_child_content_query<'a>(term: &str, match_type: &str) -> QueryType<'a> {
+pub(super) fn build_child_content_query<'a>(term: &str, match_type: &str) -> QueryType<'a> {
let exact = match_type == "exact"
|| term.chars().any(|c| c.is_whitespace())
|| term.chars().count() < MIN_PREFIX_LEN;
diff --git a/crates/opensearch_client/src/search/mod.rs b/crates/opensearch_client/src/search/mod.rs
index 46a0d631c5..8ea69aab0d 100644
--- a/crates/opensearch_client/src/search/mod.rs
+++ b/crates/opensearch_client/src/search/mod.rs
@@ -7,6 +7,7 @@
/// from the (HTTP 200, partial) response.
pub(crate) const HIGHLIGHT_MAX_ANALYZER_OFFSET: u32 = 999_999;
+pub mod agent_sessions;
mod builder;
pub mod calendar_events;
pub mod call_records;
diff --git a/crates/opensearch_client/src/search/model.rs b/crates/opensearch_client/src/search/model.rs
index 304ad11b2c..0003f872d5 100644
--- a/crates/opensearch_client/src/search/model.rs
+++ b/crates/opensearch_client/src/search/model.rs
@@ -442,6 +442,7 @@ pub struct SearchGotoCallRecord {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(untagged)]
pub enum SearchGotoContent {
+ AgentSessions(SearchGotoAgentSession),
Documents(SearchGotoDocument),
Chats(SearchGotoChat),
Emails(SearchGotoEmail),
@@ -450,6 +451,25 @@ pub enum SearchGotoContent {
// there is no goto needed for projects
}
+/// Identity of a user-visible folded message within a session.
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
+pub struct SearchGotoAgentSession {
+ /// Fold-assigned turn number.
+ pub message_turn: u32,
+ /// Side of the conversation within that turn.
+ pub author: AgentSessionAuthor,
+}
+
+/// Author sides emitted by the ACP fold.
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentSessionAuthor {
+ /// User-authored prompt.
+ User,
+ /// Agent-authored response.
+ Agent,
+}
+
/// This struct represents a single search hit for a given entity
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct SearchHit {
diff --git a/crates/opensearch_client/src/search/unified.rs b/crates/opensearch_client/src/search/unified.rs
index b7735c22cd..3c0e46fad0 100644
--- a/crates/opensearch_client/src/search/unified.rs
+++ b/crates/opensearch_client/src/search/unified.rs
@@ -51,6 +51,8 @@ impl UnifiedSearchArgs {
#[derive(Debug, Default, Clone)]
pub struct UnifiedSearchArgs {
+ /// Authorized folded-agent-session search.
+ pub agent_session_search_args: super::agent_sessions::AgentSessionSearchArgs,
pub user_id: String,
pub page: u32,
pub page_size: u32,
@@ -316,6 +318,7 @@ pub struct UnifiedProjectSearchArgs {
/// physical index it happened to live in.
#[derive(Debug)]
pub(crate) enum UnifiedSearchIndex {
+ AgentSession(super::agent_sessions::AgentSessionIndex),
ChannelMessage(ChannelMessageIndex),
Document(DocumentIndex),
Chat(ChatIndex),
@@ -358,6 +361,7 @@ impl UnifiedSearchIndex {
}
Ok(match entity {
+ OpenSearchEntityType::AgentSessions => Self::AgentSession(parse(&entity, source)?),
OpenSearchEntityType::Channels => Self::ChannelMessage(parse(&entity, source)?),
OpenSearchEntityType::Documents => Self::Document(parse(&entity, source)?),
OpenSearchEntityType::Chats => Self::Chat(parse(&entity, source)?),
@@ -371,6 +375,7 @@ impl UnifiedSearchIndex {
#[derive(Default)]
pub struct SplitUnifiedSearchResponseValues {
+ pub agent_session: Vec<SearchHit>,
pub channel_message: Vec<SearchHit>,
pub chat: Vec<SearchHit>,
pub document: Vec<SearchHit>,
@@ -393,6 +398,7 @@ where
let mut split = SplitUnifiedSearchResponseValues::default();
for item in self {
match item.entity_type {
+ SearchEntityType::AgentSessions => split.agent_session.push(item),
SearchEntityType::Channels => split.channel_message.push(item),
SearchEntityType::Chats => split.chat.push(item),
SearchEntityType::Documents => split.document.push(item),
@@ -415,6 +421,16 @@ where
/// unpack those into child-level hits; everything else (channels,
/// emails) takes the 1:1 conversion.
fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {
+ if let UnifiedSearchIndex::AgentSession(source) = hit.source {
+ return super::agent_sessions::expand(Hit {
+ source,
+ index: hit.index,
+ matched_queries: hit.matched_queries,
+ score: hit.score,
+ highlight: hit.highlight,
+ inner_hits: hit.inner_hits,
+ });
+ }
match &hit.source {
UnifiedSearchIndex::Document(parent) => {
let entity_id = parent.entity_id;
@@ -527,6 +543,25 @@ fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {
impl From<Hit<UnifiedSearchIndex>> for SearchHit {
fn from(index: Hit<UnifiedSearchIndex>) -> Self {
match index.source {
+ UnifiedSearchIndex::AgentSession(a) => SearchHit {
+ entity_id: a.agent_session_id,
+ entity_type: SearchEntityType::AgentSessions,
+ score: index.score,
+ highlight: index
+ .highlight
+ .map(|h| {
+ parse_highlight_hit(
+ h,
+ Keys {
+ title_key: "name",
+ content_key: "content",
+ },
+ )
+ })
+ .unwrap_or_default(),
+ goto: None,
+ updated_at: millis_to_datetime(Some(a.updated_at_millis)),
+ },
UnifiedSearchIndex::ChannelMessage(a) => SearchHit {
entity_id: a.entity_id,
entity_type: SearchEntityType::Channels,
@@ -709,6 +744,15 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
// There will always be 1 query as the indices are never empty
bool_query.minimum_should_match(1);
+ if args
+ .search_indices
+ .contains(&OpenSearchEntityType::AgentSessions)
+ {
+ let mut query =
+ super::agent_sessions::build_query(&args.agent_session_search_args, &args.match_type)?;
+ query.name(OpenSearchEntityType::AgentSessions.query_name());
+ bool_query.should(query.build().into());
+ }
if args
.search_indices
diff --git a/crates/opensearch_client/src/search/unified/test.rs b/crates/opensearch_client/src/search/unified/test.rs
index c8e54c805a..84a4396c50 100644
--- a/crates/opensearch_client/src/search/unified/test.rs
+++ b/crates/opensearch_client/src/search/unified/test.rs
@@ -5,6 +5,47 @@ use chrono::Utc;
use models_search_cursor::SearchMethodCursor;
use opensearch_query_builder::ToOpenSearchJson;
+#[test]
+fn agent_sessions_expand_and_paginate_as_entities_not_messages() {
+ let session_id = uuid::Uuid::from_u128(1);
+ let next_id = uuid::Uuid::from_u128(2);
+ let session = Hit {
+ index: "agent_sessions".into(),
+ matched_queries: vec!["agent_sessions".into()],
+ score: Some(1.0),
+ source: serde_json::json!({
+ "agent_session_id": session_id,
+ "updated_at_millis": 1783000000000_i64,
+ }),
+ highlight: None,
+ inner_hits: Some(serde_json::json!({
+ "agent_term_0": {"hits": {"hits": [
+ {"_id": "user", "_source": {"message_turn": 0, "author": "user"},
+ "highlight": {"content": ["<macro_em>match</macro_em>"]}},
+ {"_id": "agent", "_source": {"message_turn": 0, "author": "agent"},
+ "highlight": {"content": ["<macro_em>match</macro_em>"]}}
+ ]}}
+ })),
+ };
+ let (hits, cursor) = paginate_unified_hits(
+ vec![session, doc_hit_with_chunks(next_id, 1782999999000, 1)],
+ 1,
+ );
+ assert_eq!(hits.len(), 2);
+ assert!(hits.iter().all(|hit| hit.entity_id == session_id));
+ let SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt { entity_id, .. })) = cursor
+ else {
+ panic!("expected a continuation anchored on the session")
+ };
+ assert_eq!(entity_id, session_id);
+ let split = hits.into_iter().split_search_response();
+ assert_eq!(split.agent_session.len(), 2);
+ assert!(
+ split.chat.is_empty(),
+ "agent sessions are not legacy DCS chats"
+ );
+}
+
#[test]
fn expand_document_name_highlight_yields_name_hit_without_goto() {
use std::collections::HashMap;
@@ -495,6 +536,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
call_record_search_args: UnifiedCallRecordSearchArgs::default(),
project_search_args: UnifiedProjectSearchArgs::default(),
calendar_event_search_args: UnifiedCalendarEventSearchArgs::default(),
+ agent_session_search_args: Default::default(),
cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id,
updated_at: time,
@@ -803,6 +845,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
call_record_search_args: UnifiedCallRecordSearchArgs::default(),
project_search_args: UnifiedProjectSearchArgs::default(),
calendar_event_search_args: UnifiedCalendarEventSearchArgs::default(),
+ agent_session_search_args: Default::default(),
cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
entity_id,
updated_at: time,
@@ -1277,6 +1320,11 @@ fn every_searched_index_contributes_a_named_clause() -> anyhow::Result<()> {
let args = UnifiedSearchArgs {
search_indices: OpenSearchEntityType::iter().collect(),
+ agent_session_search_args: super::super::agent_sessions::AgentSessionSearchArgs {
+ terms: vec!["test".into()],
+ session_ids: vec![uuid::Uuid::from_u128(1).to_string()],
+ ..Default::default()
+ },
user_id: "user".to_string(),
page_size: 10,
match_type: "exact".to_string(),
diff --git a/crates/search_service/Cargo.toml b/crates/search_service/Cargo.toml
index b6022ea99f..af644ecf02 100644
--- a/crates/search_service/Cargo.toml
+++ b/crates/search_service/Cargo.toml
@@ -13,6 +13,8 @@ name = "search_service_openapi"
path = "src/openapi.rs"
[dependencies]
+agent_session = { path = "../agent_session", default-features = false }
+rootcause = { workspace = true }
anyhow = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
macro_aws_config = { path = "../macro_aws_config" }
diff --git a/crates/search_service/src/api/context.rs b/crates/search_service/src/api/context.rs
index 6ea7f9402d..1c187f5b66 100644
--- a/crates/search_service/src/api/context.rs
+++ b/crates/search_service/src/api/context.rs
@@ -1,3 +1,4 @@
+use agent_session::domain::search::AgentSessionSearchMetadataService;
use axum::extract::FromRef;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
@@ -27,9 +28,28 @@ pub struct SearchHandlerState {
pub entity_access_service: Arc<SearchEntityAccessService>,
/// Authorization state used to authenticate search requests.
pub authorization_state: MacroAuthorizationState<SearchAuthorizationService>,
+ /// Agent-session domain service used after the search layer resolves its
+ /// authorized session allowlist.
+ pub agent_session_search_metadata: Arc<dyn AgentSessionSearchMetadataService>,
/// Whether calendar events participate in search. Off in deployed
/// environments until the calendar index has been created and backfilled;
/// gating here covers every caller of the search API at once, the AI
/// search tools included.
pub calendar_search_enabled: bool,
}
+
+impl SearchHandlerState {
+ /// Assemble the agent-session search use case from read-only adapters.
+ pub(crate) fn agent_session_search(
+ &self,
+ ) -> crate::domain::agent_session::AgentSessionSearchService<
+ crate::outbound::agent_session::AgentSessionSearchMetadataSource,
+ > {
+ crate::domain::agent_session::AgentSessionSearchService(
+ crate::outbound::agent_session::AgentSessionSearchMetadataSource {
+ db: self.db.clone(),
+ service: self.agent_session_search_metadata.clone(),
+ },
+ )
+ }
+}
diff --git a/crates/search_service/src/api/search.rs b/crates/search_service/src/api/search.rs
index 2ac83f04fc..6d1cd47d61 100644
--- a/crates/search_service/src/api/search.rs
+++ b/crates/search_service/src/api/search.rs
@@ -2,6 +2,7 @@ use axum::{Router, routing::post};
use crate::api::context::SearchHandlerState;
+pub(in crate::api) mod agent_session;
pub(in crate::api) mod calendar_event;
pub(in crate::api) mod call_record;
pub(in crate::api) mod channel;
diff --git a/crates/search_service/src/api/search/agent_session.rs b/crates/search_service/src/api/search/agent_session.rs
new file mode 100644
index 0000000000..8d73d4903c
--- /dev/null
+++ b/crates/search_service/src/api/search/agent_session.rs
@@ -0,0 +1,60 @@
+//! Map authorized session metadata and folded message matches into API results.
+
+use indexmap::IndexMap;
+use macro_user_id::user_id::MacroUserId;
+use models_search::agent_session::{AgentSessionSearchResponseItem, AgentSessionSearchResult};
+use opensearch_client::search::model::{SearchGotoContent, SearchHit};
+
+use crate::api::{context::SearchHandlerState, search::simple::SearchError};
+
+pub(super) async fn enrich_agent_sessions(
+ ctx: &SearchHandlerState,
+ user_id: &str,
+ hits: Vec<SearchHit>,
+) -> Result<Vec<AgentSessionSearchResponseItem>, SearchError> {
+ if hits.is_empty() {
+ return Ok(Vec::new());
+ }
+ let user = MacroUserId::parse_from_str(user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_owned()))?
+ .lowercase();
+ let ids: Vec<_> = hits.iter().map(|hit| hit.entity_id).collect();
+ let sessions = ctx
+ .agent_session_search()
+ .scope(&user, &ids, &[], true, false)
+ .await
+ .map_err(|error| SearchError::InternalError(anyhow::anyhow!("{error}")))?;
+ let mut results: IndexMap<_, _> = sessions
+ .into_iter()
+ .map(|session| {
+ (
+ session.id,
+ AgentSessionSearchResponseItem {
+ id: session.id,
+ name: session.name,
+ owner_id: session.owner_id.to_string(),
+ bot_id: session.bot_id,
+ created_at: session.created_at,
+ updated_at: session.updated_at,
+ agent_session_search_results: Vec::new(),
+ },
+ )
+ })
+ .collect();
+ for hit in hits {
+ if let Some(session) = results.get_mut(&hit.entity_id) {
+ let goto = match hit.goto {
+ Some(SearchGotoContent::AgentSessions(goto)) => Some(goto.into()),
+ _ => None,
+ };
+ session
+ .agent_session_search_results
+ .push(AgentSessionSearchResult {
+ goto,
+ highlight: hit.highlight.into(),
+ score: hit.score,
+ });
+ }
+ }
+ Ok(results.into_values().collect())
+}
diff --git a/crates/search_service/src/api/search/enrich.rs b/crates/search_service/src/api/search/enrich.rs
index b408b78925..60fdc78214 100644
--- a/crates/search_service/src/api/search/enrich.rs
+++ b/crates/search_service/src/api/search/enrich.rs
@@ -23,6 +23,13 @@ pub async fn enrich_search_response(
search_term: Option<&str>,
) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {
match entity_type {
+ SearchEntityType::AgentSessions => Ok(super::agent_session::enrich_agent_sessions(
+ ctx, user_id, results,
+ )
+ .await?
+ .into_iter()
+ .map(UnifiedSearchResponseItem::AgentSession)
+ .collect()),
SearchEntityType::Documents => {
let response = enrich_documents(ctx, user_id, results, search_term).await?;
Ok(response
diff --git a/crates/search_service/src/api/search/simple.rs b/crates/search_service/src/api/search/simple.rs
index b196a478ef..3132a82d4b 100644
--- a/crates/search_service/src/api/search/simple.rs
+++ b/crates/search_service/src/api/search/simple.rs
@@ -54,6 +54,9 @@ pub enum SearchError {
/// A CRM company filter id was not a valid UUID
#[error("invalid crm company id: {0}")]
InvalidCrmCompanyId(String),
+ /// An agent-session filter is not a UUID.
+ #[error("invalid agent session id: {0}")]
+ InvalidAgentSessionId(String),
/// Opensearch error occurred
#[error("unable to search")]
Search(#[from] OpensearchClientError),
@@ -76,6 +79,7 @@ impl IntoResponse for SearchError {
| SearchError::TooManyTerms
| SearchError::InvalidCursor
| SearchError::InvalidCrmCompanyId(_)
+ | SearchError::InvalidAgentSessionId(_)
| SearchError::NoQueryOrTermsProvided
| SearchError::NoChannelIds => StatusCode::BAD_REQUEST,
SearchError::NameSearch(NameSearchError::IncompatibleCursor) => StatusCode::BAD_REQUEST,
diff --git a/crates/search_service/src/api/search/simple/simple_unified.rs b/crates/search_service/src/api/search/simple/simple_unified.rs
index 9d18f88275..d84f490fe1 100644
--- a/crates/search_service/src/api/search/simple/simple_unified.rs
+++ b/crates/search_service/src/api/search/simple/simple_unified.rs
@@ -16,11 +16,9 @@ use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_user_id::user_id::MacroUserId;
use model::{response::ErrorResponse, user::UserContext};
use models_search::unified::SearchEntityFilters;
-use models_search::{
- SearchOn, SimpleSearchResponse,
- unified::{SimpleUnifiedSearchResponse, UnifiedSearchRequest},
-};
+use models_search::{SearchOn, SimpleSearchResponse, unified::UnifiedSearchRequest};
use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};
+use opensearch_client::search::agent_sessions::{AgentSessionSearchArgs, AgentSessionSearchMode};
use opensearch_client::search::call_records::CallRecordSearchMode;
use opensearch_client::search::documents::{DocumentSearchMode, PropertyFilterArg};
use opensearch_client::search::model::SearchHit;
@@ -260,6 +258,25 @@ pub(in crate::api::search) async fn perform_unified_search(
let should_include_crm = crm_access.is_some() && !tags_active;
let search_filters = SearchEntityFilters::from(req.filters);
+ let requested_sessions = search_filters
+ .agent_session_filters
+ .ids
+ .iter()
+ .map(|id| {
+ uuid::Uuid::parse_str(id).map_err(|_| SearchError::InvalidAgentSessionId(id.clone()))
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let agent_sessions = ctx
+ .agent_session_search()
+ .scope(
+ &user_id,
+ &requested_sessions,
+ &search_filters.agent_session_filters.owners,
+ search_filters.should_include_agent_sessions,
+ tags_active,
+ )
+ .await
+ .map_err(|error| SearchError::InternalError(anyhow::anyhow!("{error}")))?;
let channel_filters = search_filters.channel_filters;
let email_filters = search_filters.email_filters;
let chat_filters = search_filters.chat_filters;
@@ -411,6 +428,18 @@ pub(in crate::api::search) async fn perform_unified_search(
let crm_cursor_for_search = crm_cursor.clone();
let unified_search_args = UnifiedSearchArgs {
+ agent_session_search_args: AgentSessionSearchArgs {
+ terms: search_terms.clone(),
+ session_ids: agent_sessions
+ .iter()
+ .map(|session| session.id.to_string())
+ .collect(),
+ mode: match search_on {
+ SearchOn::Name => AgentSessionSearchMode::Name,
+ SearchOn::Content => AgentSessionSearchMode::Content,
+ SearchOn::NameContent => AgentSessionSearchMode::NameContent,
+ },
+ },
user_id: user_id.as_ref().to_string(),
page: 0, // With cursor-based pagination, we always start from "page 0" relative to cursor
page_size,
@@ -419,6 +448,9 @@ pub(in crate::api::search) async fn perform_unified_search(
collapse,
search_indices: {
let mut indices = std::collections::HashSet::new();
+ if !agent_sessions.is_empty() {
+ indices.insert(models_opensearch::OpenSearchEntityType::AgentSessions);
+ }
if should_include_documents
&& !(filter_document_response.ids_only
&& filter_document_response.document_ids.is_empty())
@@ -509,6 +541,7 @@ pub(in crate::api::search) async fn perform_unified_search(
args.email_search_args.subject_only = true;
args.search_indices.retain(|i| {
*i == models_opensearch::OpenSearchEntityType::Documents
+ || *i == models_opensearch::OpenSearchEntityType::AgentSessions
|| *i == models_opensearch::OpenSearchEntityType::Emails
|| *i == models_opensearch::OpenSearchEntityType::Projects
|| *i == models_opensearch::OpenSearchEntityType::CallRecords
@@ -679,7 +712,7 @@ pub(in crate::api::search) async fn perform_unified_search(
("cursor" = Option<String>, Query, description = "Base64 encoded cursor for pagination."),
),
responses(
- (status = 200, body=SimpleUnifiedSearchResponse),
+ (status = 200, body=SimpleSearchResponse),
(status = 400, body=ErrorResponse),
(status = 401, body=ErrorResponse),
(status = 500, body=ErrorResponse),
diff --git a/crates/search_service/src/api/search/unified.rs b/crates/search_service/src/api/search/unified.rs
index 6634477dd1..dc7db02b5f 100644
--- a/crates/search_service/src/api/search/unified.rs
+++ b/crates/search_service/src/api/search/unified.rs
@@ -71,6 +71,7 @@ pub async fn handler(
// Split the results by entity type
let SplitUnifiedSearchResponseValues {
+ agent_session,
channel_message,
chat,
document,
@@ -82,6 +83,7 @@ pub async fn handler(
} = results.into_iter().split_search_response();
let (
+ enriched_agent_session_results,
enriched_document_results,
enriched_chat_results,
enriched_channel_results,
@@ -91,6 +93,13 @@ pub async fn handler(
enriched_crm_results,
enriched_calendar_event_results,
) = tokio::try_join!(
+ enrich_search_response(
+ &ctx,
+ &user_context.user_id,
+ agent_session,
+ models_opensearch::SearchEntityType::AgentSessions,
+ None,
+ ),
enrich_search_response(
&ctx,
&user_context.user_id,
@@ -146,6 +155,7 @@ pub async fn handler(
let results = {
let mut results = vec![];
+ results.extend(enriched_agent_session_results);
results.extend(enriched_document_results);
results.extend(enriched_chat_results);
diff --git a/crates/search_service/src/domain.rs b/crates/search_service/src/domain.rs
new file mode 100644
index 0000000000..8f8b58aaf7
--- /dev/null
+++ b/crates/search_service/src/domain.rs
@@ -0,0 +1 @@
+pub(crate) mod agent_session;
diff --git a/crates/search_service/src/domain/agent_session.rs b/crates/search_service/src/domain/agent_session.rs
new file mode 100644
index 0000000000..611d354c13
--- /dev/null
+++ b/crates/search_service/src/domain/agent_session.rs
@@ -0,0 +1,50 @@
+//! Search scoping uses current grants, including shared channel sessions.
+
+use agent_session::domain::search::AgentSessionSearchMetadata;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use rootcause::Report;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Source of current metadata restricted to the caller's authoritative grants.
+pub(crate) trait AgentSessionSearchSource {
+ fn accessible(
+ &self,
+ user: &MacroUserId<Lowercase<'_>>,
+ requested: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<AgentSessionSearchMetadata>, Report>> + Send;
+}
+
+/// Resolves an allowlist before search and revalidates it during enrichment.
+pub(crate) struct AgentSessionSearchService<S>(pub S);
+
+impl<S: AgentSessionSearchSource> AgentSessionSearchService<S> {
+ pub async fn scope(
+ &self,
+ user: &MacroUserId<Lowercase<'_>>,
+ requested: &[Uuid],
+ owners: &[String],
+ enabled: bool,
+ tags_active: bool,
+ ) -> Result<Vec<AgentSessionSearchMetadata>, Report> {
+ // Tags aren't projected for sessions yet. Do not return unfiltered sessions.
+ if !enabled || tags_active || requested.iter().any(Uuid::is_nil) {
+ return Ok(Vec::new());
+ }
+ Ok(self
+ .0
+ .accessible(user, requested)
+ .await?
+ .into_iter()
+ .filter(|session| {
+ (requested.is_empty() || requested.contains(&session.id))
+ && (owners.is_empty()
+ || owners
+ .iter()
+ .any(|owner| owner == session.owner_id.as_ref()))
+ })
+ .collect())
+ }
+}
diff --git a/crates/search_service/src/domain/agent_session/test.rs b/crates/search_service/src/domain/agent_session/test.rs
new file mode 100644
index 0000000000..64ce044a89
--- /dev/null
+++ b/crates/search_service/src/domain/agent_session/test.rs
@@ -0,0 +1,72 @@
+use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
+
+struct Source;
+impl AgentSessionSearchSource for Source {
+ async fn accessible(
+ &self,
+ user: &MacroUserId<Lowercase<'_>>,
+ _: &[Uuid],
+ ) -> Result<Vec<AgentSessionSearchMetadata>, Report> {
+ if user.as_ref() == "macro|[email protected]" {
+ return Ok(Vec::new());
+ }
+ Ok(vec![AgentSessionSearchMetadata {
+ id: Uuid::from_u128(1),
+ name: "Shared session".into(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ bot_id: Uuid::from_u128(2),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ }])
+ }
+}
+
+#[tokio::test]
+async fn grants_allow_channel_viewers_without_requiring_ownership() {
+ let service = AgentSessionSearchService(Source);
+ let viewer = MacroUserId::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .lowercase();
+ assert_eq!(
+ service
+ .scope(&viewer, &[], &[], true, false)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ let stranger = MacroUserId::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .lowercase();
+ assert!(
+ service
+ .scope(&stranger, &[], &[], true, false)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn exclusion_requested_ids_owners_and_tags_cannot_broaden_access() {
+ let service = AgentSessionSearchService(Source);
+ let viewer = MacroUserId::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .lowercase();
+ for (ids, owners, enabled, tags) in [
+ (vec![], vec![], false, false),
+ (vec![], vec![], true, true),
+ (vec![Uuid::nil()], vec![], true, false),
+ (vec![Uuid::from_u128(9)], vec![], true, false),
+ (vec![], vec!["macro|[email protected]".into()], true, false),
+ ] {
+ assert!(
+ service
+ .scope(&viewer, &ids, &owners, enabled, tags)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+}
diff --git a/crates/search_service/src/lib.rs b/crates/search_service/src/lib.rs
index 9e2c0671a1..06bd4b67bc 100644
--- a/crates/search_service/src/lib.rs
+++ b/crates/search_service/src/lib.rs
@@ -1,6 +1,8 @@
//! Search Service Library - exposes API routes for integration into other services
pub mod api;
+mod domain;
+mod outbound;
// Re-exports for consumers
pub use api::context::SearchHandlerState;
diff --git a/crates/search_service/src/outbound.rs b/crates/search_service/src/outbound.rs
new file mode 100644
index 0000000000..8f8b58aaf7
--- /dev/null
+++ b/crates/search_service/src/outbound.rs
@@ -0,0 +1 @@
+pub(crate) mod agent_session;
diff --git a/crates/search_service/src/outbound/agent_session.rs b/crates/search_service/src/outbound/agent_session.rs
new file mode 100644
index 0000000000..7acc64e8b1
--- /dev/null
+++ b/crates/search_service/src/outbound/agent_session.rs
@@ -0,0 +1,36 @@
+//! Read adapters consume the agent-session domain service.
+
+use std::sync::Arc;
+
+use agent_session::domain::search::{
+ AgentSessionSearchMetadata, AgentSessionSearchMetadataService,
+};
+use entity_access::outbound::{accessible_session_ids, get_user_source_ids};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use readonly_pool::ReadOnlyPool;
+use rootcause::Report;
+use uuid::Uuid;
+
+use crate::domain::agent_session::AgentSessionSearchSource;
+
+pub(crate) struct AgentSessionSearchMetadataSource {
+ pub db: ReadOnlyPool,
+ pub service: Arc<dyn AgentSessionSearchMetadataService>,
+}
+
+impl AgentSessionSearchSource for AgentSessionSearchMetadataSource {
+ async fn accessible(
+ &self,
+ user: &MacroUserId<Lowercase<'_>>,
+ requested: &[Uuid],
+ ) -> Result<Vec<AgentSessionSearchMetadata>, Report> {
+ let sources = get_user_source_ids(&self.db, Some(user))
+ .await
+ .map_err(|error| rootcause::report!("{error:#}"))?;
+ let ids = accessible_session_ids(&self.db, &sources, requested).await?;
+ self.service
+ .search_metadata(ids)
+ .await
+ .map_err(|error| rootcause::report!("{error:#}"))
+ }
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 39fc7ffe7c..b64ffdd4c3 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -220,6 +220,12 @@ at the latest message, including when history arrives after the empty view. Shor
transcripts sit at the bottom, above the composer. Only the visible rows and an
overscan buffer are mounted: scroll to older turns before searching their DOM text.
+Search links add `agent_message_turn=<zero-based turn>&agent_message_author=user|agent`.
+They wait for history to load, then scroll to and highlight the matching folded
+message instead of staying at latest. Clicking another hit (including in an already
+open session) repeats the jump. Manual navigation or **Scroll to bottom** clears the
+message highlight; incoming output does not repeat the search jump.
+
- New messages and growing streamed replies follow while within 50px of the end.
Scroll up to read history without being pulled back by subsequent output.
- Far above the end, scroll downward to reveal **Scroll to bottom**. Clicking it
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 2218fb0944..8d6dfda405 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -195,6 +195,13 @@ Sidebar `Search` button → `/app/.../component/search` with a focused query box
(including a `Featured Results` group) filter live as you type; no Enter needed. `Ctrl+K` is
usually faster for jump-to-entity; `/` opens workspace search when no editor is focused.
+Agent-session results use the robot icon and show a highlighted transcript snippet.
+`Show more [N]` expands additional matches, labeled **User / Agent · Turn N**.
+Click a snippet to open `/app/agent/<uuid>` at that folded message; a plain row click
+opens the first content match, or opens the session normally for a title-only hit. These are
+ACP-backed sessions, distinct from legacy chat results. Legacy chat rename, delete,
+copy, and move-to-folder actions are not offered on agent-session search rows.
+
## Files — `/app/component/documents`
Tabs `Owned` / `Shared` / `Attachments` / `Folders` / `All`; `New` menu; rows show title,
diff --git a/infra/stacks/opensearch/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.ts
index b2c15814f6..8af2d2504b 100644
--- a/infra/stacks/opensearch/helpers/constants.ts
+++ b/infra/stacks/opensearch/helpers/constants.ts
@@ -2,6 +2,7 @@
// Aliases are stable; underlying physical indices behind them can be swapped
// during a reindex via the OpenSearch _aliases API.
export const CHANNELS_ALIAS = 'channels';
+export const AGENT_SESSIONS_ALIAS = 'agent_sessions';
export const CHATS_ALIAS = 'chats';
export const DOCUMENTS_ALIAS = 'documents';
export const EMAILS_ALIAS = 'emails';
@@ -12,6 +13,7 @@ export const CALENDAR_EVENTS_ALIAS = 'calendar_events';
// Underlying physical indices (versioned). Bump the suffix to roll a new
// version, then swap the alias atomically.
export const CHANNELS_INDEX = 'channels_v2';
+export const AGENT_SESSIONS_INDEX = 'agent_sessions_v1';
export const CHATS_INDEX = 'chats_v2';
export const DOCUMENTS_INDEX = 'documents_v2';
export const EMAILS_INDEX = 'emails_v2';
@@ -21,6 +23,7 @@ export const CALENDAR_EVENTS_INDEX = 'calendar_events_v1';
export const ALIAS_TO_INDEX: Record<string, string> = {
[CHANNELS_ALIAS]: CHANNELS_INDEX,
+ [AGENT_SESSIONS_ALIAS]: AGENT_SESSIONS_INDEX,
[CHATS_ALIAS]: CHATS_INDEX,
[DOCUMENTS_ALIAS]: DOCUMENTS_INDEX,
[EMAILS_ALIAS]: EMAILS_INDEX,
diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts
index 788788045e..d92bd98453 100644
--- a/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts
+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.test.ts
@@ -227,3 +227,25 @@ describe('selectIndexSpecs', () => {
expect(selectIndexSpecs(INDEX_SPECS, 'nope')).toEqual([]);
});
});
+
+test('agent sessions use a parent-child folded-message mapping', () => {
+ const spec = INDEX_SPECS.find(
+ ({ aliasName }) => aliasName === 'agent_sessions'
+ );
+
+ expect(spec?.indexName).toBe('agent_sessions_v1');
+ expect(spec?.body).toMatchObject({
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ agent_session_id: { type: 'keyword' },
+ entity_id: { type: 'alias', path: 'agent_session_id' },
+ content: { type: 'text', analyzer: 'standard' },
+ agent_session_relation: {
+ type: 'join',
+ relations: { agent_session: 'message' },
+ },
+ },
+ },
+ });
+});
diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
index a76d70ff58..647c45a32f 100644
--- a/infra/stacks/opensearch/helpers/scripts/create_indices.ts
+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts
@@ -1,6 +1,8 @@
import type { Client } from '@opensearch-project/opensearch';
import { client } from '../client';
import {
+ AGENT_SESSIONS_ALIAS,
+ AGENT_SESSIONS_INDEX,
CALENDAR_EVENTS_ALIAS,
CALENDAR_EVENTS_INDEX,
CALL_RECORDS_ALIAS,
@@ -905,6 +907,63 @@ const EMAIL_BODY = {
const CHATS_RELATION_PARENT = 'chat';
const CHATS_RELATION_CHILD = 'message';
+const AGENT_SESSIONS_RELATION_PARENT = 'agent_session';
+const AGENT_SESSIONS_RELATION_CHILD = 'message';
+
+const AGENT_SESSIONS_V1_BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ ...SLOWLOG_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ // Present on both the parent and every child so a session can always be
+ // reconciled or removed with one reliable query.
+ agent_session_id: { type: 'keyword' },
+ // Unified search sorts/collapses by entity_id; preserve existing projections.
+ entity_id: { type: 'alias', path: 'agent_session_id' },
+ projection_generation: { type: 'keyword' },
+ // Parent-only metadata.
+ name: {
+ type: 'text',
+ fields: { keyword: { type: 'keyword', ignore_above: 128 } },
+ },
+ owner_id: { type: 'keyword', index: true, doc_values: true },
+ bot_id: { type: 'keyword', index: true, doc_values: true },
+ thread_id: { type: 'keyword', index: true, doc_values: true },
+ originating_message_id: {
+ type: 'keyword',
+ index: true,
+ doc_values: true,
+ },
+ created_at_millis: {
+ type: 'date',
+ format: 'epoch_millis',
+ index: false,
+ doc_values: true,
+ },
+ updated_at_millis: {
+ type: 'date',
+ format: 'epoch_millis',
+ index: false,
+ doc_values: true,
+ },
+ // Child-only folded-message fields.
+ message_turn: { type: 'integer', index: false, doc_values: true },
+ author: { type: 'keyword', index: false, doc_values: true },
+ author_user_id: { type: 'keyword', index: false, doc_values: true },
+ content: { type: 'text', analyzer: 'standard' },
+ agent_session_relation: {
+ type: 'join',
+ relations: {
+ [AGENT_SESSIONS_RELATION_PARENT]: AGENT_SESSIONS_RELATION_CHILD,
+ },
+ },
+ },
+ },
+};
const CHATS_V2_BODY = {
settings: {
...SHARD_SETTINGS,
@@ -1063,6 +1122,11 @@ const CALL_RECORDS_V2_BODY = {
* as CHATS_V2_BODY / CALL_RECORDS_V2_BODY).
*/
export const INDEX_SPECS: CreateIndexArgs[] = [
+ {
+ indexName: AGENT_SESSIONS_INDEX,
+ aliasName: AGENT_SESSIONS_ALIAS,
+ body: AGENT_SESSIONS_V1_BODY,
+ },
{
indexName: DOCUMENTS_INDEX,
aliasName: DOCUMENTS_ALIAS,
diff --git a/packages/sdk/generated/search/index.ts b/packages/sdk/generated/search/index.ts
index 3626ce930f..16966b0303 100644
--- a/packages/sdk/generated/search/index.ts
+++ b/packages/sdk/generated/search/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AgentSessionFilters, CalendarEventFilters, CalendarEventMetadata, CalendarEventOrganizer, CalendarEventSearchOccurrence, CalendarEventSearchResponseItem, CalendarEventSearchResponseItemWithMetadata, CalendarEventSearchResult, CalendarEventSearchTime, CallFilters, CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata, CallRecordSearchResult, CallStatus, ChannelFilters, ChannelMessageSearchResponseItem, ChannelMetadata, ChannelNameSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult, ChannelSortTimestamp, ChannelThreadFilters, ChatFilters, ChatMessageSearchResult, ChatMetadata, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem, ChatSearchResponseItemWithMetadata, ClientOptions, CrmCompanyFilters, CrmCompanySearchDomain, CrmCompanySearchResponseItem, DataType, DocumentFilters, DocumentMetadata, DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult, DocumentSubType, EmailFilters, EmailSearchParticipant, EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem, EmailSearchResponseItemWithMetadata, EmailSearchResult, EmptyResponse, EntityFilters, EntityReference, EntityType, ErrorResponse, FileType, ForeignEntityFilters, MatchType, NotificationFilters, NotificationState, ProjectFilters, ProjectMetadata, ProjectSearchMetadata, ProjectSearchRequest, ProjectSearchResponseItem, ProjectSearchResponseItemWithMetadata, ProjectSearchResult, PropertyDefinition, PropertyFilter, PropertyOwner, PropertyValue, ReminderFilters, SearchHighlight, SearchOn, SearchResponse, SharedEmailFilter, SimpleCalendarEventSearchResponseBaseItemHumanReadableTimestamp, SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp, SimpleChannelSearchReponseBaseItem, SimpleChannelSearchReponseBaseItemHumanReadableTimestamp, SimpleChannelSearchResponse, SimpleChatSearchResponse, SimpleChatSearchResponseBaseItem, SimpleChatSearchResponseBaseItemHumanReadableTimestamp, SimpleDocumentSearchResponse, SimpleDocumentSearchResponseBaseItem, SimpleDocumentSearchResponseBaseItemHumanReadableTimestamp, SimpleEmailSearchResponse, SimpleEmailSearchResponseBaseItem, SimpleEmailSearchResponseBaseItemHumanReadableTimestamp, SimpleProjectSearchResponse, SimpleProjectSearchResponseBaseItem, SimpleProjectSearchResponseBaseItemHumanReadableTimestamp, SimpleUnifiedSearchBaseResponse, SimpleUnifiedSearchData, SimpleUnifiedSearchError, SimpleUnifiedSearchErrors, SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseBaseItem, SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp, SimpleUnifiedSearchResponses, SoupProperty, TagFilterMode, TaskFilters, UnifiedSearchData, UnifiedSearchError, UnifiedSearchErrors, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponse2, UnifiedSearchResponseItem, UnifiedSearchResponses } from './types.gen';
+export type { AgentSessionAuthor, AgentSessionFilters, AgentSessionSearchResponseItem, AgentSessionSearchResult, CalendarEventFilters, CalendarEventMetadata, CalendarEventOrganizer, CalendarEventSearchOccurrence, CalendarEventSearchResponseItem, CalendarEventSearchResponseItemWithMetadata, CalendarEventSearchResult, CalendarEventSearchTime, CallFilters, CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata, CallRecordSearchResult, CallStatus, ChannelFilters, ChannelMessageSearchResponseItem, ChannelMetadata, ChannelNameSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult, ChannelSortTimestamp, ChannelThreadFilters, ChatFilters, ChatMessageSearchResult, ChatMetadata, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem, ChatSearchResponseItemWithMetadata, ClientOptions, CrmCompanyFilters, CrmCompanySearchDomain, CrmCompanySearchResponseItem, DataType, DocumentFilters, DocumentMetadata, DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult, DocumentSubType, EmailFilters, EmailSearchParticipant, EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem, EmailSearchResponseItemWithMetadata, EmailSearchResult, EmptyResponse, EntityFilters, EntityReference, EntityType, ErrorResponse, FileType, ForeignEntityFilters, Highlight, MatchType, NotificationFilters, NotificationState, ProjectFilters, ProjectMetadata, ProjectSearchMetadata, ProjectSearchRequest, ProjectSearchResponseItem, ProjectSearchResponseItemWithMetadata, ProjectSearchResult, PropertyDefinition, PropertyFilter, PropertyOwner, PropertyValue, ReminderFilters, SearchGotoAgentSession, SearchGotoCallRecord, SearchGotoChannel, SearchGotoChat, SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHighlight, SearchOn, SearchResponse, SharedEmailFilter, SimpleCalendarEventSearchResponseBaseItemHumanReadableTimestamp, SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp, SimpleChannelSearchReponseBaseItem, SimpleChannelSearchReponseBaseItemHumanReadableTimestamp, SimpleChannelSearchResponse, SimpleChatSearchResponse, SimpleChatSearchResponseBaseItem, SimpleChatSearchResponseBaseItemHumanReadableTimestamp, SimpleDocumentSearchResponse, SimpleDocumentSearchResponseBaseItem, SimpleDocumentSearchResponseBaseItemHumanReadableTimestamp, SimpleEmailSearchResponse, SimpleEmailSearchResponseBaseItem, SimpleEmailSearchResponseBaseItemHumanReadableTimestamp, SimpleProjectSearchResponse, SimpleProjectSearchResponseBaseItem, SimpleProjectSearchResponseBaseItemHumanReadableTimestamp, SimpleSearchResponse, SimpleSearchResponseItem, SimpleUnifiedSearchBaseResponse, SimpleUnifiedSearchData, SimpleUnifiedSearchError, SimpleUnifiedSearchErrors, SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseBaseItem, SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp, SimpleUnifiedSearchResponses, SoupProperty, TagFilterMode, TaskFilters, UnifiedSearchData, UnifiedSearchError, UnifiedSearchErrors, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponse2, UnifiedSearchResponseItem, UnifiedSearchResponses } from './types.gen';
diff --git a/packages/sdk/generated/search/types.gen.ts b/packages/sdk/generated/search/types.gen.ts
index 5c7d474702..41bdb8f6a5 100644
--- a/packages/sdk/generated/search/types.gen.ts
+++ b/packages/sdk/generated/search/types.gen.ts
@@ -4,6 +4,11 @@ export type ClientOptions = {
baseUrl: `${string}://${string}` | (string & {});
};
+/**
+ * Side of a folded conversation.
+ */
+export type AgentSessionAuthor = 'user' | 'agent';
+
/**
* Filters for agent sessions.
*/
@@ -25,6 +30,55 @@ export type AgentSessionFilters = {
owners?: Array<string>;
};
+/**
+ * One accessible agent session, grouped with its matching folded messages.
+ */
+export type AgentSessionSearchResponseItem = {
+ /**
+ * Name and folded-message matches.
+ */
+ agent_session_search_results: Array<AgentSessionSearchResult>;
+ /**
+ * Agent persona ID.
+ */
+ bot_id: string;
+ /**
+ * Session creation time.
+ */
+ created_at: string;
+ /**
+ * Session ID.
+ */
+ id: string;
+ /**
+ * Current persisted name.
+ */
+ name: string;
+ /**
+ * Session owner.
+ */
+ owner_id: string;
+ /**
+ * Current persisted modification time.
+ */
+ updated_at: string;
+};
+
+/**
+ * A name match or one matching folded message.
+ */
+export type AgentSessionSearchResult = {
+ goto?: null | SearchGotoAgentSession;
+ /**
+ * Matched name/content fragments.
+ */
+ highlight: SearchHighlight;
+ /**
+ * Search score.
+ */
+ score?: number | null;
+};
+
/**
* Filters for canonical calendar-event entities.
*/
@@ -1361,6 +1415,21 @@ export type ForeignEntityFilters = {
notification_filters?: NotificationFilters;
};
+/**
+ * The search service version of a highlight
+ */
+export type Highlight = {
+ /**
+ * If the match was on the entity content, this will provide a list of highlights
+ * for each content match
+ */
+ content?: Array<string>;
+ /**
+ * If the match was on the entity name, this will be present with that highlight
+ */
+ name?: string | null;
+};
+
export type MatchType = 'exact' | 'partial' | 'regexp' | 'query';
/**
@@ -1648,6 +1717,79 @@ export type ReminderFilters = {
include?: boolean;
};
+/**
+ * Stable navigation target from the fold, independent of raw ACP log IDs.
+ */
+export type SearchGotoAgentSession = {
+ /**
+ * Author within the turn.
+ */
+ author: AgentSessionAuthor;
+ /**
+ * Fold-assigned turn.
+ */
+ message_turn: number;
+};
+
+export type SearchGotoCallRecord = {
+ channel_id: string;
+ ended_at?: string | null;
+ participant_ids: Array<string>;
+ sequence_num: number;
+ speaker_id: string;
+ started_at: string;
+ transcript_id: string;
+};
+
+export type SearchGotoChannel = {
+ /**
+ * The channel message id
+ */
+ channel_message_id: string;
+};
+
+export type SearchGotoChat = {
+ /**
+ * The chat message id
+ */
+ chat_message_id: string;
+ /**
+ * The role of the chat message
+ */
+ role: string;
+};
+
+/**
+ * The search service version of a goto
+ */
+export type SearchGotoContent = SearchGotoAgentSession | SearchGotoDocument | SearchGotoChat | SearchGotoEmail | SearchGotoChannel | SearchGotoCallRecord;
+
+export type SearchGotoDocument = {
+ /**
+ * The node id of the document
+ * This can be a stringified page number 0-indexed for pdf/docx files,
+ * or it can be a unique id that is used in lexical for markdown files.
+ */
+ node_id: string;
+ /**
+ * The raw content of the document
+ */
+ raw_content?: string | null;
+};
+
+export type SearchGotoEmail = {
+ bcc: Array<string>;
+ cc: Array<string>;
+ /**
+ * The email message id
+ */
+ email_message_id: string;
+ labels: Array<string>;
+ recipients: Array<string>;
+ sender: string;
+ sent_at?: string | null;
+};
+
export type SearchHighlight = {
/**
* The highlight match on the bcc (email only)
@@ -2168,6 +2310,27 @@ export type SimpleProjectSearchResponseBaseItemHumanReadableTimestamp = {
user_id: string;
};
+/**
+ * The response for simple search
+ */
+export type SimpleSearchResponse = {
+ results: Array<SimpleSearchResponseItem>;
+};
+
+/**
+ * Simple response item to mimic what we get back from opensearch
+ */
+export type SimpleSearchResponseItem = {
+ /**
+ * ID of the chat, channel, email, or document
+ */
+ entity_id: string;
+ entity_type: string;
+ goto?: null | SearchGotoContent;
+ highlight: Highlight;
+ score?: number | null;
+};
+
export type SimpleUnifiedSearchBaseResponse = {
results: Array<SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp>;
};
@@ -2294,6 +2457,8 @@ export type UnifiedSearchResponseItem = (DocumentSearchResponseItemWithMetadata
type: 'company';
}) | (CalendarEventSearchResponseItemWithMetadata & {
type: 'calendarEvent';
+}) | (AgentSessionSearchResponseItem & {
+ type: 'agentSession';
});
export type UnifiedSearchData = {
@@ -2351,7 +2516,7 @@ export type SimpleUnifiedSearchErrors = {
export type SimpleUnifiedSearchError = SimpleUnifiedSearchErrors[keyof SimpleUnifiedSearchErrors];
export type SimpleUnifiedSearchResponses = {
- 200: SimpleUnifiedSearchBaseResponse;
+ 200: SimpleSearchResponse;
};
export type SimpleUnifiedSearchResponse = SimpleUnifiedSearchResponses[keyof SimpleUnifiedSearchResponses];
diff --git a/packages/sdk/specs/search.json b/packages/sdk/specs/search.json
index 815a639a14..1545b6a3a4 100644
--- a/packages/sdk/specs/search.json
+++ b/packages/sdk/specs/search.json
@@ -132,7 +132,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/SimpleUnifiedSearchBaseResponse"
+ "$ref": "#/components/schemas/SimpleSearchResponse"
}
}
}
@@ -173,6 +173,11 @@
},
"components": {
"schemas": {
+ "AgentSessionAuthor": {
+ "type": "string",
+ "description": "Side of a folded conversation.",
+ "enum": ["user", "agent"]
+ },
"AgentSessionFilters": {
"type": "object",
"description": "Filters for agent sessions.",
@@ -197,6 +202,83 @@
}
}
},
+ "AgentSessionSearchResponseItem": {
+ "type": "object",
+ "description": "One accessible agent session, grouped with its matching folded messages.",
+ "required": [
+ "id",
+ "name",
+ "owner_id",
+ "bot_id",
+ "created_at",
+ "updated_at",
+ "agent_session_search_results"
+ ],
+ "properties": {
+ "agent_session_search_results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentSessionSearchResult"
+ },
+ "description": "Name and folded-message matches."
+ },
+ "bot_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Agent persona ID."
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Session creation time."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session ID."
+ },
+ "name": {
+ "type": "string",
+ "description": "Current persisted name."
+ },
+ "owner_id": {
+ "type": "string",
+ "description": "Session owner."
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Current persisted modification time."
+ }
+ }
+ },
+ "AgentSessionSearchResult": {
+ "type": "object",
+ "description": "A name match or one matching folded message.",
+ "required": ["highlight"],
+ "properties": {
+ "goto": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoAgentSession",
+ "description": "Absent for a name-only match."
+ }
+ ]
+ },
+ "highlight": {
+ "$ref": "#/components/schemas/SearchHighlight",
+ "description": "Matched name/content fragments."
+ },
+ "score": {
+ "type": ["number", "null"],
+ "format": "double",
+ "description": "Search score."
+ }
+ }
+ },
"CalendarEventFilters": {
"type": "object",
"description": "Filters for canonical calendar-event entities.",
@@ -2622,6 +2704,23 @@
}
}
},
+ "Highlight": {
+ "type": "object",
+ "description": "The search service version of a highlight",
+ "properties": {
+ "content": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "If the match was on the entity content, this will provide a list of highlights\nfor each content match"
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "If the match was on the entity name, this will be present with that highlight"
+ }
+ }
+ },
"MatchType": {
"type": "string",
"enum": ["exact", "partial", "regexp", "query"]
@@ -3149,6 +3248,177 @@
}
}
},
+ "SearchGotoAgentSession": {
+ "type": "object",
+ "description": "Stable navigation target from the fold, independent of raw ACP log IDs.",
+ "required": ["message_turn", "author"],
+ "properties": {
+ "author": {
+ "$ref": "#/components/schemas/AgentSessionAuthor",
+ "description": "Author within the turn."
+ },
+ "message_turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Fold-assigned turn.",
+ "minimum": 0
+ }
+ }
+ },
+ "SearchGotoCallRecord": {
+ "type": "object",
+ "required": [
+ "channel_id",
+ "transcript_id",
+ "speaker_id",
+ "sequence_num",
+ "started_at",
+ "participant_ids"
+ ],
+ "properties": {
+ "channel_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "ended_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "participant_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sequence_num": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "speaker_id": {
+ "type": "string"
+ },
+ "started_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "transcript_id": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ },
+ "SearchGotoChannel": {
+ "type": "object",
+ "required": ["channel_message_id"],
+ "properties": {
+ "channel_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The channel message id"
+ }
+ }
+ },
+ "SearchGotoChat": {
+ "type": "object",
+ "required": ["chat_message_id", "role"],
+ "properties": {
+ "chat_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The chat message id"
+ },
+ "role": {
+ "type": "string",
+ "description": "The role of the chat message"
+ }
+ }
+ },
+ "SearchGotoContent": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SearchGotoAgentSession"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoDocument"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoChat"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoEmail"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoChannel"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoCallRecord"
+ }
+ ],
+ "description": "The search service version of a goto"
+ },
+ "SearchGotoDocument": {
+ "type": "object",
+ "required": ["node_id"],
+ "properties": {
+ "node_id": {
+ "type": "string",
+ "description": "The node id of the document\nThis can be a stringified page number 0-indexed for pdf/docx files,\nor it can be a unique id that is used in lexical for markdown files."
+ },
+ "raw_content": {
+ "type": ["string", "null"],
+ "description": "The raw content of the document"
+ }
+ }
+ },
+ "SearchGotoEmail": {
+ "type": "object",
+ "required": [
+ "email_message_id",
+ "bcc",
+ "cc",
+ "labels",
+ "sender",
+ "recipients"
+ ],
+ "properties": {
+ "bcc": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "cc": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "email_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The email message id"
+ },
+ "labels": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "recipients": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "sender": {
+ "type": "string"
+ },
+ "sent_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ }
+ }
+ },
"SearchHighlight": {
"type": "object",
"properties": {
@@ -4023,6 +4293,51 @@
}
}
},
+ "SimpleSearchResponse": {
+ "type": "object",
+ "description": "The response for simple search",
+ "required": ["results"],
+ "properties": {
+ "results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SimpleSearchResponseItem"
+ }
+ }
+ }
+ },
+ "SimpleSearchResponseItem": {
+ "type": "object",
+ "description": "Simple response item to mimic what we get back from opensearch",
+ "required": ["entity_id", "entity_type", "highlight"],
+ "properties": {
+ "entity_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "ID of the chat, channel, email, or document"
+ },
+ "entity_type": {
+ "type": "string"
+ },
+ "goto": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/SearchGotoContent"
+ }
+ ]
+ },
+ "highlight": {
+ "$ref": "#/components/schemas/Highlight"
+ },
+ "score": {
+ "type": ["number", "null"],
+ "format": "double"
+ }
+ }
+ },
"SimpleUnifiedSearchBaseResponse": {
"type": "object",
"required": ["results"],
@@ -4523,6 +4838,23 @@
}
}
]
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentSessionSearchResponseItem"
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["agentSession"]
+ }
+ }
+ }
+ ]
}
]
}
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index 0057cfb512..14c459c141 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -27,6 +27,7 @@ local_auth = ["macro_authorization/local_auth"]
location_check = []
[dependencies]
+agent_session = { path = "../../crates/agent_session", features = ["outbound"] }
activity = { path = "../../crates/activity" }
ai_tools = { path = "../../crates/ai_tools" }
ai_usage = { path = "../../crates/ai_usage" }
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 7b651d76ae..5e2841f610 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -63,6 +63,10 @@ use user_api_key::{
outbound::pg_user_api_keys_repo::PgUserApiKeysRepo,
};
+use agent_session::{
+ domain::search::{AgentSessionSearchMetadataService, AgentSessionSearchMetadataServiceImpl},
+ outbound::postgres::PgAgentSessionRepo,
+};
use collab_surface::{
domain::service::CollabSurfaceServiceImpl, inbound::axum_router::CollabSurfaceRouterState,
outbound::pg_collab_surface_repo::PgCollabSurfaceRepo,
@@ -610,6 +614,10 @@ impl From<&ApiContext> for SearchHandlerState {
opensearch_client: ctx.opensearch_client.clone(),
entity_access_service: ctx.entity_access_service.clone(),
authorization_state: ctx.authorization_state.clone(),
+ agent_session_search_metadata: Arc::new(AgentSessionSearchMetadataServiceImpl::new(
+ PgAgentSessionRepo::new(ctx.db.clone()),
+ ))
+ as Arc<dyn AgentSessionSearchMetadataService>,
calendar_search_enabled: ctx.config.calendar_search_enabled,
}
}