@luxass/pi-session-search 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,456 @@
1
+ /**
2
+ * Scrolls pi's fullscreen transcript to a message.
3
+ *
4
+ * pi has no public API for this, so this module reads pi-tui and pi internals:
5
+ * the fullscreen renderer's last layout (`currentLayout`), its primary scroll
6
+ * view, the rendered transcript rows, and the per-child row cache that pi-tui
7
+ * containers keep (`childLines`). pi's message components store the session
8
+ * entry id (`messageId`) and tool components store the tool call id
9
+ * (`toolCallId`), so a message can be found by identity before falling back
10
+ * to text search. Tool components also have `setExpanded`, which is used to
11
+ * expand one tool's collapsed output when the match is inside it.
12
+ *
13
+ * Every step is feature-detected and nothing here throws. When anything is
14
+ * missing, callers get "unsupported" and fall back to closing the picker with
15
+ * a notice. Keep all internal access here.
16
+ */
17
+
18
+ import { stripTerminalSequences, type TUI } from "@earendil-works/pi-tui";
19
+
20
+ /**
21
+ * What a reveal did. "collapsed" means the tool component was found but the
22
+ * matched text is not rendered in it, as when its output is collapsed; the
23
+ * transcript then shows the top of that tool call.
24
+ */
25
+ export type RevealOutcome = "revealed" | "collapsed" | "not-found" | "unsupported";
26
+
27
+ /** Identity of the transcript component that renders a message. */
28
+ export interface TranscriptIdentity {
29
+ /** Session entry id, which pi stores as `messageId` on user and assistant message components. */
30
+ messageId?: string;
31
+ /** Tool call id, which pi stores as `toolCallId` on tool execution components. */
32
+ toolCallId?: string;
33
+ }
34
+
35
+ /** A text to look for, and which of its occurrences belongs to the message. */
36
+ export interface TranscriptNeedle {
37
+ text: string;
38
+ /** Occurrences of `text` rendered before the message's own one, counted over the whole transcript (0-based). */
39
+ occurrence: number;
40
+ /** Occurrences of `text` inside the message before the matched one (0-based). Used within an identified component. */
41
+ occurrenceInMessage: number;
42
+ /**
43
+ * True when finding this needle shows the match itself: the words at the
44
+ * match, or a tool call's argument, which renders in the call's header.
45
+ * Not set for the start of the message, which only shows where it begins.
46
+ */
47
+ pinpoints?: boolean;
48
+ }
49
+
50
+ export interface RevealTarget {
51
+ /** Tried first. Undefined when the message kind has no identity in the transcript. */
52
+ identity?: TranscriptIdentity;
53
+ /** Texts to look for, best first. Each is tried until one is found. */
54
+ needles: TranscriptNeedle[];
55
+ }
56
+
57
+ /** Rows kept above the message after scrolling, so its start is easy to see. */
58
+ const ROWS_ABOVE = 2;
59
+ /** Attempts to find the message while pi re-renders after a switch. */
60
+ const ATTEMPTS = 12;
61
+ const ATTEMPT_DELAY_MS = 50;
62
+ /** Deepest component nesting walked when looking for an identity. */
63
+ const MAX_COMPONENT_DEPTH = 32;
64
+
65
+ interface ScrollViewLike {
66
+ scrollTo(row: number, options?: { disableFollow?: boolean }): void;
67
+ }
68
+
69
+ interface TranscriptView {
70
+ scrollView: ScrollViewLike;
71
+ rows: readonly string[];
72
+ /** The component rendered inside the scroll view, when the layout exposes it. */
73
+ content: unknown;
74
+ }
75
+
76
+ function isRecord(value: unknown): value is Record<string, unknown> {
77
+ return typeof value === "object" && value !== null;
78
+ }
79
+
80
+ /** Finds the layout box that renders `scrollView`. */
81
+ function findScrollBox(
82
+ box: unknown,
83
+ scrollView: unknown,
84
+ depth = 0,
85
+ ): Record<string, unknown> | undefined {
86
+ if (!isRecord(box) || depth > 64) {
87
+ return undefined;
88
+ }
89
+ if (box.scrollView === scrollView && Array.isArray(box.scrollContentLines)) {
90
+ return box;
91
+ }
92
+ if (!Array.isArray(box.children)) {
93
+ return undefined;
94
+ }
95
+ for (const child of box.children) {
96
+ const found = findScrollBox(child, scrollView, depth + 1);
97
+ if (found !== undefined) {
98
+ return found;
99
+ }
100
+ }
101
+ return undefined;
102
+ }
103
+
104
+ /** Reads the transcript of the fullscreen renderer, or undefined when not available. */
105
+ function readTranscript(tui: TUI): TranscriptView | undefined {
106
+ try {
107
+ if (tui.mode !== "fullscreen") {
108
+ return undefined;
109
+ }
110
+ const layout: unknown = (tui as unknown as Record<string, unknown>).currentLayout;
111
+ if (!isRecord(layout)) {
112
+ return undefined;
113
+ }
114
+ const scrollView = layout.primaryScrollView;
115
+ if (!isRecord(scrollView) || typeof scrollView.scrollTo !== "function") {
116
+ return undefined;
117
+ }
118
+ const box = findScrollBox(layout.root, scrollView);
119
+ if (box === undefined) {
120
+ return undefined;
121
+ }
122
+ const rows = box.scrollContentLines as unknown[];
123
+ if (!rows.every((row) => typeof row === "string")) {
124
+ return undefined;
125
+ }
126
+ const children: unknown = box.children;
127
+ const contentBox: unknown = Array.isArray(children) ? (children as unknown[])[0] : undefined;
128
+ const content = isRecord(contentBox) ? contentBox.component : undefined;
129
+ return { scrollView: scrollView as unknown as ScrollViewLike, rows, content };
130
+ } catch {
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ /** True when this pi build exposes what revealInTranscript needs. */
136
+ export function canRevealInTranscript(tui: TUI | undefined): boolean {
137
+ return tui !== undefined && readTranscript(tui) !== undefined;
138
+ }
139
+
140
+ /**
141
+ * Normalizes text for comparing source messages with rendered rows: no
142
+ * escapes, no Markdown markers, single spaces, lowercase.
143
+ */
144
+ export function normalizeForComparison(text: string): string {
145
+ return stripTerminalSequences(text)
146
+ .replace(/[`*_#>|~]/gu, "")
147
+ .replace(/\s+/gu, " ")
148
+ .trim()
149
+ .toLowerCase();
150
+ }
151
+
152
+ /** Counts how often `needle` occurs in `haystack`, both already normalized. */
153
+ export function countOccurrences(haystack: string, needle: string): number {
154
+ if (needle === "") {
155
+ return 0;
156
+ }
157
+ let count = 0;
158
+ let from = haystack.indexOf(needle);
159
+ while (from >= 0) {
160
+ count += 1;
161
+ from = haystack.indexOf(needle, from + needle.length);
162
+ }
163
+ return count;
164
+ }
165
+
166
+ /**
167
+ * Returns the transcript row where the chosen occurrence of a needle starts,
168
+ * or undefined when the needle occurs fewer than `occurrence + 1` times. A
169
+ * missing occurrence is a miss, never a guess at another occurrence.
170
+ */
171
+ export function locateRow(
172
+ rows: readonly string[],
173
+ needle: string,
174
+ occurrence: number,
175
+ ): number | undefined {
176
+ const target = normalizeForComparison(needle);
177
+ if (target === "" || occurrence < 0) {
178
+ return undefined;
179
+ }
180
+ const rowStarts: number[] = [];
181
+ let joined = "";
182
+ for (const row of rows) {
183
+ rowStarts.push(joined.length);
184
+ const normalized = normalizeForComparison(row);
185
+ joined += normalized === "" ? "" : `${normalized} `;
186
+ }
187
+ let position = joined.indexOf(target);
188
+ for (let skipped = 0; skipped < occurrence && position >= 0; skipped += 1) {
189
+ position = joined.indexOf(target, position + target.length);
190
+ }
191
+ if (position < 0) {
192
+ return undefined;
193
+ }
194
+ let low = 0;
195
+ let high = rowStarts.length - 1;
196
+ while (low < high) {
197
+ const middle = Math.ceil((low + high) / 2);
198
+ if ((rowStarts[middle] as number) <= position) {
199
+ low = middle;
200
+ } else {
201
+ high = middle - 1;
202
+ }
203
+ }
204
+ return low;
205
+ }
206
+
207
+ /** Rows a component rendered, and where they start in the transcript. */
208
+ export interface ComponentRows {
209
+ start: number;
210
+ count: number;
211
+ /** The component itself, for feature-detected actions such as expanding it. */
212
+ component: Record<string, unknown>;
213
+ }
214
+
215
+ function componentHasIdentity(
216
+ component: Record<string, unknown>,
217
+ identity: TranscriptIdentity,
218
+ ): boolean {
219
+ if (identity.messageId !== undefined && component.messageId === identity.messageId) {
220
+ return true;
221
+ }
222
+ return identity.toolCallId !== undefined && component.toolCallId === identity.toolCallId;
223
+ }
224
+
225
+ /** The per-child row cache of a pi-tui Container, when it has one that matches its row count. */
226
+ function cachedChildRows(
227
+ component: Record<string, unknown>,
228
+ expectedRows: number,
229
+ ): Array<{ child: unknown; rows: number }> | undefined {
230
+ const cache = component.childLines;
231
+ if (
232
+ !isRecord(cache) ||
233
+ !Array.isArray(cache.children) ||
234
+ !Array.isArray(cache.parts) ||
235
+ !Array.isArray(cache.lines)
236
+ ) {
237
+ return undefined;
238
+ }
239
+ if (cache.children.length !== cache.parts.length || cache.lines.length !== expectedRows) {
240
+ return undefined;
241
+ }
242
+ const children: Array<{ child: unknown; rows: number }> = [];
243
+ for (let index = 0; index < cache.children.length; index += 1) {
244
+ const part: unknown = cache.parts[index];
245
+ if (!Array.isArray(part)) {
246
+ return undefined;
247
+ }
248
+ children.push({ child: cache.children[index], rows: part.length });
249
+ }
250
+ return children;
251
+ }
252
+
253
+ /**
254
+ * Finds the rows of the first component with the given identity, walking the
255
+ * row caches pi-tui containers keep from their last render. Walks only caches
256
+ * whose row counts add up, so a stale cache never yields a wrong row.
257
+ */
258
+ export function findComponentRows(
259
+ content: unknown,
260
+ totalRows: number,
261
+ identity: TranscriptIdentity,
262
+ ): ComponentRows | undefined {
263
+ if (identity.messageId === undefined && identity.toolCallId === undefined) {
264
+ return undefined;
265
+ }
266
+ const visit = (
267
+ component: unknown,
268
+ start: number,
269
+ count: number,
270
+ depth: number,
271
+ ): ComponentRows | undefined => {
272
+ if (!isRecord(component) || depth > MAX_COMPONENT_DEPTH) {
273
+ return undefined;
274
+ }
275
+ if (componentHasIdentity(component, identity)) {
276
+ return count > 0 ? { start, count, component } : undefined;
277
+ }
278
+ const children = cachedChildRows(component, count);
279
+ if (children === undefined) {
280
+ return undefined;
281
+ }
282
+ let offset = start;
283
+ for (const { child, rows } of children) {
284
+ const found = visit(child, offset, rows, depth + 1);
285
+ if (found !== undefined) {
286
+ return found;
287
+ }
288
+ offset += rows;
289
+ }
290
+ return undefined;
291
+ };
292
+ try {
293
+ return visit(content, 0, totalRows, 0);
294
+ } catch {
295
+ return undefined;
296
+ }
297
+ }
298
+
299
+ /** Where a target is in the transcript. */
300
+ export interface TargetLocation {
301
+ row: number;
302
+ /**
303
+ * Set when the target's tool component is rendered but the match is not
304
+ * found inside it, usually because its output is collapsed. `row` is then
305
+ * the start of the message when that is found, else the top of the component.
306
+ */
307
+ hiddenInTool?: Record<string, unknown>;
308
+ }
309
+
310
+ /**
311
+ * The transcript row to show for a target: the identified component first,
312
+ * refined to the matched text inside it when that text is found there; then
313
+ * the needles, each with its own occurrence count.
314
+ */
315
+ export function locateTarget(
316
+ rows: readonly string[],
317
+ content: unknown,
318
+ target: RevealTarget,
319
+ ): TargetLocation | undefined {
320
+ if (target.identity !== undefined) {
321
+ const found = findComponentRows(content, rows.length, target.identity);
322
+ if (found !== undefined) {
323
+ // Message text can render differently from its source, so only a tool
324
+ // component, whose output pi collapses, counts as hiding the match.
325
+ const isTool =
326
+ target.identity.toolCallId !== undefined &&
327
+ found.component.toolCallId === target.identity.toolCallId;
328
+ // In a tool, finding only the start of the message is not finding the
329
+ // match: collapsed output can show its first lines and hide the rest.
330
+ const needsPinpoint = isTool && target.needles.some((needle) => needle.pinpoints === true);
331
+ const componentRows = rows.slice(found.start, found.start + found.count);
332
+ let startRow: number | undefined;
333
+ for (const needle of target.needles) {
334
+ const row = locateRow(componentRows, needle.text, needle.occurrenceInMessage);
335
+ if (row === undefined) {
336
+ continue;
337
+ }
338
+ if (!needsPinpoint || needle.pinpoints === true) {
339
+ return { row: found.start + row };
340
+ }
341
+ startRow ??= found.start + row;
342
+ }
343
+ return isTool && target.needles.length > 0
344
+ ? { row: startRow ?? found.start, hiddenInTool: found.component }
345
+ : { row: found.start };
346
+ }
347
+ }
348
+ for (const needle of target.needles) {
349
+ const row = locateRow(rows, needle.text, needle.occurrence);
350
+ if (row !== undefined) {
351
+ return { row };
352
+ }
353
+ }
354
+ return undefined;
355
+ }
356
+
357
+ function delay(milliseconds: number): Promise<void> {
358
+ return new Promise((resolve) => {
359
+ setTimeout(resolve, milliseconds).unref?.();
360
+ });
361
+ }
362
+
363
+ export interface RevealOptions {
364
+ /**
365
+ * Keep waiting while the match is hidden in its tool component, because
366
+ * tool output was just expanded and pi has not re-rendered yet.
367
+ */
368
+ afterExpand?: boolean;
369
+ }
370
+
371
+ /**
372
+ * Scrolls the transcript so the target message is near the top. Waits a few
373
+ * frames for pi to re-render after a session or branch switch. When the
374
+ * match is hidden in collapsed tool output, scrolls to the top of the tool
375
+ * call and returns "collapsed". Never throws.
376
+ */
377
+ export async function revealInTranscript(
378
+ tui: TUI | undefined,
379
+ target: RevealTarget,
380
+ afterSwitch: boolean,
381
+ options: RevealOptions = {},
382
+ ): Promise<RevealOutcome> {
383
+ if (tui === undefined) {
384
+ return "unsupported";
385
+ }
386
+ try {
387
+ if (afterSwitch || options.afterExpand === true) {
388
+ // Let pi lay out the new transcript before reading rows.
389
+ tui.requestRender();
390
+ await delay(ATTEMPT_DELAY_MS * 2);
391
+ }
392
+ let hiddenRow: number | undefined;
393
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
394
+ const transcript = readTranscript(tui);
395
+ if (transcript === undefined) {
396
+ return "unsupported";
397
+ }
398
+ const location = locateTarget(transcript.rows, transcript.content, target);
399
+ const hidden = location?.hiddenInTool !== undefined;
400
+ if (location !== undefined && (!hidden || options.afterExpand !== true)) {
401
+ transcript.scrollView.scrollTo(Math.max(0, location.row - ROWS_ABOVE), {
402
+ disableFollow: true,
403
+ });
404
+ tui.requestRender();
405
+ return hidden ? "collapsed" : "revealed";
406
+ }
407
+ if (location !== undefined) {
408
+ hiddenRow = location.row;
409
+ }
410
+ tui.requestRender();
411
+ await delay(ATTEMPT_DELAY_MS);
412
+ }
413
+ if (hiddenRow !== undefined) {
414
+ // Expanding did not bring the match into view; show the tool call at least.
415
+ const transcript = readTranscript(tui);
416
+ transcript?.scrollView.scrollTo(Math.max(0, hiddenRow - ROWS_ABOVE), { disableFollow: true });
417
+ tui.requestRender();
418
+ return "collapsed";
419
+ }
420
+ return "not-found";
421
+ } catch {
422
+ return "unsupported";
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Expands the output of the tool component that hides the target, through
428
+ * the `setExpanded` method pi's tool components have. Returns false when the
429
+ * component is not found, is already expanded, or has no such method. Pi
430
+ * applies this to one component only; its global tool expansion setting
431
+ * stays as it was. Never throws.
432
+ */
433
+ export function expandHiddenToolOutput(tui: TUI | undefined, target: RevealTarget): boolean {
434
+ if (tui === undefined) {
435
+ return false;
436
+ }
437
+ try {
438
+ const transcript = readTranscript(tui);
439
+ if (transcript === undefined) {
440
+ return false;
441
+ }
442
+ const component = locateTarget(transcript.rows, transcript.content, target)?.hiddenInTool;
443
+ if (
444
+ component === undefined ||
445
+ component.expanded === true ||
446
+ typeof component.setExpanded !== "function"
447
+ ) {
448
+ return false;
449
+ }
450
+ (component.setExpanded as (expanded: boolean) => void).call(component, true);
451
+ tui.requestRender();
452
+ return true;
453
+ } catch {
454
+ return false;
455
+ }
456
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Messages between pi's main thread and the index worker.
3
+ * Only types and two constants, so the worker can load it without Pi packages.
4
+ */
5
+
6
+ import type { SearchHit } from "./hits.ts";
7
+ import type { RoleFilter } from "./query.ts";
8
+ import type { SyncProgress, SyncSummary } from "./session-index.ts";
9
+
10
+ /** Passed as workerData. */
11
+ export interface WorkerSetup {
12
+ databasePath: string;
13
+ /**
14
+ * Shared Int32 slots the main thread writes while the worker is busy:
15
+ * the newest search request id, and a stop flag for indexing.
16
+ */
17
+ signals: SharedArrayBuffer;
18
+ }
19
+
20
+ /** Slot holding the newest search request id. Older searches stop early. */
21
+ export const SEARCH_SLOT = 0;
22
+ /** Slot that is non-zero when indexing should stop after the current transaction. */
23
+ export const STOP_SLOT = 1;
24
+ export const SIGNAL_SLOTS = 2;
25
+
26
+ export type WorkerRequest =
27
+ | { type: "sync"; roots: string[] }
28
+ | {
29
+ type: "search";
30
+ requestId: number;
31
+ queryText: string;
32
+ roleFilter: RoleFilter;
33
+ limit: number;
34
+ /** Time of the search in milliseconds since the epoch, for relative since: and until:. */
35
+ now: number;
36
+ /** Most hits per session file. Undefined for no cap. */
37
+ perSessionLimit: number | undefined;
38
+ }
39
+ | {
40
+ /** Reads one item's full text, for copying or inserting a match. */
41
+ type: "readItem";
42
+ requestId: number;
43
+ sessionFile: string;
44
+ entryId: string;
45
+ part: number;
46
+ }
47
+ | { type: "close" };
48
+
49
+ export type WorkerReply =
50
+ | ({ type: "progress" } & SyncProgress)
51
+ | { type: "synced"; summary: SyncSummary }
52
+ | {
53
+ type: "results";
54
+ requestId: number;
55
+ hits: SearchHit[];
56
+ truncated: boolean;
57
+ /** Session files that had more matches than perSessionLimit allowed. */
58
+ sessionsWithMore: string[];
59
+ }
60
+ | {
61
+ type: "item";
62
+ requestId: number;
63
+ /** Undefined when the file no longer holds the indexed item. */
64
+ text: string | undefined;
65
+ }
66
+ | { type: "failed"; requestId?: number; message: string };