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

ThreadFind.ts

424 lines16.6 KB

1import {
2 OrchestrationV2TurnItemJson,
3 type OrchestrationV2ProjectedTurnItem,
4 OrchestrationV2SearchThreadInput,
5 type OrchestrationV2SearchThreadResult,
6 type OrchestrationV2TurnItem,
7 ThreadId,
8 TurnItemId,
9} from "@t3tools/contracts";
10import { searchableMessageSegments, searchablePlanSegments } from "@t3tools/shared/threadFindText";
11import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
12import * as Cache from "effect/Cache";
13import * as Data from "effect/Data";
14import * as Effect from "effect/Effect";
15import * as RcRef from "effect/RcRef";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
19import * as SqlClient from "effect/sql/SqlClient";
20import {
21 ProjectionStoreReadError,
22 ProjectionStoreThreadNotFoundError,
23 type ProjectionStoreV2Error,
24} from "./ProjectionStore.ts";
25​
26interface FindRow {
27 readonly position: number;
28 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
29 readonly sourceThreadId: ThreadId;
30 readonly sourceItemId: TurnItemId;
32interface FindPayload extends FindRow {
33 readonly payload: string;
34 readonly entryId: string;
35 readonly runId: OrchestrationV2TurnItem["runId"];
36 readonly type: OrchestrationV2TurnItem["type"];
38interface FindDocument extends FindRow {
39 readonly entryId: string;
40 readonly runId: OrchestrationV2TurnItem["runId"];
41 readonly count: number;
43type CompletedScans = Map<
44 string,
45 {
46 sequence: number;
47 documents: readonly FindDocument[];
48 sourceThreadIds: readonly ThreadId[];
49 }
50>;
51class TextKey extends Data.Class<{
52 text: string;
53 role: "user" | "assistant" | "plan";
54 streaming: boolean;
55 hasContext: boolean;
56 cwd: string | undefined;
57 skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;
58}> {}
59​
60function textKey(
61 item: OrchestrationV2TurnItem,
62 cwd: string | undefined,
63 skills: TextKey["skills"],
64) {
65 return new TextKey({
66 text:
67 item.type === "proposed_plan"
68 ? item.markdown
69 : item.type === "user_message" || item.type === "assistant_message"
70 ? item.text
71 : "",
72 role:
73 item.type === "proposed_plan" ? "plan" : item.type === "user_message" ? "user" : "assistant",
74 streaming: item.type === "assistant_message" && item.streaming,
75 hasContext: item.type === "user_message" && item.context !== undefined,
76 cwd,
77 skills,
78 });
80​
81function parseText(key: TextKey): readonly string[] {
82 return key.role === "plan"
83 ? searchablePlanSegments(key.text, key.cwd)
84 : (searchableMessageSegments(
85 {
86 role: key.role,
87 text: key.text,
88 streaming: key.streaming,
89 context: key.hasContext ? { version: 1, records: [] } : undefined,
90 },
91 key.cwd,
92 key.skills,
93 ) ?? []);
95​
96function documentFor(row: OrchestrationV2ProjectedTurnItem, count: number): FindDocument {
97 return {
98 position: row.position,
99 visibility: row.visibility,
100 sourceThreadId: row.sourceThreadId,
101 sourceItemId: row.sourceItemId,
102 entryId:
103 row.item.type === "user_message" || row.item.type === "assistant_message"
104 ? row.item.messageId
105 : row.item.id,
106 runId: row.item.runId,
107 count,
108 };
110​
111function countSegments(segments: readonly string[], query: string) {
112 return segments.reduce((sum, text) => sum + countThreadSearchOccurrences(text, query), 0);
114​
115function selectMatch(
116 documents: readonly FindDocument[],
117 input: Pick<OrchestrationV2SearchThreadInput, "index" | "start" | "offset">,
118) {
119 const totalMatches = documents.reduce((sum, doc) => sum + doc.count, 0);
120 let requestedIndex = input.index ?? 0;
121 if (input.index === undefined && input.start) {
122 const startIndex = documents.findIndex((doc) => doc.entryId === input.start?.entryId);
123 if (startIndex >= 0) {
124 requestedIndex =
125 documents.slice(0, startIndex).reduce((sum, doc) => sum + doc.count, 0) +
126 Math.min(input.start.occurrence, documents[startIndex]!.count);
127 if (requestedIndex >= totalMatches) requestedIndex = 0;
128 }
129 }
130 const activeIndex =
131 input.index === undefined && totalMatches > 0
132 ? (((requestedIndex + (input.offset ?? 0)) % totalMatches) + totalMatches) % totalMatches
133 : Math.min(requestedIndex, Math.max(0, totalMatches - 1));
134 let occurrence = activeIndex;
135 for (const document of documents) {
136 if (occurrence < document.count) return { totalMatches, activeIndex, document, occurrence };
137 occurrence -= document.count;
138 }
139 return { totalMatches, activeIndex, document: null, occurrence: 0 };
141​
142function resultForSelection(
143 selected: ReturnType<typeof selectMatch>,
144 documents: readonly FindDocument[],
145 snapshotSequence: number,
146): OrchestrationV2SearchThreadResult {
147 let startIndex = 0;
148 const entries = documents.flatMap(({ entryId, runId, count }) => {
149 const entry = { entryId, runId, count, startIndex };
150 startIndex += count;
151 return count > 0 ? [entry] : [];
152 });
153 const selectedEntry = entries.findIndex((entry) => entry.entryId === selected.document?.entryId);
154 const navigation =
155 entries.length <= 17
156 ? entries
157 : Array.from(
158 { length: 17 },
159 (_, i) => entries[(selectedEntry + i - 8 + entries.length) % entries.length]!,
160 );
161 return {
162 snapshotSequence,
163 totalMatches: selected.totalMatches,
164 activeIndex: selected.activeIndex,
165 navigation,
166 match:
167 selected.document === null
168 ? null
169 : {
170 entryId: selected.document.entryId,
171 runId: selected.document.runId,
172 occurrence: selected.occurrence,
173 },
174 };
176​
177export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
178 readIndex: (threadId: ThreadId) => Effect.Effect<
179 readonly (Omit<FindRow, "position"> & {
180 readonly item: Pick<OrchestrationV2TurnItem, "type">;
181 })[],
182 ProjectionStoreV2Error
183 >,
184) {
185 const sql = yield* SqlClient.SqlClient;
186 const encodeCacheKey = Schema.encodeEffect(
187 Schema.fromJsonString(
188 Schema.Struct({
189 threadId: ThreadId,
190 cwd: Schema.optional(Schema.String),
191 query: Schema.String,
192 skills: OrchestrationV2SearchThreadInput.fields.skills,
193 }),
194 ),
195 );
196 const encodeThreadIds = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(ThreadId)));
197 const encodeSources = Schema.encodeEffect(
198 Schema.fromJsonString(Schema.Array(Schema.Struct({ threadId: ThreadId, id: TurnItemId }))),
199 );
200 const decodeItem = Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2TurnItemJson));
201 const isSnapshotError = Schema.is(
202 Schema.Union([ProjectionStoreReadError, ProjectionStoreThreadNotFoundError]),
203 );
204 const load = Effect.fn("ThreadFind.load")(function* (
205 threadId: ThreadId,
206 rows: readonly FindRow[],
207 ) {
208 if (rows.length === 0) return [];
209 const sources = yield* encodeSources(
210 rows.map((row) => ({ threadId: row.sourceThreadId, id: row.sourceItemId })),
211 ).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
212 const payloads = yield* sql<{
213 thread_id: string;
214 turn_item_id: string;
215 payload_json: string;
216 entry_id: string;
217 run_id: OrchestrationV2TurnItem["runId"];
218 item_type: OrchestrationV2TurnItem["type"];
219 }>`
220 SELECT item.thread_id, item.turn_item_id, item.payload_json,
221 COALESCE(json_extract(item.payload_json, '$.messageId'), item.turn_item_id) AS entry_id,
222 json_extract(item.payload_json, '$.runId') AS run_id,
223 json_extract(item.payload_json, '$.type') AS item_type
224 FROM orchestration_v2_projection_turn_items AS item
225 JOIN json_each(${sources}) AS wanted
226 ON item.thread_id = json_extract(wanted.value, '$.threadId')
227 AND item.turn_item_id = json_extract(wanted.value, '$.id')
228 `.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
229 const byThread = new Map<string, Map<string, (typeof payloads)[number]>>();
230 for (const row of payloads) {
231 let items = byThread.get(row.thread_id);
232 if (!items) byThread.set(row.thread_id, (items = new Map()));
233 items.set(row.turn_item_id, row);
234 }
235 return yield* Effect.forEach(rows, (row) => {
236 const payload = byThread.get(row.sourceThreadId)?.get(row.sourceItemId);
237 return payload === undefined
238 ? Effect.fail(new ProjectionStoreReadError({ threadId }))
239 : Effect.succeed({
240 ...row,
241 payload: payload.payload_json,
242 entryId: payload.entry_id,
243 runId: payload.run_id,
244 type: payload.item_type,
245 });
246 });
247 });
248 const makeTextCache = (capacity: number) =>
249 Cache.make({ capacity, lookup: (key: TextKey) => Effect.sync(() => parseText(key)) });
250 // Text keys are message content, so entries never go stale. Cache TTL only expires on access
251 // and would keep the last searched threads forever. Each search borrows this for its whole
252 // stream, and all of it is dropped once Find is idle.
253 const findCaches = yield* RcRef.make({
254 acquire: Effect.all({
255 // Scans visit every message; a cache smaller than the thread churns without hits.
256 text: makeTextCache(8192),
257 // Bounded separately because each entry can hold a large body; typing reuses the parse.
258 largeText: makeTextCache(32),
259 scans: Effect.sync((): CompletedScans => new Map()),
260 }),
261 idleTimeToLive: "1 minute",
262 });
263 const readRevision = Effect.fn("ThreadFind.readRevision")(function* (
264 threadIds: readonly ThreadId[],
265 ) {
266 const sources = yield* encodeThreadIds(threadIds);
267 const revision = yield* sql<{ sequence: number }>`
268 WITH RECURSIVE source_threads(thread_id) AS (
269 SELECT value FROM json_each(${sources})
270 UNION
271 SELECT json_extract(t.payload_json, '$.forkedFrom.threadId')
272 FROM orchestration_v2_projection_threads t
273 JOIN source_threads s ON s.thread_id = t.thread_id
274 WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
275 )
276 SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
277 -- The planner otherwise walks every V2 event backwards from the newest,
278 -- which takes seconds for a thread that has been idle a long time.
279 INDEXED BY idx_orch_events_stream_sequence
280 WHERE application_event_version = 2 AND aggregate_kind = 'thread'
281 AND stream_id IN (SELECT thread_id FROM source_threads)
282 `;
283 return revision[0]?.sequence ?? 0;
284 });
285 const snapshot = Effect.fn("ThreadFind.snapshot")(
286 function* (input: OrchestrationV2SearchThreadInput, scans: CompletedScans) {
287 const { threadId } = input;
288 const active = yield* sql<{ cwd: string | null }>`
289 SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
290 FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
291 WHERE t.thread_id = ${threadId} AND t.deleted_at IS NULL AND p.deleted_at IS NULL
292 `;
293 if (!active[0]) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
294 const cwd = active[0].cwd ?? undefined;
295 const cacheKey = yield* encodeCacheKey({
296 threadId,
297 cwd,
298 query: input.query,
299 skills: input.skills ?? [],
300 });
301 const cached = scans.get(cacheKey);
302 if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
303 const selected = selectMatch(cached.documents, input);
304 scans.delete(cacheKey);
305 scans.set(cacheKey, cached);
306 return { result: resultForSelection(selected, cached.documents, cached.sequence) };
307 }
308 const index = yield* readIndex(threadId);
309 const sourceThreadIds = [...new Set([threadId, ...index.map((row) => row.sourceThreadId)])];
310 const sequence = yield* readRevision(sourceThreadIds);
311 const candidates = index
312 .map((row, position) => ({ ...row, position }))
313 .filter((row) =>
314 ["user_message", "assistant_message", "proposed_plan", "user_input_request"].includes(
315 row.item.type,
316 ),
317 );
318 const payloads: FindPayload[] = [];
319 for (let start = 0; start < candidates.length; start += 128) {
320 payloads.push(...(yield* load(threadId, candidates.slice(start, start + 128))));
321 }
322 return { payloads, cwd, sequence, cacheKey, sourceThreadIds };
323 },
324 (effect) => sql.withTransaction(effect).pipe(NodeSqliteClient.readOnly),
325 (effect, input) =>
326 effect.pipe(
327 Effect.mapError((cause) =>
328 isSnapshotError(cause)
329 ? cause
330 : new ProjectionStoreReadError({ threadId: input.threadId, cause }),
331 ),
332 ),
333 );
334 const searchThreadStream = (input: OrchestrationV2SearchThreadInput) =>
335 Stream.unwrap(
336 Effect.gen(function* () {
337 const { scans, ...textCache } = yield* RcRef.get(findCaches);
338 // Release SQLite before decoding and parsing. Both frames describe one snapshot.
339 const data = yield* snapshot(input, scans);
340 if (data.result) return Stream.succeed(data.result);
341 const { payloads, cwd, sequence, cacheKey, sourceThreadIds } = data;
342 const decode = (row: FindPayload) =>
343 decodeItem(row.payload).pipe(
344 Effect.map((item) => ({ ...row, item })),
345 Effect.mapError(
346 (cause) => new ProjectionStoreReadError({ threadId: input.threadId, cause }),
347 ),
348 );
349 // Answers rendered inside question cards must not appear as separate matches.
350 const foldedAnswerRunIds = new Map<string, OrchestrationV2TurnItem["runId"]>();
351 for (const payload of payloads) {
352 if (payload.type !== "user_input_request") continue;
353 const { item } = yield* decode(payload);
354 if (item.type === "user_input_request" && item.questionAnswer)
355 foldedAnswerRunIds.set(`async-answer:${item.questionAnswer.requestId}`, item.runId);
356 }
357 const rows = payloads.filter(
358 (row) =>
359 row.type !== "user_input_request" &&
360 !(row.type === "user_message" && foldedAnswerRunIds.get(row.entryId) === row.runId),
361 );
362 const documents = new Map<number, FindDocument>();
363 const count = Effect.fnUntraced(function* (row: FindPayload) {
364 const cached = documents.get(row.position);
365 if (cached) return cached;
366 const decoded = yield* decode(row);
367 const key = textKey(decoded.item, cwd, input.skills ?? []);
368 const segments = yield* Cache.get(
369 key.text.length <= 32_768 ? textCache.text : textCache.largeText,
370 key,
371 );
372 const document = documentFor(decoded, countSegments(segments, input.query));
373 documents.set(row.position, document);
374 yield* Effect.yieldNow;
375 return document;
376 });
377 const finish = Effect.gen(function* () {
378 for (const row of rows) yield* count(row);
379 const ordered = rows.map((row) => documents.get(row.position)!);
380 scans.delete(cacheKey);
381 scans.set(cacheKey, { sequence, documents: ordered, sourceThreadIds });
382 if (scans.size > 8) {
383 const oldest = scans.keys().next().value;
384 if (oldest !== undefined) scans.delete(oldest);
385 }
386 return resultForSelection(selectMatch(ordered, input), ordered, sequence);
387 });
388 if (input.index !== undefined || (input.offset ?? 0) !== 0)
389 return Stream.fromEffect(finish);
390 const anchor = Math.max(
391 0,
392 rows.findIndex((row) => row.entryId === input.start?.entryId),
393 );
394 for (let step = 0; step <= rows.length; step++) {
395 const index = (anchor + step) % rows.length;
396 const row = rows[index];
397 if (!row) break;
398 const document = yield* count(row);
399 const occurrence =
400 step === 0 && row.entryId === input.start?.entryId
401 ? Math.min(input.start.occurrence, document.count)
402 : 0;
403 if (occurrence >= document.count) continue;
404 const first: OrchestrationV2SearchThreadResult = {
405 complete: false,
406 snapshotSequence: sequence,
407 totalMatches: 1,
408 activeIndex: 0,
409 match: { entryId: document.entryId, runId: document.runId, occurrence },
410 };
411 return Stream.concat(Stream.succeed(first), Stream.fromEffect(finish));
412 }
413 return Stream.fromEffect(finish);
414 }),
415 );
416 return {
417 searchThreadStream,
418 searchThread: (input: OrchestrationV2SearchThreadInput) =>
419 searchThreadStream(input).pipe(
420 Stream.runCollect,
421 Effect.map((results) => results[results.length - 1]!),
422 ),
423 };
424});