Files
t3code/apps/server/src/orchestration-v2/ThreadSearch.ts
T
+36 de34391427 feat(orchestrator): introduce new orchestrator (#2829)
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Bilal Bakr <[email protected]>
Co-authored-by: shivam <[email protected]>
Co-authored-by: Vitalii Yehorov <[email protected]>
Co-authored-by: Jake Leventhal <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Alex Southwell <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Nicholas Wasmiller <[email protected]>
Co-authored-by: PB <[email protected]>
Co-authored-by: Exotic <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Theo Browne <[email protected]>
Co-authored-by: Gabriel De Andrade <[email protected]>
Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: scratchyone <[email protected]>
Co-authored-by: Dominic Roy <[email protected]>
Co-authored-by: chukfinley <[email protected]>
Co-authored-by: Primož Ajdišek <[email protected]>
Co-authored-by: benthecarman <[email protected]>
Co-authored-by: NaveDanan <[email protected]>
Co-authored-by: aaditagrawal <[email protected]>
Co-authored-by: Aditya Garud <[email protected]>
Co-authored-by: Nick Anisimov <[email protected]>
Co-authored-by: MacKinley Smith <[email protected]>
Co-authored-by: Yordis Prieto <[email protected]>
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: AKolenda <[email protected]>
Co-authored-by: Guillermo Casanova <[email protected]>
Co-authored-by: Otavio Salvador <[email protected]>
Co-authored-by: Shirish Pothi <[email protected]>
Co-authored-by: Ishaan Kothari <[email protected]>
Co-authored-by: Bob Fowler <[email protected]>
Co-authored-by: Anton Bezdenezhnykh <[email protected]>
Co-authored-by: ValeraZSD <[email protected]>
Co-authored-by: Ephraim <[email protected]>
Co-authored-by: Ryan Ilano <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: maco <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Tristan Knight <[email protected]>
Co-authored-by: PR Batch Tester <[email protected]>
Co-authored-by: oliver <[email protected]>
Co-authored-by: kamkm <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-10-02 12:22:22 -07:00

169 lines
5.6 KiB
TypeScript

import {
IsoDateTime,
OrchestrationThreadSearchSource,
type OrchestrationSearchThreadsInput,
type OrchestrationSearchThreadsResult,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
/** Carries no query text: search input is user content. */
export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
"ThreadSearchError",
{
operation: Schema.Literals(["query", "decode"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Thread search ${this.operation} failed.`;
}
}
const SearchRequest = Schema.Struct({ pattern: Schema.String, limit: Schema.Int });
const SearchRow = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
source: OrchestrationThreadSearchSource,
matchText: Schema.String,
messageCreatedAt: Schema.NullOr(IsoDateTime),
});
function escapeLikePattern(value: string): string {
return value.replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_");
}
function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
/** At most 240 characters, centred near the first match. */
function buildSearchSnippet(text: string, query: string): string {
const normalizedText = text.replace(/\s+/g, " ").trim();
if (normalizedText.length <= 240) {
return normalizedText;
}
const normalizedQuery = foldAsciiCase(query.replace(/\s+/g, " ").trim());
const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);
const bodyLength = 236;
const idealStart = Math.max(0, matchIndex - 72);
const start = Math.min(idealStart, normalizedText.length - bodyLength);
const end = Math.min(normalizedText.length, start + bodyLength);
return `${start > 0 ? "…" : ""}${normalizedText.slice(start, end)}${
end < normalizedText.length ? "…" : ""
}`;
}
/**
* Searches the finished user and assistant messages of active V2 threads in
* active projects. Legacy V1 transcripts that have not been imported yet are
* not searched.
*/
export class ThreadSearch extends Context.Service<
ThreadSearch,
{
readonly search: (
input: OrchestrationSearchThreadsInput,
) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
}
>()("t3/orchestration-v2/ThreadSearch") {}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// One best match per thread: user messages outrank assistant ones, then the
// newest message wins. Threads order by match kind, then recency.
const searchRows = SqlSchema.findAll({
Request: SearchRequest,
Result: SearchRow,
execute: ({ pattern, limit }) => sql`
WITH candidate AS (
SELECT
threads.thread_id,
threads.project_id,
messages.role,
json_extract(messages.payload_json, '$.text') AS match_text,
messages.created_at AS message_created_at,
messages.message_id,
threads.updated_at AS thread_updated_at
FROM orchestration_v2_projection_messages AS messages
INNER JOIN orchestration_v2_projection_threads AS threads
ON threads.thread_id = messages.thread_id
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND projects.deleted_at IS NULL
AND messages.streaming = 0
AND messages.role IN ('user', 'assistant')
AND json_extract(messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!'
),
ranked AS (
SELECT
thread_id,
project_id,
role AS source,
match_text,
message_created_at,
CASE role WHEN 'user' THEN 0 ELSE 1 END AS match_rank,
thread_updated_at,
ROW_NUMBER() OVER (
PARTITION BY thread_id
ORDER BY
CASE role WHEN 'user' THEN 0 ELSE 1 END ASC,
message_created_at DESC,
message_id ASC
) AS thread_match_rank
FROM candidate
)
SELECT
thread_id AS "threadId",
project_id AS "projectId",
source,
match_text AS "matchText",
message_created_at AS "messageCreatedAt"
FROM ranked
WHERE thread_match_rank = 1
ORDER BY match_rank ASC, thread_updated_at DESC, thread_id ASC
LIMIT ${limit}
`,
});
const search: ThreadSearch["Service"]["search"] = Effect.fn("ThreadSearch.search")(
function* (input) {
const rows = yield* searchRows({
pattern: `%${escapeLikePattern(input.query)}%`,
limit: input.limit ?? 50,
}).pipe(
Effect.mapError(
(cause) =>
new ThreadSearchError({
operation: Schema.isSchemaError(cause) ? "decode" : "query",
cause,
}),
),
);
return {
matches: rows.map((row) => ({
threadId: row.threadId,
projectId: row.projectId,
source: row.source,
snippet: buildSearchSnippet(row.matchText, input.query),
messageCreatedAt: row.messageCreatedAt,
})),
};
},
);
return ThreadSearch.of({ search });
});
export const layer = Layer.effect(ThreadSearch, make);