opencode-session-searcher 0.0.0-stage → 0.2.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/db.ts ADDED
@@ -0,0 +1,422 @@
1
+ import { Database } from "bun:sqlite"
2
+ import { spawnSync } from "node:child_process"
3
+ import { existsSync } from "node:fs"
4
+ import { homedir } from "node:os"
5
+ import { join } from "node:path"
6
+
7
+ const MAX_ROWS = 500
8
+ const MAX_CHARS = 4000
9
+ const FIRST_KEYWORD = /^\s*(select|with|explain)\b/i
10
+ const WRITE_KEYWORDS = /\b(insert|update|delete|replace|create|drop|alter|attach|detach|vacuum|reindex|analyze|pragma)\b/i
11
+
12
+ export type SqlValue = string | number | null
13
+
14
+ export type QueryResult = {
15
+ columns: string[]
16
+ rows: Record<string, SqlValue>[]
17
+ rowCount: number
18
+ truncatedRows: boolean
19
+ truncatedValues: number
20
+ elapsedMs: number
21
+ }
22
+
23
+ export type PartType = "text" | "reasoning" | "tool" | "step-start"
24
+
25
+ export type DbSession = {
26
+ id: string
27
+ title: SqlValue
28
+ directory: SqlValue
29
+ parentId: SqlValue
30
+ agent: SqlValue
31
+ model: SqlValue
32
+ cost: SqlValue
33
+ tokensInput: SqlValue
34
+ tokensOutput: SqlValue
35
+ timeCreated: number
36
+ timeUpdated: number
37
+ }
38
+
39
+ export type SessionPart = {
40
+ messageId: string
41
+ role: SqlValue
42
+ type: SqlValue
43
+ text: SqlValue
44
+ tool: SqlValue
45
+ status: SqlValue
46
+ toolOutput: SqlValue
47
+ timeCreated: number
48
+ }
49
+
50
+ export type ReadSessionResult = {
51
+ session: DbSession
52
+ parts: SessionPart[]
53
+ truncated: boolean
54
+ elapsedMs: number
55
+ }
56
+
57
+ export type SearchScope = "titles" | "session" | "global"
58
+
59
+ export type SearchMatch = {
60
+ sessionId: string
61
+ title: SqlValue
62
+ directory: SqlValue
63
+ agent: SqlValue
64
+ timeCreated: number
65
+ messageId: SqlValue
66
+ role: SqlValue
67
+ type: SqlValue
68
+ snippet: SqlValue
69
+ }
70
+
71
+ export type SearchResult = {
72
+ scope: SearchScope
73
+ term: string
74
+ /** The words that all had to match (a quoted phrase is one word). */
75
+ words: string[]
76
+ matches: SearchMatch[]
77
+ truncated: boolean
78
+ elapsedMs: number
79
+ }
80
+
81
+ export type DbPathSources = {
82
+ env?: Record<string, string | undefined>
83
+ /** Runs `opencode db path`; returns its trimmed stdout, or null when it fails. */
84
+ opencodeDbPath?: () => string | null
85
+ }
86
+
87
+ function runOpencodeDbPath(): string | null {
88
+ try {
89
+ const result = spawnSync("opencode", ["db", "path"], {
90
+ encoding: "utf8",
91
+ stdio: ["ignore", "pipe", "ignore"],
92
+ timeout: 5000,
93
+ })
94
+ if (result.status !== 0) return null
95
+ return (result.stdout ?? "").trim() || null
96
+ } catch {
97
+ return null
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Resolve the database path, in order:
103
+ * 1. `OPENCODE_DB_PATH`
104
+ * 2. `opencode db path` (opencode's own answer)
105
+ * 3. `${XDG_DATA_HOME ?? ~/.local/share}/opencode/opencode.db`
106
+ */
107
+ export function resolveDbPath(sources: DbPathSources = {}): string {
108
+ const env = sources.env ?? process.env
109
+ const fromEnv = env.OPENCODE_DB_PATH?.trim()
110
+ if (fromEnv) return fromEnv
111
+ const fromCli = (sources.opencodeDbPath ?? runOpencodeDbPath)()
112
+ if (fromCli) return fromCli
113
+ const dataHome = env.XDG_DATA_HOME || join(homedir(), ".local", "share")
114
+ return join(dataHome, "opencode", "opencode.db")
115
+ }
116
+
117
+ let cachedPath: string | undefined
118
+
119
+ /** The resolved database path, looked up once per process. */
120
+ export function dbPath(): string {
121
+ cachedPath ??= resolveDbPath()
122
+ return cachedPath
123
+ }
124
+
125
+ export function openDB(): Database {
126
+ const file = dbPath()
127
+ if (!existsSync(file)) throw new Error(`opencode database not found at ${file}`)
128
+ const db = new Database(file, { readonly: true })
129
+ db.exec("PRAGMA busy_timeout = 5000")
130
+ return db
131
+ }
132
+
133
+ function clamp(n: number | undefined, min: number, max: number, fallback: number): number {
134
+ const value = Math.floor(n ?? fallback)
135
+ if (!Number.isFinite(value)) return fallback
136
+ return Math.min(max, Math.max(min, value))
137
+ }
138
+
139
+ function stripLiterals(sql: string): string {
140
+ let out = ""
141
+ let inString = false
142
+ let inIdent = false
143
+ let inLine = false
144
+ let inBlock = false
145
+ for (let i = 0; i < sql.length; i++) {
146
+ const ch = sql[i]
147
+ if (inLine) {
148
+ if (ch === "\n") {
149
+ inLine = false
150
+ out += ch
151
+ }
152
+ continue
153
+ }
154
+ if (inBlock) {
155
+ if (ch === "*" && sql[i + 1] === "/") {
156
+ inBlock = false
157
+ i++
158
+ }
159
+ continue
160
+ }
161
+ if (inString) {
162
+ if (ch === "'" && sql[i + 1] === "'") {
163
+ i++
164
+ continue
165
+ }
166
+ if (ch === "'") inString = false
167
+ continue
168
+ }
169
+ if (inIdent) {
170
+ if (ch === '"') inIdent = false
171
+ continue
172
+ }
173
+ if (ch === "'") {
174
+ inString = true
175
+ out += " "
176
+ continue
177
+ }
178
+ if (ch === '"') {
179
+ inIdent = true
180
+ out += " "
181
+ continue
182
+ }
183
+ if (ch === "-" && sql[i + 1] === "-") {
184
+ inLine = true
185
+ i++
186
+ continue
187
+ }
188
+ if (ch === "/" && sql[i + 1] === "*") {
189
+ inBlock = true
190
+ i++
191
+ continue
192
+ }
193
+ out += ch
194
+ }
195
+ return out
196
+ }
197
+
198
+ export function validateSql(sql: string): void {
199
+ const stripped = stripLiterals(sql)
200
+ if (!FIRST_KEYWORD.test(stripped)) {
201
+ throw new Error("only a single SELECT, WITH, or EXPLAIN statement is allowed (the connection is read-only)")
202
+ }
203
+ const keyword = WRITE_KEYWORDS.exec(stripped)
204
+ if (keyword) {
205
+ throw new Error(`write keyword "${keyword[0].toLowerCase()}" is not allowed (the connection is read-only)`)
206
+ }
207
+ for (let i = 0; i < stripped.length; i++) {
208
+ if (stripped[i] === ";" && stripped.slice(i + 1).trim() !== "") {
209
+ throw new Error("only a single SQL statement is allowed")
210
+ }
211
+ }
212
+ }
213
+
214
+ function truncateCell(value: unknown, maxChars: number): { value: SqlValue; truncated: boolean } {
215
+ if (value === null || value === undefined) return { value: null, truncated: false }
216
+ if (typeof value === "number") return { value, truncated: false }
217
+ if (typeof value === "bigint") {
218
+ const asNumber = Number(value)
219
+ return { value: Number.isSafeInteger(asNumber) ? asNumber : value.toString(), truncated: false }
220
+ }
221
+ if (value instanceof Uint8Array) return { value: `[blob: ${value.length} bytes]`, truncated: false }
222
+ const str = String(value)
223
+ if (str.length > maxChars) {
224
+ return { value: `${str.slice(0, maxChars)}…[+${str.length - maxChars} chars]`, truncated: true }
225
+ }
226
+ return { value: str, truncated: false }
227
+ }
228
+
229
+ export function query(sql: string, opts: { maxRows?: number; maxChars?: number } = {}): QueryResult {
230
+ validateSql(sql)
231
+ const maxRows = clamp(opts.maxRows, 1, MAX_ROWS, 50)
232
+ const maxChars = clamp(opts.maxChars, 1, MAX_CHARS, 500)
233
+ const db = openDB()
234
+ const started = performance.now()
235
+ try {
236
+ const stmt = db.prepare(sql)
237
+ const columns = [...(stmt.columnNames as string[])]
238
+ const rows: Record<string, SqlValue>[] = []
239
+ let truncatedRows = false
240
+ let truncatedValues = 0
241
+ for (const raw of stmt.iterate() as Iterable<Record<string, unknown>>) {
242
+ if (rows.length === maxRows) {
243
+ truncatedRows = true
244
+ break
245
+ }
246
+ const row: Record<string, SqlValue> = {}
247
+ for (const key of columns) {
248
+ const cell = truncateCell(raw[key], maxChars)
249
+ if (cell.truncated) truncatedValues++
250
+ row[key] = cell.value
251
+ }
252
+ rows.push(row)
253
+ }
254
+ return {
255
+ columns,
256
+ rows,
257
+ rowCount: rows.length,
258
+ truncatedRows,
259
+ truncatedValues,
260
+ elapsedMs: Math.round(performance.now() - started),
261
+ }
262
+ } finally {
263
+ db.close()
264
+ }
265
+ }
266
+
267
+ export function readSession(
268
+ sessionId: string,
269
+ opts: { types?: PartType[]; limit?: number; charsPerPart?: number } = {},
270
+ ): ReadSessionResult {
271
+ const types = opts.types && opts.types.length > 0 ? opts.types : (["text", "reasoning"] as PartType[])
272
+ const limit = clamp(opts.limit, 1, 500, 100)
273
+ const chars = clamp(opts.charsPerPart, 1, 8000, 600)
274
+ const db = openDB()
275
+ const started = performance.now()
276
+ try {
277
+ const session = db
278
+ .prepare(
279
+ "SELECT id, title, directory, parent_id, agent, model, cost, tokens_input, tokens_output, time_created, time_updated FROM session WHERE id = ?",
280
+ )
281
+ .get(sessionId) as any
282
+ if (!session) throw new Error(`session not found: ${sessionId}`)
283
+ const placeholders = types.map(() => "?").join(", ")
284
+ const rows = db
285
+ .prepare(
286
+ `SELECT m.id AS message_id, ` +
287
+ `json_extract(m.data, '$.role') AS role, ` +
288
+ `json_extract(p.data, '$.type') AS type, ` +
289
+ `substr(json_extract(p.data, '$.text'), 1, ?) AS text, ` +
290
+ `json_extract(p.data, '$.tool') AS tool, ` +
291
+ `json_extract(p.data, '$.state.status') AS status, ` +
292
+ `substr(json_extract(p.data, '$.state.output'), 1, ?) AS tool_output, ` +
293
+ `p.time_created AS part_time ` +
294
+ `FROM message m JOIN part p ON p.message_id = m.id ` +
295
+ `WHERE m.session_id = ? AND json_extract(p.data, '$.type') IN (${placeholders}) ` +
296
+ `ORDER BY m.time_created, m.id, p.time_created, p.id LIMIT ?`,
297
+ )
298
+ .all(chars, chars, sessionId, ...types, limit + 1) as any[]
299
+ const truncated = rows.length > limit
300
+ if (truncated) rows.pop()
301
+ const parts: SessionPart[] = rows.map((r) => ({
302
+ messageId: r.message_id,
303
+ role: r.role ?? null,
304
+ type: r.type ?? null,
305
+ text: r.text ?? null,
306
+ tool: r.tool ?? null,
307
+ status: r.status ?? null,
308
+ toolOutput: r.tool_output ?? null,
309
+ timeCreated: r.part_time,
310
+ }))
311
+ const meta: DbSession = {
312
+ id: session.id,
313
+ title: session.title ?? null,
314
+ directory: session.directory ?? null,
315
+ parentId: session.parent_id ?? null,
316
+ agent: session.agent ?? null,
317
+ model: session.model ?? null,
318
+ cost: session.cost ?? null,
319
+ tokensInput: session.tokens_input ?? null,
320
+ tokensOutput: session.tokens_output ?? null,
321
+ timeCreated: session.time_created,
322
+ timeUpdated: session.time_updated,
323
+ }
324
+ return { session: meta, parts, truncated, elapsedMs: Math.round(performance.now() - started) }
325
+ } finally {
326
+ db.close()
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Split a search query into the words that must all match.
332
+ * Whitespace separates words; a double-quoted phrase stays one word.
333
+ * Lowercased and de-duplicated.
334
+ */
335
+ export function splitSearchTerms(query: string): string[] {
336
+ const words: string[] = []
337
+ for (const m of query.matchAll(/"([^"]*)"|(\S+)/g)) {
338
+ const word = (m[1] ?? m[2] ?? "").trim().toLowerCase()
339
+ if (word && !words.includes(word)) words.push(word)
340
+ }
341
+ return words
342
+ }
343
+
344
+ function likePattern(word: string): string {
345
+ return `%${word.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
346
+ }
347
+
348
+ export function searchSessions(
349
+ term: string,
350
+ opts: { sessionId?: string; scope?: SearchScope; limit?: number } = {},
351
+ ): SearchResult {
352
+ const needle = term.trim()
353
+ const words = splitSearchTerms(needle)
354
+ if (words.length === 0) throw new Error("query must be a non-empty search term")
355
+ const scope: SearchScope = opts.scope ?? (opts.sessionId ? "session" : "global")
356
+ if (scope === "session" && !opts.sessionId) {
357
+ throw new Error('scope "session" requires a session_id')
358
+ }
359
+ const limit = clamp(opts.limit, 1, 200, 25)
360
+ const patterns = words.map(likePattern)
361
+ const allLike = (column: string) => words.map(() => `${column} LIKE ? ESCAPE '\\'`).join(" AND ")
362
+ const db = openDB()
363
+ const started = performance.now()
364
+ try {
365
+ if (scope === "titles") {
366
+ const rows = db
367
+ .prepare(
368
+ `SELECT id, title, directory, agent, time_created FROM session WHERE ${allLike("title")} ORDER BY time_updated DESC LIMIT ?`,
369
+ )
370
+ .all(...patterns, limit + 1) as any[]
371
+ const truncated = rows.length > limit
372
+ if (truncated) rows.pop()
373
+ const matches: SearchMatch[] = rows.map((r) => ({
374
+ sessionId: r.id,
375
+ title: r.title ?? null,
376
+ directory: r.directory ?? null,
377
+ agent: r.agent ?? null,
378
+ timeCreated: r.time_created,
379
+ messageId: null,
380
+ role: null,
381
+ type: null,
382
+ snippet: null,
383
+ }))
384
+ return { scope, term: needle, words, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
385
+ }
386
+ const order = scope === "session" ? "ASC" : "DESC"
387
+ const sessionFilter = scope === "session" ? "AND p.session_id = ? " : ""
388
+ const sql =
389
+ `SELECT p.session_id, s.title, s.directory, p.message_id, ` +
390
+ `json_extract(m.data, '$.role') AS role, ` +
391
+ `json_extract(p.data, '$.type') AS type, ` +
392
+ `substr(p.data, max(1, instr(lower(p.data), lower(?)) - 150), 400) AS snippet, ` +
393
+ `p.time_created ` +
394
+ `FROM part p ` +
395
+ `JOIN message m ON m.id = p.message_id ` +
396
+ `JOIN session s ON s.id = p.session_id ` +
397
+ `WHERE ${allLike("p.data")} ${sessionFilter}` +
398
+ `ORDER BY p.time_created ${order} LIMIT ?`
399
+ // The snippet is centred on the first word.
400
+ const params: unknown[] =
401
+ scope === "session"
402
+ ? [words[0], ...patterns, opts.sessionId, limit + 1]
403
+ : [words[0], ...patterns, limit + 1]
404
+ const rows = db.prepare(sql).all(...(params as any[])) as any[]
405
+ const truncated = rows.length > limit
406
+ if (truncated) rows.pop()
407
+ const matches: SearchMatch[] = rows.map((r) => ({
408
+ sessionId: r.session_id,
409
+ title: r.title ?? null,
410
+ directory: r.directory ?? null,
411
+ agent: null,
412
+ timeCreated: r.time_created,
413
+ messageId: r.message_id ?? null,
414
+ role: r.role ?? null,
415
+ type: r.type ?? null,
416
+ snippet: r.snippet ?? null,
417
+ }))
418
+ return { scope, term: needle, words, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
419
+ } finally {
420
+ db.close()
421
+ }
422
+ }