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/index.ts ADDED
@@ -0,0 +1,577 @@
1
+ import type { Plugin, PluginModule } from "@opencode-ai/plugin"
2
+ import { tool } from "@opencode-ai/plugin/tool"
3
+ import * as db from "./db"
4
+
5
+ type Depth = "conversation" | "tool" | "both"
6
+
7
+ const SNIPPET_RADIUS = 80
8
+
9
+ type SessionMeta = {
10
+ id: string
11
+ title: string
12
+ created: number
13
+ agent?: string
14
+ model?: string
15
+ parentID?: string
16
+ }
17
+
18
+ type Match = {
19
+ role: string
20
+ snippet: string
21
+ timestamp: number
22
+ }
23
+
24
+ type SessionResult = {
25
+ sessionID: string
26
+ title: string
27
+ date: string
28
+ agent?: string
29
+ model?: string
30
+ matches: Match[]
31
+ }
32
+
33
+ function extractPartTexts(part: any, depth: Depth): string[] {
34
+ const texts: string[] = []
35
+ const includeConversation = depth === "conversation" || depth === "both"
36
+ const includeTool = depth === "tool" || depth === "both"
37
+
38
+ switch (part.type) {
39
+ case "text":
40
+ if (includeConversation && part.text) texts.push(part.text)
41
+ break
42
+
43
+ case "reasoning":
44
+ if (includeConversation && part.text) texts.push(part.text)
45
+ break
46
+
47
+ case "tool":
48
+ if (includeTool && part.state) {
49
+ const state = part.state
50
+ if (state.input && typeof state.input === "object") {
51
+ texts.push(JSON.stringify(state.input))
52
+ }
53
+ if (state.status === "pending" && state.raw) texts.push(state.raw)
54
+ if (state.status === "completed" && state.output) texts.push(state.output)
55
+ if (state.status === "error" && state.error) texts.push(state.error)
56
+ }
57
+ break
58
+ }
59
+
60
+ return texts
61
+ }
62
+
63
+ function buildSnippet(text: string, query: string): string | null {
64
+ const lower = text.toLowerCase()
65
+ const idx = lower.indexOf(query)
66
+ if (idx === -1) return null
67
+
68
+ const start = Math.max(0, idx - SNIPPET_RADIUS)
69
+ const end = Math.min(text.length, idx + query.length + SNIPPET_RADIUS)
70
+ let snippet = text.slice(start, end).replace(/\n/g, " ")
71
+ if (start > 0) snippet = "..." + snippet
72
+ if (end < text.length) snippet = snippet + "..."
73
+ return snippet
74
+ }
75
+
76
+ async function scanSession(
77
+ client: any,
78
+ sessionID: string,
79
+ query: string,
80
+ depth: Depth,
81
+ ): Promise<Match[]> {
82
+ const matches: Match[] = []
83
+
84
+ try {
85
+ const result = await client.session.messages({ path: { id: sessionID } })
86
+ if (!result.data) return matches
87
+
88
+ for (const entry of result.data) {
89
+ const role = entry.info?.role ?? "unknown"
90
+ const timestamp = entry.info?.time?.created ?? 0
91
+
92
+ for (const part of entry.parts ?? []) {
93
+ const texts = extractPartTexts(part, depth)
94
+ for (const text of texts) {
95
+ const snippet = buildSnippet(text, query)
96
+ if (snippet) {
97
+ matches.push({ role, snippet, timestamp })
98
+ }
99
+ }
100
+ }
101
+ }
102
+ } catch {
103
+ // Skip sessions that can't be read (e.g. deleted, corrupted)
104
+ }
105
+
106
+ return matches
107
+ }
108
+
109
+ /** Normalize any session-shaped object into SessionMeta. */
110
+ function mapSession(s: any): SessionMeta {
111
+ return {
112
+ id: s.id,
113
+ title: s.title ?? "Untitled",
114
+ created: s.time?.created ?? 0,
115
+ agent: s.agent ?? undefined,
116
+ model: typeof s.model === "string" ? s.model : (s.model?.id ?? undefined),
117
+ parentID: s.parentID ?? s.parent_id ?? undefined,
118
+ }
119
+ }
120
+
121
+ /** Resolve a single session ID into SessionMeta via the SDK. */
122
+ async function resolveSessionMeta(client: any, sessionID: string): Promise<SessionMeta> {
123
+ try {
124
+ const info = await client.session.get({ path: { id: sessionID } })
125
+ if (info.data) {
126
+ return mapSession(info.data)
127
+ }
128
+ } catch {
129
+ // Fall back to minimal metadata
130
+ }
131
+ return { id: sessionID, title: sessionID, created: 0 }
132
+ }
133
+
134
+ async function fetchGlobalSessions(
135
+ client: any,
136
+ maxSessions: number,
137
+ ): Promise<SessionMeta[]> {
138
+ const sessions: SessionMeta[] = []
139
+ let cursor: string | undefined
140
+ // Access the underlying HTTP client which carries the in-process fetch shim.
141
+ const httpClient = (client as any)._client
142
+
143
+ while (sessions.length < maxSessions) {
144
+ const query: Record<string, string> = {
145
+ roots: "true",
146
+ limit: String(Math.min(maxSessions - sessions.length, 50)),
147
+ // Pass empty directory so the SDK rewrite interceptor skips injecting
148
+ // the project directory, while the server treats "" as falsy (no filter).
149
+ directory: "",
150
+ }
151
+ if (cursor) query.cursor = cursor
152
+
153
+ const result = await httpClient.get({
154
+ url: "/experimental/session",
155
+ query,
156
+ })
157
+
158
+ const data = result.data
159
+ if (!Array.isArray(data)) break
160
+
161
+ for (const s of data) {
162
+ sessions.push(mapSession(s))
163
+ }
164
+
165
+ const nextCursor = result.response?.headers?.get("x-next-cursor")
166
+ if (!nextCursor) break
167
+ cursor = nextCursor
168
+ }
169
+
170
+ return sessions
171
+ }
172
+
173
+ /** Fetch all local sessions via the SDK client. */
174
+ async function fetchLocalSessions(client: any): Promise<SessionMeta[]> {
175
+ const result = await client.session.list()
176
+ const sessions = (result.data ?? []).map(mapSession)
177
+ sessions.sort((a: SessionMeta, b: SessionMeta) => b.created - a.created)
178
+ return sessions
179
+ }
180
+
181
+ function formatResults(results: SessionResult[]): string {
182
+ if (results.length === 0) return "No matches found."
183
+
184
+ const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0)
185
+ const lines: string[] = [
186
+ `Found ${totalMatches} match${totalMatches === 1 ? "" : "es"} across ${results.length} session${results.length === 1 ? "" : "s"}:`,
187
+ "",
188
+ ]
189
+
190
+ for (const result of results) {
191
+ lines.push(
192
+ `## ${result.title} (${result.date}) — ${result.matches.length} match${result.matches.length === 1 ? "" : "es"}`,
193
+ )
194
+ lines.push(`Session ID: ${result.sessionID}`)
195
+ if (result.agent) lines.push(`Agent: ${result.agent}`)
196
+ if (result.model) lines.push(`Model: ${result.model}`)
197
+ for (const match of result.matches.slice(0, 5)) {
198
+ lines.push(`- [${match.role}] ${match.snippet}`)
199
+ }
200
+ if (result.matches.length > 5) {
201
+ lines.push(`- ... and ${result.matches.length - 5} more matches`)
202
+ }
203
+ lines.push("")
204
+ }
205
+
206
+ return lines.join("\n")
207
+ }
208
+
209
+ function formatDate(ms: number): string {
210
+ return new Date(ms).toISOString().slice(0, 10)
211
+ }
212
+
213
+ function formatDbModel(model: db.SqlValue): string | null {
214
+ if (model === null) return null
215
+ const raw = String(model)
216
+ try {
217
+ const parsed = JSON.parse(raw)
218
+ return typeof parsed === "object" && parsed !== null && typeof parsed.id === "string" ? parsed.id : raw
219
+ } catch {
220
+ return raw
221
+ }
222
+ }
223
+
224
+ function formatDbSessionRead(result: db.ReadSessionResult): string {
225
+ const s = result.session
226
+ const lines: string[] = [`## ${s.title ?? "Untitled"}`, `Session: ${s.id}`]
227
+ if (s.directory) lines.push(`Directory: ${s.directory}`)
228
+ const idents: string[] = []
229
+ if (s.agent) idents.push(`Agent: ${s.agent}`)
230
+ const model = formatDbModel(s.model)
231
+ if (model) idents.push(`Model: ${model}`)
232
+ if (idents.length > 0) lines.push(idents.join(" | "))
233
+ lines.push(`Created: ${formatDate(s.timeCreated)} | Updated: ${formatDate(s.timeUpdated)}`)
234
+ if (s.cost !== null) {
235
+ lines.push(`Cost: $${Number(s.cost).toFixed(4)} | Tokens in/out: ${s.tokensInput ?? 0}/${s.tokensOutput ?? 0}`)
236
+ }
237
+ lines.push(`Parts: ${result.parts.length}${result.truncated ? " (truncated — raise limit for more)" : ""}`)
238
+ lines.push("")
239
+ for (const part of result.parts) {
240
+ const time = new Date(part.timeCreated).toISOString().slice(11, 19)
241
+ const label = part.tool
242
+ ? `${part.role ?? "?"}/${part.type ?? "?"} ${part.tool}${part.status ? ` → ${part.status}` : ""}`
243
+ : `${part.role ?? "?"}/${part.type ?? "?"}`
244
+ lines.push(`[${time} ${label}]`)
245
+ if (part.text) lines.push(String(part.text))
246
+ if (part.toolOutput) lines.push(String(part.toolOutput))
247
+ lines.push("")
248
+ }
249
+ return lines.join("\n")
250
+ }
251
+
252
+ function formatDbSearch(result: db.SearchResult): string {
253
+ const header =
254
+ `Scope: ${result.scope} | Term: "${result.term}" | ` +
255
+ `${result.matches.length} match${result.matches.length === 1 ? "" : "es"} in ${result.elapsedMs} ms` +
256
+ (result.truncated ? " (capped at limit)" : "")
257
+ if (result.matches.length === 0) return `${header}\n\nNo matches found.`
258
+ const lines: string[] = [header, ""]
259
+ for (const m of result.matches) {
260
+ const date = new Date(m.timeCreated).toISOString().slice(0, 16).replace("T", " ")
261
+ if (result.scope === "titles") {
262
+ lines.push(`## ${m.title ?? "Untitled"} (${date}) — ${m.sessionId}`)
263
+ if (m.directory) lines.push(`Directory: ${m.directory}`)
264
+ } else {
265
+ lines.push(`- ${date} [${m.role ?? "?"}/${m.type ?? "?"}] ${m.title ?? "Untitled"} — ${m.sessionId}`)
266
+ if (m.directory) lines.push(` ${m.directory}`)
267
+ if (m.snippet) lines.push(` ${String(m.snippet).replace(/\s+/g, " ").trim()}`)
268
+ }
269
+ }
270
+ return lines.join("\n")
271
+ }
272
+
273
+ function formatSessionList(sessions: SessionMeta[]): string {
274
+ if (sessions.length === 0) return "No sessions found."
275
+
276
+ const lines: string[] = [
277
+ `Found ${sessions.length} session${sessions.length === 1 ? "" : "s"}:`,
278
+ "",
279
+ ]
280
+
281
+ for (const s of sessions) {
282
+ lines.push(`## ${s.title}`)
283
+ lines.push(`ID: ${s.id}`)
284
+ lines.push(`Created: ${formatDate(s.created)}`)
285
+ if (s.parentID) lines.push(`Parent: ${s.parentID}`)
286
+ if (s.agent) lines.push(`Agent: ${s.agent}`)
287
+ if (s.model) lines.push(`Model: ${s.model}`)
288
+ lines.push("")
289
+ }
290
+
291
+ return lines.join("\n")
292
+ }
293
+
294
+ const plugin: Plugin = async (ctx) => ({
295
+ tool: {
296
+ search_sessions: tool({
297
+ description:
298
+ "Search past session history by message content. " +
299
+ "Scans session messages for a text query and returns matching snippets. " +
300
+ "Use to recall previous conversations, find when a topic was discussed, " +
301
+ "or locate past solutions. " +
302
+ "Pass session_id or session_ids to target specific sessions. " +
303
+ "Pass parent_session_id to search only child sessions of a parent.",
304
+ args: {
305
+ query: tool.schema.string().describe("Search term (case-insensitive substring match)"),
306
+ session_id: tool.schema
307
+ .string()
308
+ .optional()
309
+ .describe(
310
+ "Search only this specific session (by session ID). " +
311
+ "When set, session_ids, parent_session_id, global, and max_sessions are ignored.",
312
+ ),
313
+ session_ids: tool.schema
314
+ .array(tool.schema.string())
315
+ .optional()
316
+ .describe(
317
+ "Search a specific set of sessions by ID. " +
318
+ "When set, parent_session_id, global, and max_sessions are ignored.",
319
+ ),
320
+ parent_session_id: tool.schema
321
+ .string()
322
+ .optional()
323
+ .describe(
324
+ "Search only child sessions of this parent session ID. " +
325
+ "Lists sessions and filters to those whose parentID matches. " +
326
+ "Combines with global to search children across all projects.",
327
+ ),
328
+ global: tool.schema
329
+ .boolean()
330
+ .optional()
331
+ .describe("Search across all projects instead of just the current one (default: false)"),
332
+ depth: tool.schema
333
+ .enum(["conversation", "tool", "both"])
334
+ .optional()
335
+ .describe(
336
+ 'What to search: "conversation" for user/assistant text (default), ' +
337
+ '"tool" for tool inputs/outputs, "both" for everything',
338
+ ),
339
+ limit: tool.schema
340
+ .number()
341
+ .optional()
342
+ .describe("Max sessions to return in results (default: 5)"),
343
+ max_sessions: tool.schema
344
+ .number()
345
+ .optional()
346
+ .describe("Max sessions to scan (default: 20)"),
347
+ },
348
+ async execute(args) {
349
+ const query = args.query.toLowerCase()
350
+ const depth: Depth = args.depth ?? "conversation"
351
+ const limit = args.limit ?? 5
352
+ const maxSessions = args.max_sessions ?? 20
353
+
354
+ let sessions: SessionMeta[]
355
+
356
+ if (args.session_id) {
357
+ // Single session — resolve metadata, ignore other filters
358
+ sessions = [await resolveSessionMeta(ctx.client, args.session_id)]
359
+ } else if (args.session_ids && args.session_ids.length > 0) {
360
+ // Batch of specific sessions — resolve each in parallel
361
+ sessions = await Promise.all(
362
+ args.session_ids.map((id) => resolveSessionMeta(ctx.client, id)),
363
+ )
364
+ } else if (args.parent_session_id) {
365
+ // Find children of a parent — fetch all, then filter by parentID
366
+ const allSessions = args.global
367
+ ? await fetchGlobalSessions(ctx.client, 500)
368
+ : await fetchLocalSessions(ctx.client)
369
+ sessions = allSessions.filter((s) => s.parentID === args.parent_session_id)
370
+ } else if (args.global) {
371
+ sessions = await fetchGlobalSessions(ctx.client, maxSessions)
372
+ } else {
373
+ const allSessions = await fetchLocalSessions(ctx.client)
374
+ sessions = allSessions.slice(0, maxSessions)
375
+ }
376
+
377
+ const results: SessionResult[] = []
378
+
379
+ for (const session of sessions) {
380
+ const matches = await scanSession(ctx.client, session.id, query, depth)
381
+ if (matches.length > 0) {
382
+ results.push({
383
+ sessionID: session.id,
384
+ title: session.title,
385
+ date: formatDate(session.created),
386
+ agent: session.agent,
387
+ model: session.model,
388
+ matches,
389
+ })
390
+ }
391
+ }
392
+
393
+ results.sort((a, b) => b.matches.length - a.matches.length)
394
+ const topResults = results.slice(0, limit)
395
+ const totalMatches = topResults.reduce((sum, r) => sum + r.matches.length, 0)
396
+
397
+ return {
398
+ title: `Searched ${sessions.length} sessions, found ${totalMatches} matches in ${topResults.length} sessions`,
399
+ output: formatResults(topResults),
400
+ metadata: {
401
+ scanned: sessions.length,
402
+ matchingSessions: topResults.length,
403
+ totalMatches,
404
+ },
405
+ }
406
+ },
407
+ }),
408
+
409
+ list_sessions: tool({
410
+ description:
411
+ "List sessions with metadata (title, agent, model, parent ID). " +
412
+ "Use to discover session IDs, find child sessions of a parent, or " +
413
+ "orient before searching. Does not scan message content — use search_sessions for that.",
414
+ args: {
415
+ parent_session_id: tool.schema
416
+ .string()
417
+ .optional()
418
+ .describe("Filter to child sessions of this parent session ID."),
419
+ global: tool.schema
420
+ .boolean()
421
+ .optional()
422
+ .describe("List sessions across all projects instead of just the current one (default: false)"),
423
+ max_sessions: tool.schema
424
+ .number()
425
+ .optional()
426
+ .describe("Max sessions to return (default: 50)"),
427
+ },
428
+ async execute(args) {
429
+ const maxSessions = args.max_sessions ?? 50
430
+
431
+ let sessions: SessionMeta[]
432
+
433
+ if (args.global) {
434
+ sessions = await fetchGlobalSessions(ctx.client, args.parent_session_id ? 500 : maxSessions)
435
+ } else {
436
+ sessions = await fetchLocalSessions(ctx.client)
437
+ }
438
+
439
+ if (args.parent_session_id) {
440
+ sessions = sessions.filter((s) => s.parentID === args.parent_session_id)
441
+ }
442
+
443
+ sessions = sessions.slice(0, maxSessions)
444
+
445
+ return {
446
+ title: `Found ${sessions.length} session${sessions.length === 1 ? "" : "s"}`,
447
+ output: formatSessionList(sessions),
448
+ metadata: {
449
+ count: sessions.length,
450
+ },
451
+ }
452
+ },
453
+ }),
454
+
455
+ db_query: tool({
456
+ description:
457
+ "Run a single read-only SQL statement (SELECT, WITH, or EXPLAIN) directly against opencode's local SQLite session database. " +
458
+ "Read-only is enforced at the engine level — writes are impossible. " +
459
+ "Returns JSON rows, one per line, capped at max_rows rows and max_chars characters per value. " +
460
+ "Discover the schema with: SELECT sql FROM sqlite_master WHERE type = 'table'. " +
461
+ "Core tables: session, message, part (message and part have a `data` JSON column; timestamps are epoch milliseconds). " +
462
+ "Fastest path for structured session-history questions: joins, counts, tool-call history, todos, cost rollups. " +
463
+ "Never select part.data unbounded — tool outputs can be megabytes; use substr(json_extract(...), 1, N). " +
464
+ "Use db_read_session to read a conversation, db_search for substring search.",
465
+ args: {
466
+ sql: tool.schema
467
+ .string()
468
+ .describe("Single SQL statement (SELECT/WITH/EXPLAIN only). Timestamps are epoch milliseconds."),
469
+ max_rows: tool.schema.number().optional().describe("Max rows to return (default: 50, max: 500)"),
470
+ max_chars: tool.schema
471
+ .number()
472
+ .optional()
473
+ .describe("Max characters per cell value, truncated with a marker (default: 500, max: 4000)"),
474
+ },
475
+ async execute(args) {
476
+ const result = db.query(args.sql, { maxRows: args.max_rows, maxChars: args.max_chars })
477
+ const lines: string[] = [
478
+ `${result.rowCount} row${result.rowCount === 1 ? "" : "s"} in ${result.elapsedMs} ms` +
479
+ (result.truncatedRows ? " (row-capped)" : "") +
480
+ (result.truncatedValues > 0 ? ` (${result.truncatedValues} values truncated)` : ""),
481
+ ]
482
+ for (const row of result.rows) lines.push(JSON.stringify(row))
483
+ return {
484
+ title: `${result.rowCount} row(s) in ${result.elapsedMs}ms`,
485
+ output: lines.join("\n"),
486
+ metadata: {
487
+ rowCount: result.rowCount,
488
+ truncatedRows: result.truncatedRows,
489
+ truncatedValues: result.truncatedValues,
490
+ elapsedMs: result.elapsedMs,
491
+ },
492
+ }
493
+ },
494
+ }),
495
+
496
+ db_read_session: tool({
497
+ description:
498
+ "Read a session's conversation directly from the database: every part of every message in chronological order, " +
499
+ "rendered as readable text with roles and part types. " +
500
+ 'Defaults to text + reasoning parts; include "tool" for tool calls with their outputs, "step-start" for step boundaries. ' +
501
+ "Completes in milliseconds regardless of session size. Use to recall exactly what happened in a past session.",
502
+ args: {
503
+ session_id: tool.schema.string().describe("Session ID (ses_...)"),
504
+ types: tool.schema
505
+ .array(tool.schema.enum(["text", "reasoning", "tool", "step-start"]))
506
+ .optional()
507
+ .describe('Part types to include (default: ["text", "reasoning"])'),
508
+ limit: tool.schema
509
+ .number()
510
+ .optional()
511
+ .describe("Max parts to return in chronological order (default: 100, max: 500)"),
512
+ chars_per_part: tool.schema
513
+ .number()
514
+ .optional()
515
+ .describe("Max characters per part, truncated with a marker (default: 600, max: 8000)"),
516
+ },
517
+ async execute(args) {
518
+ const result = db.readSession(args.session_id, {
519
+ types: args.types,
520
+ limit: args.limit,
521
+ charsPerPart: args.chars_per_part,
522
+ })
523
+ return {
524
+ title: `${result.parts.length} parts from "${result.session.title ?? result.session.id}" in ${result.elapsedMs}ms`,
525
+ output: formatDbSessionRead(result),
526
+ metadata: {
527
+ sessionId: result.session.id,
528
+ parts: result.parts.length,
529
+ truncated: result.truncated,
530
+ elapsedMs: result.elapsedMs,
531
+ },
532
+ }
533
+ },
534
+ }),
535
+
536
+ db_search: tool({
537
+ description:
538
+ "Substring search over session content, tiered by scope. " +
539
+ '"titles": session titles only — instant. ' +
540
+ '"session": every part of one session — milliseconds (requires session_id). ' +
541
+ '"global": every part of every session — full table scan, typically 10–30 seconds; narrow first (titles, project, session) when possible. ' +
542
+ 'Default scope: "session" when session_id is given, otherwise "global". ' +
543
+ "Matches conversation text, reasoning, and tool inputs/outputs. Returns snippets with session titles and roles.",
544
+ args: {
545
+ query: tool.schema.string().describe("Search term (case-insensitive substring; % and _ match literally)"),
546
+ session_id: tool.schema
547
+ .string()
548
+ .optional()
549
+ .describe('Restrict search to this session (required and implied for scope "session")'),
550
+ scope: tool.schema
551
+ .enum(["titles", "session", "global"])
552
+ .optional()
553
+ .describe('Search scope: "titles" (instant), "session" (ms), "global" (full scan, 10-30s)'),
554
+ limit: tool.schema.number().optional().describe("Max matches to return (default: 25, max: 200)"),
555
+ },
556
+ async execute(args) {
557
+ const result = db.searchSessions(args.query, {
558
+ sessionId: args.session_id,
559
+ scope: args.scope,
560
+ limit: args.limit,
561
+ })
562
+ return {
563
+ title: `${result.matches.length} match(es) in ${result.scope} scope in ${result.elapsedMs}ms`,
564
+ output: formatDbSearch(result),
565
+ metadata: {
566
+ scope: result.scope,
567
+ matches: result.matches.length,
568
+ truncated: result.truncated,
569
+ elapsedMs: result.elapsedMs,
570
+ },
571
+ }
572
+ },
573
+ }),
574
+ },
575
+ })
576
+
577
+ export default { id: "session-search", server: plugin } satisfies PluginModule