Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSearch.ts

168 lines5.5 KB

1import {
2 IsoDateTime,
3 OrchestrationThreadSearchSource,
4 type OrchestrationSearchThreadsInput,
5 type OrchestrationSearchThreadsResult,
6 ProjectId,
7 ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13import * as SqlClient from "effect/sql/SqlClient";
14import * as SqlSchema from "effect/sql/SqlSchema";
15​
16/** Carries no query text: search input is user content. */
17export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
18 "ThreadSearchError",
19 {
20 operation: Schema.Literals(["query", "decode"]),
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Thread search ${this.operation} failed.`;
26 }
28​
29const SearchRequest = Schema.Struct({ pattern: Schema.String, limit: Schema.Int });
30const SearchRow = Schema.Struct({
31 threadId: ThreadId,
32 projectId: ProjectId,
33 source: OrchestrationThreadSearchSource,
34 matchText: Schema.String,
35 messageCreatedAt: Schema.NullOr(IsoDateTime),
36});
37​
38function escapeLikePattern(value: string): string {
39 return value.replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_");
41​
42function foldAsciiCase(value: string): string {
43 return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
45​
46/** At most 240 characters, centred near the first match. */
47function buildSearchSnippet(text: string, query: string): string {
48 const normalizedText = text.replace(/\s+/g, " ").trim();
49 if (normalizedText.length <= 240) {
50 return normalizedText;
51 }
52 const normalizedQuery = foldAsciiCase(query.replace(/\s+/g, " ").trim());
53 const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);
54 const bodyLength = 236;
55 const idealStart = Math.max(0, matchIndex - 72);
56 const start = Math.min(idealStart, normalizedText.length - bodyLength);
57 const end = Math.min(normalizedText.length, start + bodyLength);
58 return `${start > 0 ? "…" : ""}${normalizedText.slice(start, end)}${
59 end < normalizedText.length ? "…" : ""
60 }`;
62​
63/**
64 * Searches the finished user and assistant messages of active V2 threads in
65 * active projects. Legacy V1 transcripts that have not been imported yet are
66 * not searched.
67 */
68export class ThreadSearch extends Context.Service<
69 ThreadSearch,
70 {
71 readonly search: (
72 input: OrchestrationSearchThreadsInput,
73 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
74 }
75>()("t3/orchestration-v2/ThreadSearch") {}
76​
77/** @public Service construction is part of the canonical Effect module API. */
78export const make = Effect.gen(function* () {
79 const sql = yield* SqlClient.SqlClient;
80​
81 // One best match per thread: user messages outrank assistant ones, then the
82 // newest message wins. Threads order by match kind, then recency.
83 const searchRows = SqlSchema.findAll({
84 Request: SearchRequest,
85 Result: SearchRow,
86 execute: ({ pattern, limit }) => sql`
87 WITH candidate AS (
88 SELECT
89 threads.thread_id,
90 threads.project_id,
91 messages.role,
92 json_extract(messages.payload_json, '$.text') AS match_text,
93 messages.created_at AS message_created_at,
94 messages.message_id,
95 threads.updated_at AS thread_updated_at
96 FROM orchestration_v2_projection_messages AS messages
97 INNER JOIN orchestration_v2_projection_threads AS threads
98 ON threads.thread_id = messages.thread_id
99 INNER JOIN projection_projects AS projects
100 ON projects.project_id = threads.project_id
101 WHERE threads.deleted_at IS NULL
102 AND threads.archived_at IS NULL
103 AND projects.deleted_at IS NULL
104 AND messages.streaming = 0
105 AND messages.role IN ('user', 'assistant')
106 AND json_extract(messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!'
107 ),
108 ranked AS (
109 SELECT
110 thread_id,
111 project_id,
112 role AS source,
113 match_text,
114 message_created_at,
115 CASE role WHEN 'user' THEN 0 ELSE 1 END AS match_rank,
116 thread_updated_at,
117 ROW_NUMBER() OVER (
118 PARTITION BY thread_id
119 ORDER BY
120 CASE role WHEN 'user' THEN 0 ELSE 1 END ASC,
121 message_created_at DESC,
122 message_id ASC
123 ) AS thread_match_rank
124 FROM candidate
125 )
126 SELECT
127 thread_id AS "threadId",
128 project_id AS "projectId",
129 source,
130 match_text AS "matchText",
131 message_created_at AS "messageCreatedAt"
132 FROM ranked
133 WHERE thread_match_rank = 1
134 ORDER BY match_rank ASC, thread_updated_at DESC, thread_id ASC
135 LIMIT ${limit}
136 `,
137 });
138​
139 const search: ThreadSearch["Service"]["search"] = Effect.fn("ThreadSearch.search")(
140 function* (input) {
141 const rows = yield* searchRows({
142 pattern: `%${escapeLikePattern(input.query)}%`,
143 limit: input.limit ?? 50,
144 }).pipe(
145 Effect.mapError(
146 (cause) =>
147 new ThreadSearchError({
148 operation: Schema.isSchemaError(cause) ? "decode" : "query",
149 cause,
150 }),
151 ),
152 );
153 return {
154 matches: rows.map((row) => ({
155 threadId: row.threadId,
156 projectId: row.projectId,
157 source: row.source,
158 snippet: buildSearchSnippet(row.matchText, input.query),
159 messageCreatedAt: row.messageCreatedAt,
160 })),
161 };
162 },
163 );
164​
165 return ThreadSearch.of({ search });
166});
167​
168export const layer = Layer.effect(ThreadSearch, make);