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