@deathbeam/pi-archive 0.0.1

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -0
  3. package/index.ts +399 -0
  4. package/package.json +36 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tomas Slusny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @deathbeam/pi-archive
2
+
3
+ Search past Pi sessions with `search_archive` and show recent session titles.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ # Choose one:
9
+ pi install npm:@deathbeam/pi-archive # this package
10
+ pi install git:github.com/deathbeam/pi-packages # all four packages
11
+ ```
12
+
13
+ ## Development
14
+
15
+ From this package directory:
16
+
17
+ ```sh
18
+ npm install
19
+ npm test
20
+ pi install .
21
+ ```
package/index.ts ADDED
@@ -0,0 +1,399 @@
1
+ /** Search Pi's persisted JSONL transcripts, including compacted-away entries. */
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+
7
+ const MAX_TOTAL_BYTES = 400 * 1024 * 1024;
8
+ const MAX_PER_FILE = 3; // max matches per session file
9
+ const MAX_SEARCH_LIMIT = 100;
10
+ const READ_CHUNK_BYTES = 64 * 1024;
11
+ const MAX_LINE_BYTES = 16 * 1024 * 1024;
12
+ // ponytail: 16 MiB record ceiling; raise only if real sessions exceed it, or add incremental JSON parsing.
13
+
14
+ export interface ArchiveMatch {
15
+ file: string;
16
+ project: string; // short project label, e.g. "git/dotfiles"
17
+ date: string; // from file name, e.g. "2026-09-07"
18
+ role: string;
19
+ excerpt: string;
20
+ currentSession: boolean;
21
+ sameProject: boolean;
22
+ }
23
+
24
+ export interface SearchOptions {
25
+ currentFile?: string;
26
+ currentDir?: string;
27
+ sessionFilter?: string; // substring matched against the encoded cwd dir name
28
+ limit?: number;
29
+ }
30
+
31
+ function parseJsonLine(line: string): any | null {
32
+ try {
33
+ return JSON.parse(line);
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ export function projectLabel(dirName: string): string {
40
+ const parts = dirName.replace(/^-+|-+$/g, "").split("-");
41
+ return parts.length <= 2 ? parts.join("/") : parts.slice(-2).join("/");
42
+ }
43
+
44
+ export function fileDate(fileName: string): string {
45
+ return fileName.slice(0, 10);
46
+ }
47
+
48
+ export function entryText(entry: unknown): { role: string; text: string } | null {
49
+ const e = entry as Record<string, any>;
50
+ const content = e?.message?.content;
51
+ if (
52
+ e?.type === "message" &&
53
+ (Array.isArray(content) || (e.message.role === "user" && typeof content === "string"))
54
+ ) {
55
+ const text =
56
+ typeof content === "string"
57
+ ? content
58
+ : content
59
+ .filter((c: any) => c?.type === "text" && typeof c.text === "string")
60
+ .map((c: any) => c.text)
61
+ .join("\n");
62
+ if (!text) return null;
63
+ return { role: String(e.message.role ?? "?"), text };
64
+ }
65
+ if (e?.type === "compaction" && typeof e.summary === "string") {
66
+ return { role: "summary", text: e.summary };
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /** LF-only JSONL: readline also splits literal U+2028/U+2029 inside JSON strings. */
72
+ async function scanJsonLines(
73
+ file: string,
74
+ maxBytes: number,
75
+ signal: AbortSignal | undefined,
76
+ onLine: (line: string) => boolean,
77
+ ): Promise<{ bytes: number; incomplete: boolean; oversizedLines: number }> {
78
+ const empty = { bytes: 0, incomplete: false, oversizedLines: 0 };
79
+ if (signal?.aborted || maxBytes <= 0) return { ...empty, incomplete: maxBytes <= 0 };
80
+
81
+ let size: number;
82
+ try {
83
+ size = (await fs.promises.stat(file)).size;
84
+ } catch {
85
+ return { ...empty, incomplete: true };
86
+ }
87
+ if (size === 0) return empty;
88
+
89
+ const stream = fs.createReadStream(file, {
90
+ start: 0,
91
+ end: Math.min(size, maxBytes) - 1,
92
+ encoding: "utf8",
93
+ highWaterMark: READ_CHUNK_BYTES,
94
+ });
95
+ let bytes = 0;
96
+ let pending = "";
97
+ let pendingBytes = 0;
98
+ let skippingLine = false;
99
+ let oversizedLines = 0;
100
+ let stopped = false;
101
+
102
+ const consume = (text: string): boolean => {
103
+ let start = 0;
104
+ while (start < text.length) {
105
+ const newline = text.indexOf("\n", start);
106
+ const end = newline === -1 ? text.length : newline + 1;
107
+ if (skippingLine) {
108
+ if (newline !== -1) skippingLine = false;
109
+ } else {
110
+ const part = text.slice(start, end);
111
+ pending += part;
112
+ pendingBytes += Buffer.byteLength(part);
113
+ if (pendingBytes > MAX_LINE_BYTES) {
114
+ oversizedLines++;
115
+ pending = "";
116
+ pendingBytes = 0;
117
+ skippingLine = newline === -1;
118
+ } else if (newline !== -1) {
119
+ if (!onLine(pending.slice(0, -1))) return false;
120
+ pending = "";
121
+ pendingBytes = 0;
122
+ }
123
+ }
124
+ if (newline === -1) return true;
125
+ start = end;
126
+ }
127
+ return true;
128
+ };
129
+
130
+ try {
131
+ for await (const chunk of stream) {
132
+ if (signal?.aborted) {
133
+ stopped = true;
134
+ break;
135
+ }
136
+ const text = chunk as string;
137
+ bytes += Buffer.byteLength(text);
138
+ if (!consume(text)) {
139
+ stopped = true;
140
+ break;
141
+ }
142
+ }
143
+ if (!stopped && !signal?.aborted && pending && !skippingLine) onLine(pending);
144
+ let incomplete = size > maxBytes;
145
+ if (!incomplete && !stopped && !signal?.aborted) {
146
+ try {
147
+ incomplete = (await fs.promises.stat(file)).size > bytes;
148
+ } catch {
149
+ incomplete = true;
150
+ }
151
+ }
152
+ return { bytes, incomplete, oversizedLines };
153
+ } catch {
154
+ return { bytes, incomplete: true, oversizedLines };
155
+ }
156
+ }
157
+
158
+ export function parseTerms(query: string): string[] {
159
+ return query.toLowerCase().split(/\s+/).filter(Boolean);
160
+ }
161
+
162
+ export function matchesAll(text: string, terms: string[]): boolean {
163
+ const lower = text.toLowerCase();
164
+ return terms.every((t) => lower.includes(t));
165
+ }
166
+
167
+ export function excerptAround(text: string, terms: string[], radius = 150): string {
168
+ const lower = text.toLowerCase();
169
+ let idx = -1;
170
+ for (const t of terms) {
171
+ const i = lower.indexOf(t);
172
+ if (i >= 0 && (idx === -1 || i < idx)) idx = i;
173
+ }
174
+ const start = idx === -1 ? 0 : Math.max(0, idx - radius);
175
+ const end = idx === -1 ? radius * 2 : idx + radius;
176
+ return (start > 0 ? "…" : "") + text.slice(start, end) + (end < text.length ? "…" : "");
177
+ }
178
+
179
+ /** Rank the current session first, then this project, then other projects newest-first. */
180
+ export async function searchSessions(
181
+ root: string,
182
+ query: string,
183
+ opts: SearchOptions = {},
184
+ signal?: AbortSignal,
185
+ onProgress?: (filesScanned: number, matches: number) => void,
186
+ ): Promise<{ matches: ArchiveMatch[]; bytesScanned: number; filesScanned: number; truncated: boolean }> {
187
+ const terms = parseTerms(query);
188
+ if (
189
+ opts.limit !== undefined &&
190
+ (!Number.isSafeInteger(opts.limit) || opts.limit < 1 || opts.limit > MAX_SEARCH_LIMIT)
191
+ ) {
192
+ throw new RangeError(`limit must be an integer from 1 to ${MAX_SEARCH_LIMIT}`);
193
+ }
194
+ if (terms.length === 0) return { matches: [], bytesScanned: 0, filesScanned: 0, truncated: false };
195
+ const limit = opts.limit ?? 20;
196
+ const filter = opts.sessionFilter?.toLowerCase();
197
+
198
+ const files: { file: string; dir: string; name: string; mtime: number }[] = [];
199
+ let rootEntries: fs.Dirent[];
200
+ try {
201
+ rootEntries = await fs.promises.readdir(root, { withFileTypes: true });
202
+ } catch {
203
+ return { matches: [], bytesScanned: 0, filesScanned: 0, truncated: false };
204
+ }
205
+ for (const entry of rootEntries) {
206
+ if (signal?.aborted) break;
207
+ if (!entry.isDirectory()) continue;
208
+ const dirName = entry.name;
209
+ if (filter && !dirName.toLowerCase().includes(filter)) continue;
210
+ const dir = path.join(root, dirName);
211
+ let entries: fs.Dirent[];
212
+ try {
213
+ entries = await fs.promises.readdir(dir, { withFileTypes: true });
214
+ } catch {
215
+ continue; // directory changed or became unreadable
216
+ }
217
+ for (const fileEntry of entries) {
218
+ if (signal?.aborted) break;
219
+ if (!fileEntry.isFile() || !fileEntry.name.endsWith(".jsonl")) continue;
220
+ const file = path.join(dir, fileEntry.name);
221
+ try {
222
+ files.push({ file, dir: dirName, name: fileEntry.name, mtime: (await fs.promises.stat(file)).mtimeMs });
223
+ } catch {}
224
+ }
225
+ }
226
+ if (signal?.aborted) return { matches: [], bytesScanned: 0, filesScanned: 0, truncated: true };
227
+
228
+ const currentDirName = opts.currentDir ? path.basename(opts.currentDir) : undefined;
229
+ const rank = (f: (typeof files)[number]) =>
230
+ f.file === opts.currentFile ? 0 : currentDirName && f.dir === currentDirName ? 1 : 2;
231
+ files.sort((a, b) => rank(a) - rank(b) || b.mtime - a.mtime);
232
+
233
+ const matches: ArchiveMatch[] = [];
234
+ let bytes = 0;
235
+ let filesScanned = 0;
236
+ let truncated = false;
237
+ for (const { file, dir, name } of files) {
238
+ if (signal?.aborted || bytes >= MAX_TOTAL_BYTES) {
239
+ truncated = true;
240
+ break;
241
+ }
242
+ onProgress?.(filesScanned, matches.length);
243
+ let fileMatches = 0;
244
+ const scan = await scanJsonLines(file, MAX_TOTAL_BYTES - bytes, signal, (line) => {
245
+ if (fileMatches >= MAX_PER_FILE || matches.length >= limit) return false;
246
+ if (!line || !terms.some((t) => line.toLowerCase().includes(t))) return true;
247
+ const parsed = parseJsonLine(line);
248
+ if (!parsed) return true;
249
+ const et = entryText(parsed);
250
+ if (!et || !matchesAll(et.text, terms)) return true;
251
+ matches.push({
252
+ file,
253
+ project: projectLabel(dir),
254
+ date: fileDate(name),
255
+ role: et.role,
256
+ excerpt: excerptAround(et.text, terms),
257
+ currentSession: file === opts.currentFile,
258
+ sameProject: currentDirName !== undefined && dir === currentDirName,
259
+ });
260
+ fileMatches++;
261
+ return fileMatches < MAX_PER_FILE && matches.length < limit;
262
+ });
263
+ bytes += scan.bytes;
264
+ filesScanned++;
265
+ if (signal?.aborted || matches.length >= limit || scan.incomplete) {
266
+ truncated = true;
267
+ break;
268
+ }
269
+ if (scan.oversizedLines > 0) truncated = true;
270
+ }
271
+ return { matches, bytesScanned: bytes, filesScanned, truncated };
272
+ }
273
+
274
+ export async function firstUserTitle(file: string, maxLen = 120): Promise<string | null> {
275
+ let title: string | null = null;
276
+ await scanJsonLines(file, Number.MAX_SAFE_INTEGER, undefined, (line) => {
277
+ const et = entryText(parseJsonLine(line));
278
+ if (et?.role !== "user" || !et.text.trim()) return true;
279
+ title = et.text.length > maxLen ? et.text.slice(0, maxLen) + "…" : et.text;
280
+ return false;
281
+ });
282
+ return title;
283
+ }
284
+
285
+ /** Recent session files in a project dir (encoded cwd), newest first. */
286
+ export function recentSessions(
287
+ sessionDir: string,
288
+ excludeFile: string | undefined,
289
+ count: number,
290
+ ): { file: string; name: string }[] {
291
+ let names: string[];
292
+ try {
293
+ names = fs.readdirSync(sessionDir).filter((n) => n.endsWith(".jsonl"));
294
+ } catch {
295
+ return [];
296
+ }
297
+ const out: { file: string; name: string; mtime: number }[] = [];
298
+ for (const name of names) {
299
+ const file = path.join(sessionDir, name);
300
+ if (file === excludeFile) continue;
301
+ try {
302
+ out.push({ file, name, mtime: fs.statSync(file).mtimeMs });
303
+ } catch {
304
+ /* skip */
305
+ }
306
+ }
307
+ out.sort((a, b) => b.mtime - a.mtime);
308
+ return out.slice(0, count).map(({ file, name }) => ({ file, name }));
309
+ }
310
+
311
+ export function formatResults(query: string, result: Awaited<ReturnType<typeof searchSessions>>): string {
312
+ const note = result.truncated ? "\n(Search incomplete; narrow with the session filter.)" : "";
313
+ if (result.matches.length === 0) {
314
+ return `No matches for "${query}" in ${result.filesScanned} scanned session files.${note}`;
315
+ }
316
+ const lines = result.matches.map(
317
+ (m) =>
318
+ `${m.file}\n[${m.currentSession ? "this session" : m.sameProject ? "this project" : m.project} | ${m.date} | ${m.role}] ${m.excerpt.replace(/\s+/g, " ")}`,
319
+ );
320
+ return `Found ${result.matches.length} match(es) for "${query}" — each hit starts with the session file; read or grep it for full context:\n\n${lines.join("\n\n")}${note}`;
321
+ }
322
+
323
+ export default async function piArchive(pi: ExtensionAPI) {
324
+ const { defineTool } = await import("@earendil-works/pi-coding-agent");
325
+ const { Type } = await import("@earendil-works/pi-ai");
326
+
327
+ const searchArchive = defineTool({
328
+ name: "search_archive",
329
+ label: "Search archive",
330
+ description:
331
+ "Search the full transcript archive of past and current pi sessions — including content that was compacted away. " +
332
+ "Use when the current context is missing a detail: exact code, command output, error messages, or decisions from " +
333
+ "earlier in this session (before compaction) or from previous sessions in this or other projects.",
334
+ parameters: Type.Object({
335
+ query: Type.String({ description: "Search terms; all must appear (case-insensitive)" }),
336
+ session: Type.Optional(
337
+ Type.String({ description: "Only search sessions whose project path contains this, e.g. 'dotfiles'" }),
338
+ ),
339
+ limit: Type.Optional(
340
+ Type.Integer({
341
+ minimum: 1,
342
+ maximum: MAX_SEARCH_LIMIT,
343
+ description: `Max matches (default 20, max ${MAX_SEARCH_LIMIT})`,
344
+ }),
345
+ ),
346
+ }),
347
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
348
+ const sessionDir = ctx.sessionManager.getSessionDir();
349
+ const root = path.dirname(sessionDir);
350
+ const result = await searchSessions(
351
+ root,
352
+ params.query,
353
+ {
354
+ currentFile: ctx.sessionManager.getSessionFile(),
355
+ currentDir: sessionDir,
356
+ sessionFilter: params.session,
357
+ limit: params.limit,
358
+ },
359
+ signal,
360
+ (files, hits) =>
361
+ onUpdate?.({
362
+ content: [{ type: "text", text: `Scanning archive… ${files} files, ${hits} match(es) so far` }],
363
+ details: {},
364
+ }),
365
+ );
366
+ return {
367
+ content: [{ type: "text", text: formatResults(params.query, result) }],
368
+ details: {
369
+ matchCount: result.matches.length,
370
+ filesScanned: result.filesScanned,
371
+ truncated: result.truncated,
372
+ },
373
+ };
374
+ },
375
+ });
376
+ pi.registerTool(searchArchive);
377
+
378
+ // Inject titles only; search_archive retrieves transcript details on demand.
379
+ let memoryInjected = false;
380
+ pi.on("before_agent_start", async (_event, ctx) => {
381
+ if (memoryInjected) return;
382
+ memoryInjected = true;
383
+ const hasConversation = ctx.sessionManager.getEntries().some((e: any) => e.type === "message");
384
+ if (hasConversation) return;
385
+ const sessionDir = ctx.sessionManager.getSessionDir();
386
+ const current = ctx.sessionManager.getSessionFile();
387
+ const recent = recentSessions(sessionDir, current, 5);
388
+ if (recent.length === 0) return;
389
+ const titles = await Promise.all(recent.map(({ file }) => firstUserTitle(file)));
390
+ const lines = recent.map(({ name }, i) => `- ${fileDate(name)}: ${titles[i] ?? "(no user message)"}`);
391
+ return {
392
+ message: {
393
+ customType: "archive-memory",
394
+ content: `[pi-archive] Recent past sessions in this project (retrievable in full via the search_archive tool):\n${lines.join("\n")}`,
395
+ display: false,
396
+ },
397
+ };
398
+ });
399
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@deathbeam/pi-archive",
3
+ "version": "0.0.1",
4
+ "description": "Search and recall past Pi session transcripts",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/deathbeam/pi-packages.git",
10
+ "directory": "packages/pi-archive"
11
+ },
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi-extension"
15
+ ],
16
+ "engines": {
17
+ "node": ">=22.19.0"
18
+ },
19
+ "files": [
20
+ "index.ts",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "pi": {
25
+ "extensions": [
26
+ "./index.ts"
27
+ ]
28
+ },
29
+ "scripts": {
30
+ "test": "node check.mjs"
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-ai": "*",
34
+ "@earendil-works/pi-coding-agent": "*"
35
+ }
36
+ }