@luxass/pi-session-search 0.0.0-stage → 0.1.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.
package/src/index.ts ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * session-search: /find searches the current session, /find-all searches
3
+ * every pi session on this machine through a local SQLite index.
4
+ */
5
+
6
+ import { homedir } from "node:os";
7
+ import { isAbsolute, join, relative } from "node:path";
8
+
9
+ import {
10
+ copyToClipboard,
11
+ type ExtensionAPI,
12
+ type ExtensionCommandContext,
13
+ type ExtensionContext,
14
+ getAgentDir,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import type { TUI } from "@earendil-works/pi-tui";
17
+
18
+ import { CurrentSessionSearcher } from "./current-session-search.ts";
19
+ import { type FinderResult, type FinderScope, FinderOverlay } from "./finder-overlay.ts";
20
+ import type { SearchHit } from "./hits.ts";
21
+ import { type IndexLocation, IndexSearcher, IndexUpdater } from "./index-client.ts";
22
+ import { type MatchTextSources, readMatchText } from "./match-text.ts";
23
+ import { openHit } from "./open-match.ts";
24
+
25
+ /** Wait after startup before the background index update, so startup stays quick. */
26
+ const BACKGROUND_INDEX_DELAY_MS = 4000;
27
+
28
+ function isInside(child: string, parent: string): boolean {
29
+ const path = relative(parent, child);
30
+ return path === "" || (!path.startsWith("..") && !isAbsolute(path));
31
+ }
32
+
33
+ /**
34
+ * The index lives in the agent cache directory. It covers pi's sessions
35
+ * directory, plus the current session's directory when a custom session
36
+ * directory puts it elsewhere.
37
+ */
38
+ function indexLocation(ctx: Pick<ExtensionContext, "sessionManager">): IndexLocation {
39
+ const agentDirectory = getAgentDir();
40
+ const sessionsRoot = join(agentDirectory, "sessions");
41
+ const sessionRoots = [sessionsRoot];
42
+ try {
43
+ const currentDirectory = ctx.sessionManager.getSessionDir();
44
+ if (currentDirectory !== "" && !isInside(currentDirectory, sessionsRoot)) {
45
+ sessionRoots.push(currentDirectory);
46
+ }
47
+ } catch {
48
+ // An in-memory session has no directory to add.
49
+ }
50
+ return {
51
+ databasePath: join(agentDirectory, "cache", "session-search", "index.sqlite"),
52
+ sessionRoots,
53
+ };
54
+ }
55
+
56
+ /** One index updater per process, so /find-all and the startup update share work. */
57
+ let sharedUpdater: { key: string; updater: IndexUpdater } | undefined;
58
+
59
+ function updaterFor(location: IndexLocation): IndexUpdater {
60
+ const key = JSON.stringify(location);
61
+ if (sharedUpdater === undefined || sharedUpdater.key !== key) {
62
+ sharedUpdater?.updater.stop();
63
+ sharedUpdater = { key, updater: new IndexUpdater(location) };
64
+ }
65
+ return sharedUpdater.updater;
66
+ }
67
+
68
+ /**
69
+ * Puts the full text of `hit` into the prompt editor at the cursor, as a paste,
70
+ * so a long match collapses like any pasted text and the draft around it stays.
71
+ */
72
+ async function insertMatch(
73
+ ctx: ExtensionCommandContext,
74
+ hit: SearchHit,
75
+ sources: MatchTextSources,
76
+ ): Promise<void> {
77
+ let text: string;
78
+ try {
79
+ text = await readMatchText(hit, sources);
80
+ } catch (error) {
81
+ ctx.ui.notify(
82
+ `Could not insert the match: ${error instanceof Error ? error.message : String(error)}`,
83
+ "error",
84
+ );
85
+ return;
86
+ }
87
+ ctx.ui.pasteToEditor(text);
88
+ }
89
+
90
+ async function runFinder(
91
+ ctx: ExtensionCommandContext,
92
+ scope: FinderScope,
93
+ args: string,
94
+ ): Promise<void> {
95
+ if (ctx.mode !== "tui") {
96
+ ctx.ui.notify("/find and /find-all need pi's interactive terminal UI.", "error");
97
+ return;
98
+ }
99
+ const sessionManager = ctx.sessionManager;
100
+ const sessionName = sessionManager.getSessionName();
101
+ const current = new CurrentSessionSearcher({
102
+ sessionFile: sessionManager.getSessionFile(),
103
+ sessionId: sessionManager.getSessionId(),
104
+ ...(sessionName === undefined ? {} : { sessionName }),
105
+ cwd: sessionManager.getCwd(),
106
+ entries: sessionManager.getEntries(),
107
+ activeEntryIds: new Set(sessionManager.getBranch().map((entry) => entry.id)),
108
+ });
109
+
110
+ const location = indexLocation(ctx);
111
+ const searcher = new IndexSearcher(location);
112
+ const index = { searcher, updater: updaterFor(location) };
113
+ const sources: MatchTextSources = { current, index: searcher };
114
+
115
+ let tuiForReveal: TUI | undefined;
116
+ let overlay: FinderOverlay | undefined;
117
+ let result: FinderResult | undefined;
118
+ try {
119
+ result = await ctx.ui.custom<FinderResult | undefined>(
120
+ (tui, theme, keybindings, done) => {
121
+ tuiForReveal = tui;
122
+ overlay = new FinderOverlay({
123
+ tui,
124
+ theme,
125
+ keybindings,
126
+ done,
127
+ readMatchText: (hit) => readMatchText(hit, sources),
128
+ copyToClipboard,
129
+ scope,
130
+ initialQuery: args.trim(),
131
+ current,
132
+ index,
133
+ homeDirectory: homedir(),
134
+ });
135
+ return overlay;
136
+ },
137
+ {
138
+ overlay: true,
139
+ overlayOptions: { width: "90%", minWidth: 60, maxHeight: "85%", anchor: "center" },
140
+ blocked: { kind: "question", message: "Find a message" },
141
+ },
142
+ );
143
+ // Inserting may read the match through the searcher, so it runs before the searcher closes.
144
+ if (result?.action === "insert") {
145
+ await insertMatch(ctx, result.hit, sources);
146
+ }
147
+ } finally {
148
+ overlay?.dispose();
149
+ searcher.close();
150
+ }
151
+ if (result?.action === "open") {
152
+ await openHit(ctx, tuiForReveal, result.hit, overlay?.queryText ?? "");
153
+ }
154
+ }
155
+
156
+ export default function sessionSearch(pi: ExtensionAPI): void {
157
+ let backgroundTimer: ReturnType<typeof setTimeout> | undefined;
158
+
159
+ pi.registerCommand("find", {
160
+ description: "Search this session, all branches",
161
+ handler: async (args, ctx) => {
162
+ await runFinder(ctx, "current", args);
163
+ },
164
+ });
165
+
166
+ pi.registerCommand("find-all", {
167
+ description: "Search every pi session on this machine",
168
+ handler: async (args, ctx) => {
169
+ await runFinder(ctx, "all", args);
170
+ },
171
+ });
172
+
173
+ pi.on("session_start", (event, ctx) => {
174
+ if (event.reason !== "startup" || ctx.mode !== "tui") {
175
+ return;
176
+ }
177
+ const location = indexLocation(ctx);
178
+ backgroundTimer = setTimeout(() => {
179
+ backgroundTimer = undefined;
180
+ // Failures here are silent; /find-all reports them when the user asks.
181
+ updaterFor(location)
182
+ .update()
183
+ .catch(() => undefined);
184
+ }, BACKGROUND_INDEX_DELAY_MS);
185
+ backgroundTimer.unref?.();
186
+ });
187
+
188
+ pi.on("session_shutdown", () => {
189
+ if (backgroundTimer !== undefined) {
190
+ clearTimeout(backgroundTimer);
191
+ backgroundTimer = undefined;
192
+ }
193
+ // Committed index data stays; the worker stops after its current transaction.
194
+ sharedUpdater?.updater.stop();
195
+ });
196
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Byte-exact reading of session JSONL files.
3
+ *
4
+ * The index stores where each line starts and how long it is instead of the
5
+ * text, then reads the line again when it needs to verify or preview a hit.
6
+ * Loaded by the index worker, which strips types itself: type annotations only, and no Pi packages.
7
+ */
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { readSync } from "node:fs";
11
+
12
+ /** One complete line. `offset` and `length` are in bytes and exclude the newline. */
13
+ export interface JsonlLine {
14
+ offset: number;
15
+ length: number;
16
+ text: string;
17
+ }
18
+
19
+ export interface LineBatch {
20
+ lines: JsonlLine[];
21
+ /** Byte offset just after the last complete line. Equal to `start` when none was read. */
22
+ nextOffset: number;
23
+ }
24
+
25
+ const READ_CHUNK_BYTES = 1024 * 1024;
26
+ const NEWLINE = 0x0a;
27
+
28
+ /**
29
+ * Reads complete lines from `start`, stopping at the first line boundary after
30
+ * `maxBytes`. A line still being written (no newline yet) is left for later,
31
+ * because pi appends whole lines and the rest will follow.
32
+ */
33
+ export function readCompleteLines(fd: number, start: number, maxBytes: number): LineBatch {
34
+ const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES);
35
+ const pending: Buffer[] = [];
36
+ const lines: JsonlLine[] = [];
37
+ let position = start;
38
+ let lineStart = start;
39
+
40
+ for (;;) {
41
+ const bytesRead = readSync(fd, buffer, 0, READ_CHUNK_BYTES, position);
42
+ if (bytesRead === 0) {
43
+ break;
44
+ }
45
+ let scan = 0;
46
+ while (scan < bytesRead) {
47
+ const newline = buffer.indexOf(NEWLINE, scan);
48
+ if (newline === -1 || newline >= bytesRead) {
49
+ pending.push(Buffer.from(buffer.subarray(scan, bytesRead)));
50
+ break;
51
+ }
52
+ const tail = buffer.subarray(scan, newline);
53
+ const lineBytes = pending.length > 0 ? Buffer.concat([...pending, tail]) : tail;
54
+ pending.length = 0;
55
+ lines.push({ offset: lineStart, length: lineBytes.length, text: lineBytes.toString("utf8") });
56
+ lineStart += lineBytes.length + 1;
57
+ scan = newline + 1;
58
+ if (lineStart - start >= maxBytes) {
59
+ return { lines, nextOffset: lineStart };
60
+ }
61
+ }
62
+ position += bytesRead;
63
+ }
64
+ return { lines, nextOffset: lineStart };
65
+ }
66
+
67
+ function readBytesAt(fd: number, offset: number, length: number): Buffer {
68
+ const buffer = Buffer.allocUnsafe(length);
69
+ let filled = 0;
70
+ while (filled < length) {
71
+ const bytesRead = readSync(fd, buffer, filled, length - filled, offset + filled);
72
+ if (bytesRead === 0) {
73
+ break;
74
+ }
75
+ filled += bytesRead;
76
+ }
77
+ return buffer.subarray(0, filled);
78
+ }
79
+
80
+ /** Reads one line back by its byte range. */
81
+ export function readLineAt(fd: number, offset: number, length: number): string {
82
+ return readBytesAt(fd, offset, length).toString("utf8");
83
+ }
84
+
85
+ /** Bytes hashed just before an offset to notice files rewritten in place. */
86
+ const CHECKPOINT_BYTES = 512;
87
+
88
+ /**
89
+ * Hashes the bytes that end at `offset`. If the stored hash no longer matches,
90
+ * the file was rewritten and its index must be rebuilt from the start.
91
+ */
92
+ export function checkpointDigest(fd: number, offset: number): string {
93
+ if (offset <= 0) {
94
+ return "";
95
+ }
96
+ const start = Math.max(0, offset - CHECKPOINT_BYTES);
97
+ return createHash("sha1")
98
+ .update(readBytesAt(fd, start, offset - start))
99
+ .digest("hex");
100
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The full text of a match, for copying it or inserting it into the prompt.
3
+ * A hit only carries the window around the match (see windowAroundMatch()),
4
+ * so the whole item is read again: from memory for the open session, or from
5
+ * the session file through the index worker for other sessions.
6
+ */
7
+
8
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
9
+
10
+ import type { CurrentSessionSearcher } from "./current-session-search.ts";
11
+ import type { SearchHit } from "./hits.ts";
12
+ import type { IndexSearcher } from "./index-client.ts";
13
+
14
+ /** Where the full text of a hit can come from. */
15
+ export interface MatchTextSources {
16
+ current: Pick<CurrentSessionSearcher, "owns" | "fullText">;
17
+ /** Undefined when the all-sessions index cannot run. */
18
+ index: Pick<IndexSearcher, "readItem"> | undefined;
19
+ }
20
+
21
+ /**
22
+ * Removes terminal escape sequences and control characters, so copied or
23
+ * inserted text cannot drive the terminal. Newlines and tabs stay, and CRLF
24
+ * line ends become LF.
25
+ */
26
+ export function cleanMatchText(text: string): string {
27
+ return (
28
+ stripTerminalSequences(text)
29
+ .replace(/\r\n?/gu, "\n")
30
+ // oxlint-disable-next-line no-control-regex -- removing control characters is the point.
31
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu, "")
32
+ );
33
+ }
34
+
35
+ /**
36
+ * The whole text of the hit's item, cleaned with cleanMatchText(). When the
37
+ * item cannot be read again, a hit that already shows its whole item still
38
+ * gives its text. Otherwise this throws, so nothing partial is copied.
39
+ */
40
+ export async function readMatchText(hit: SearchHit, sources: MatchTextSources): Promise<string> {
41
+ let fullText: string | undefined;
42
+ if (sources.current.owns(hit)) {
43
+ fullText = sources.current.fullText(hit.entryId, hit.part);
44
+ }
45
+ if (fullText === undefined && hit.sessionFile !== undefined && sources.index !== undefined) {
46
+ fullText = await sources.index.readItem({
47
+ sessionFile: hit.sessionFile,
48
+ entryId: hit.entryId,
49
+ part: hit.part,
50
+ });
51
+ }
52
+ if (fullText === undefined) {
53
+ if (hit.clippedStart || hit.clippedEnd) {
54
+ throw new Error("the session file changed since the search; search again");
55
+ }
56
+ fullText = hit.text;
57
+ }
58
+ return cleanMatchText(fullText);
59
+ }
60
+
61
+ /** "Copied 1,234 characters": the status note after a copy. */
62
+ export function copiedNoteText(text: string): string {
63
+ const count = Array.from(text).length;
64
+ return `Copied ${count.toLocaleString("en-US")} ${count === 1 ? "character" : "characters"}`;
65
+ }