-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprovider_opencode.go
More file actions
545 lines (487 loc) · 12.8 KB
/
Copy pathprovider_opencode.go
File metadata and controls
545 lines (487 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package main
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
_ "modernc.org/sqlite"
)
// OpenCodeProvider loads sessions from OpenCode's SQLite database.
type OpenCodeProvider struct {
dbPath string
}
func NewOpenCodeProvider() *OpenCodeProvider {
home, _ := os.UserHomeDir()
return &OpenCodeProvider{
dbPath: filepath.Join(home, ".local", "share", "opencode", "opencode.db"),
}
}
func (p *OpenCodeProvider) Name() string { return "OpenCode" }
func (p *OpenCodeProvider) Available() bool {
return fileExists(p.dbPath)
}
func (p *OpenCodeProvider) openDB() (*sql.DB, error) {
return sql.Open("sqlite", p.dbPath+"?mode=ro&_journal_mode=WAL")
}
func (p *OpenCodeProvider) LoadTree() (*TreeData, error) {
db, err := p.openDB()
if err != nil {
return nil, fmt.Errorf("opencode db: %w", err)
}
defer db.Close()
data := &TreeData{}
// Load projects
projRows, err := db.Query(`SELECT id, worktree, name, time_created, time_updated FROM project ORDER BY time_updated DESC`)
if err != nil {
return nil, fmt.Errorf("opencode projects: %w", err)
}
defer projRows.Close()
type dbProject struct {
id string
worktree string
name sql.NullString
timeCreated int64
timeUpdated int64
}
var dbProjects []dbProject
for projRows.Next() {
var dp dbProject
if err := projRows.Scan(&dp.id, &dp.worktree, &dp.name, &dp.timeCreated, &dp.timeUpdated); err != nil {
continue
}
dbProjects = append(dbProjects, dp)
}
for _, dp := range dbProjects {
proj := TreeProject{
DirName: dp.id,
DirPath: dp.worktree,
Source: "opencode",
}
if dp.name.Valid && dp.name.String != "" {
proj.DisplayName = dp.name.String
} else {
proj.DisplayName = shortenPath(dp.worktree)
}
// Load sessions for this project
sessRows, err := db.Query(`
SELECT s.id, s.title, s.slug, s.directory, s.time_created, s.time_updated, s.parent_id,
(SELECT COUNT(*) FROM message m WHERE m.session_id = s.id) as msg_count
FROM session s
WHERE s.project_id = ? AND s.parent_id IS NULL AND s.time_archived IS NULL
ORDER BY s.time_updated DESC
`, dp.id)
if err != nil {
continue
}
var latestTime int64
for sessRows.Next() {
var (
sid, title, slug, dir string
created, updated int64
parentID sql.NullString
msgCount int
)
if err := sessRows.Scan(&sid, &title, &slug, &dir, &created, &updated, &parentID, &msgCount); err != nil {
continue
}
if updated > latestTime {
latestTime = updated
}
modTime := time.UnixMilli(updated).Format(time.RFC3339)
conv := TreeConversation{
SessionID: sid,
Path: sid, // For OpenCode, path is the session ID
ModTime: modTime,
Title: title,
Slug: slug,
CWD: dir,
MsgCount: msgCount,
Source: "opencode",
}
// Get preview from first user message
conv.Preview = p.getSessionPreview(db, sid)
// Load child sessions (subagents)
conv.SubAgents = p.loadChildSessions(db, sid)
proj.Conversations = append(proj.Conversations, conv)
proj.MsgCount += msgCount
}
sessRows.Close()
proj.ConvCount = len(proj.Conversations)
if latestTime > 0 {
proj.LastActive = time.UnixMilli(latestTime).Format(time.RFC3339)
}
if proj.ConvCount > 0 {
data.Projects = append(data.Projects, proj)
}
}
// Compute stats
for _, p := range data.Projects {
data.Stats.TotalProjects++
data.Stats.TotalConversations += p.ConvCount
data.Stats.TotalMessages += p.MsgCount
}
return data, nil
}
func (p *OpenCodeProvider) getSessionPreview(db *sql.DB, sessionID string) string {
var msgData string
err := db.QueryRow(`
SELECT m.data FROM message m
WHERE m.session_id = ? AND json_extract(m.data, '$.role') = 'user'
ORDER BY m.time_created ASC LIMIT 1
`, sessionID).Scan(&msgData)
if err != nil {
return ""
}
// Get first text part for this message
var msgID string
// Extract message ID from data or use a different approach
err = db.QueryRow(`
SELECT m.id FROM message m
WHERE m.session_id = ? AND json_extract(m.data, '$.role') = 'user'
ORDER BY m.time_created ASC LIMIT 1
`, sessionID).Scan(&msgID)
if err != nil {
return ""
}
var partData string
err = db.QueryRow(`
SELECT data FROM part
WHERE message_id = ? AND json_extract(data, '$.type') = 'text'
ORDER BY time_created ASC LIMIT 1
`, msgID).Scan(&partData)
if err != nil {
return ""
}
var part struct {
Text string `json:"text"`
}
if json.Unmarshal([]byte(partData), &part) != nil {
return ""
}
text := strings.ReplaceAll(part.Text, "\n", " ")
text = strings.Join(strings.Fields(text), " ")
if len(text) > 100 {
text = text[:97] + "..."
}
return text
}
func (p *OpenCodeProvider) loadChildSessions(db *sql.DB, parentID string) []TreeSubAgent {
rows, err := db.Query(`
SELECT s.id, s.title, s.slug, s.time_updated,
(SELECT COUNT(*) FROM message m WHERE m.session_id = s.id) as msg_count
FROM session s
WHERE s.parent_id = ?
ORDER BY s.time_created ASC
`, parentID)
if err != nil {
return nil
}
defer rows.Close()
var agents []TreeSubAgent
for rows.Next() {
var (
sid, title, slug string
updated int64
msgCount int
)
if err := rows.Scan(&sid, &title, &slug, &updated, &msgCount); err != nil {
continue
}
name := slug
if name == "" {
name = title
}
if len(name) > 40 {
name = name[:37] + "..."
}
agents = append(agents, TreeSubAgent{
Name: name,
Path: sid,
ModTime: time.UnixMilli(updated).Format(time.RFC3339),
MsgCount: msgCount,
})
}
return agents
}
func (p *OpenCodeProvider) LoadConversation(sessionID string) ([]Entry, error) {
db, err := p.openDB()
if err != nil {
return nil, err
}
defer db.Close()
// Load messages ordered by creation time
msgRows, err := db.Query(`
SELECT m.id, m.data, m.time_created
FROM message m
WHERE m.session_id = ?
ORDER BY m.time_created ASC
`, sessionID)
if err != nil {
return nil, err
}
defer msgRows.Close()
var entries []Entry
for msgRows.Next() {
var (
msgID string
msgData string
created int64
)
if err := msgRows.Scan(&msgID, &msgData, &created); err != nil {
continue
}
entry, err := p.convertMessage(db, msgID, msgData, created)
if err != nil {
continue
}
entries = append(entries, entry)
}
return entries, nil
}
// ocMessageData represents the JSON structure in OpenCode's message.data column.
type ocMessageData struct {
Role string `json:"role"`
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
Mode string `json:"mode"`
Agent string `json:"agent"`
Finish string `json:"finish"`
Time struct {
Created int64 `json:"created"`
Completed int64 `json:"completed"`
} `json:"time"`
Path struct {
CWD string `json:"cwd"`
Root string `json:"root"`
} `json:"path"`
Tokens struct {
Total int `json:"total"`
Input int `json:"input"`
Output int `json:"output"`
Reasoning int `json:"reasoning"`
Cache struct {
Read int `json:"read"`
Write int `json:"write"`
} `json:"cache"`
} `json:"tokens"`
}
func (p *OpenCodeProvider) convertMessage(db *sql.DB, msgID, msgData string, created int64) (Entry, error) {
var md ocMessageData
if err := json.Unmarshal([]byte(msgData), &md); err != nil {
return Entry{}, err
}
ts := time.UnixMilli(created).Format(time.RFC3339)
entry := Entry{
Type: md.Role,
UUID: msgID,
Timestamp: ts,
CWD: md.Path.CWD,
}
// Build content blocks from parts
partRows, err := db.Query(`
SELECT data FROM part
WHERE message_id = ?
ORDER BY time_created ASC
`, msgID)
if err != nil {
return entry, nil
}
defer partRows.Close()
var blocks []ContentBlock
var usage *Usage
for partRows.Next() {
var partData string
if err := partRows.Scan(&partData); err != nil {
continue
}
var partType struct {
Type string `json:"type"`
}
if json.Unmarshal([]byte(partData), &partType) != nil {
continue
}
switch partType.Type {
case "text":
var tp struct {
Text string `json:"text"`
}
if json.Unmarshal([]byte(partData), &tp) == nil && tp.Text != "" {
blocks = append(blocks, ContentBlock{Type: "text", Text: tp.Text})
}
case "tool":
var tp struct {
CallID string `json:"callID"`
Tool string `json:"tool"`
State struct {
Status string `json:"status"`
Input json.RawMessage `json:"input"`
Output string `json:"output"`
} `json:"state"`
}
if json.Unmarshal([]byte(partData), &tp) == nil {
blocks = append(blocks, ContentBlock{
Type: "tool_use",
Name: capitalizeToolName(tp.Tool),
ID: tp.CallID,
Input: tp.State.Input,
})
}
case "reasoning":
var tp struct {
Text string `json:"text"`
}
if json.Unmarshal([]byte(partData), &tp) == nil && tp.Text != "" {
blocks = append(blocks, ContentBlock{Type: "thinking", Thinking: tp.Text})
}
case "step-finish":
var tp struct {
Tokens struct {
Total int `json:"total"`
Input int `json:"input"`
Output int `json:"output"`
Reasoning int `json:"reasoning"`
Cache struct {
Read int `json:"read"`
Write int `json:"write"`
} `json:"cache"`
} `json:"tokens"`
}
if json.Unmarshal([]byte(partData), &tp) == nil && tp.Tokens.Total > 0 {
usage = &Usage{
InputTokens: tp.Tokens.Input,
OutputTokens: tp.Tokens.Output,
CacheReadInputTokens: tp.Tokens.Cache.Read,
}
}
case "file":
var tp struct {
Filename string `json:"filename"`
URL string `json:"url"`
}
if json.Unmarshal([]byte(partData), &tp) == nil && tp.Filename != "" {
blocks = append(blocks, ContentBlock{
Type: "text",
Text: fmt.Sprintf("📎 %s", tp.Filename),
})
}
case "patch":
var tp struct {
Files []string `json:"files"`
}
if json.Unmarshal([]byte(partData), &tp) == nil && len(tp.Files) > 0 {
fileList := make([]string, len(tp.Files))
for i, f := range tp.Files {
fileList[i] = shortenPath(f)
}
blocks = append(blocks, ContentBlock{
Type: "text",
Text: fmt.Sprintf("[patch] %s", strings.Join(fileList, ", ")),
})
}
}
}
// Build the ParsedMessage
contentJSON, _ := json.Marshal(blocks)
pm := &ParsedMessage{
Role: md.Role,
Model: md.ModelID,
Usage: usage,
}
pm.Content = contentJSON
entry.Parsed = pm
return entry, nil
}
// capitalizeToolName maps opencode tool names to display-friendly names.
func capitalizeToolName(name string) string {
mapping := map[string]string{
"read": "Read",
"write": "Write",
"edit": "Edit",
"bash": "Bash",
"grep": "Grep",
"glob": "Glob",
"agent": "Agent",
"skill": "Skill",
"fetch": "Fetch",
"list_files": "ListFiles",
"search": "Search",
"todoread": "TodoRead",
"todowrite": "TodoWrite",
}
if mapped, ok := mapping[name]; ok {
return mapped
}
// Capitalize first letter
if len(name) > 0 {
return strings.ToUpper(name[:1]) + name[1:]
}
return name
}
func (p *OpenCodeProvider) SearchSessions(query, projectID string) []SearchResult {
db, err := p.openDB()
if err != nil {
return nil
}
defer db.Close()
q := "%" + query + "%"
var rows *sql.Rows
if projectID != "" {
rows, err = db.Query(`
SELECT s.id, s.title, s.slug, s.directory, s.time_updated, p.worktree, p.name
FROM session s
JOIN project p ON s.project_id = p.id
WHERE s.project_id = ? AND s.parent_id IS NULL AND s.time_archived IS NULL
AND (s.title LIKE ? OR s.slug LIKE ?)
ORDER BY s.time_updated DESC
LIMIT 50
`, projectID, q, q)
} else {
rows, err = db.Query(`
SELECT s.id, s.title, s.slug, s.directory, s.time_updated, p.worktree, p.name
FROM session s
JOIN project p ON s.project_id = p.id
WHERE s.parent_id IS NULL AND s.time_archived IS NULL
AND (s.title LIKE ? OR s.slug LIKE ? OR p.worktree LIKE ?)
ORDER BY s.time_updated DESC
LIMIT 50
`, q, q, q)
}
if err != nil {
return nil
}
defer rows.Close()
var results []SearchResult
for rows.Next() {
var (
sid, title, slug, dir string
updated int64
worktree string
projName sql.NullString
)
if err := rows.Scan(&sid, &title, &slug, &dir, &updated, &worktree, &projName); err != nil {
continue
}
displayName := shortenPath(worktree)
if projName.Valid && projName.String != "" {
displayName = projName.String
}
results = append(results, SearchResult{
Source: "opencode",
ProjectName: displayName,
Title: title,
Path: sid,
ModTime: time.UnixMilli(updated).Format(time.RFC3339),
})
}
return results
}
// sortSearchResults sorts results by modification time (newest first).
func sortSearchResults(results []SearchResult) {
sort.Slice(results, func(i, j int) bool {
return results[i].ModTime > results[j].ModTime
})
}