forked from kenn-io/agentsview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode.go
More file actions
1725 lines (1591 loc) · 44.2 KB
/
Copy pathopencode.go
File metadata and controls
1725 lines (1591 loc) · 44.2 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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package parser
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/tidwall/gjson"
)
const openCodeStorageFingerprintPrefix = "opencode-storage:v1:"
// OpenCodeSessionMeta is lightweight metadata for a session,
// used to detect changes without parsing messages or parts.
type OpenCodeSessionMeta struct {
SessionID string
VirtualPath string
FileMtime int64
// CompositeMtime reports that FileMtime is the per-session composite
// (see openCodeCompositeMtimeExpr) rather than the session row's own
// time_updated. When true the fingerprint omits the shared container's
// size, because the composite already discriminates per session.
CompositeMtime bool
}
// OpenCodeSQLiteSessionExists reports whether a session row with
// the given ID is present in the OpenCode SQLite database at
// dbPath. Returns false when the file is missing, the schema is
// unexpected, or no row matches. Used by the OpenCode-format
// provider's source lookup so callers can distinguish "this DB has
// the session" from
// "this DB exists but doesn't have it" — the latter must let
// resolution continue to other configured roots.
func OpenCodeSQLiteSessionExists(dbPath, sessionID string) bool {
if dbPath == "" || sessionID == "" {
return false
}
info, err := os.Stat(dbPath)
if err != nil || info.IsDir() {
return false
}
db, err := openOpenCodeDB(dbPath)
if err != nil {
return false
}
defer db.Close()
var found int
err = db.QueryRow(
"SELECT 1 FROM session WHERE id = ? LIMIT 1",
sessionID,
).Scan(&found)
return err == nil
}
// ListOpenCodeSessionMeta returns lightweight metadata for
// all sessions without parsing messages or parts. Used by
// the sync engine to detect which sessions have changed.
func ListOpenCodeSessionMeta(
dbPath string,
) ([]OpenCodeSessionMeta, error) {
var metas []OpenCodeSessionMeta
err := ForEachOpenCodeSessionMeta(
context.Background(), dbPath,
func(meta OpenCodeSessionMeta) error {
metas = append(metas, meta)
return nil
},
)
return metas, err
}
// ForEachOpenCodeSessionMeta streams lightweight session rows directly from
// SQLite. The callback runs while the read-only query is open and receives one
// row at a time; callers must not retain database-owned values.
func ForEachOpenCodeSessionMeta(
ctx context.Context,
dbPath string,
yield func(OpenCodeSessionMeta) error,
) error {
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return nil
}
db, err := openOpenCodeDB(dbPath)
if err != nil {
return err
}
defer db.Close()
composite, err := openCodeCompositeMtimeSupportedCached(db, dbPath)
if err != nil {
return err
}
query := "SELECT s.id, s.time_updated FROM session s"
if composite {
query = "SELECT s.id, " + openCodeCompositeMtimeExpr +
" FROM session s" + openCodeCompositeMtimeJoins
}
rows, err := db.QueryContext(ctx, query)
if err != nil {
return fmt.Errorf(
"listing opencode sessions: %w", err,
)
}
defer rows.Close()
for rows.Next() {
var id string
var timeUpdated int64
if err := rows.Scan(
&id, &timeUpdated,
); err != nil {
return fmt.Errorf(
"scanning opencode session meta: %w", err,
)
}
observeStreamingDiscoveryBuffer(ctx, 1)
if err := yield(OpenCodeSessionMeta{
SessionID: id,
VirtualPath: dbPath + "#" + id,
FileMtime: timeUpdated * 1_000_000,
CompositeMtime: composite,
}); err != nil {
return err
}
}
return rows.Err()
}
// openCodeSessionCompositeMtime returns one session's composite change signal
// in milliseconds, and whether the container schema supports it. Discovery,
// single-session source lookup, and the parse path all resolve mtime through
// this so a session's stored file_mtime always equals the value the freshness
// gate compares it against.
func openCodeSessionCompositeMtime(
db *sql.DB, dbPath, sessionID string,
) (int64, bool, error) {
composite, err := openCodeCompositeMtimeSupportedCached(db, dbPath)
if err != nil {
return 0, false, err
}
query := "SELECT s.time_updated FROM session s WHERE s.id = ?"
if composite {
query = "SELECT " + openCodeCompositeMtimeExpr +
" FROM session s" + openCodeCompositeMtimeJoins +
" WHERE s.id = ?"
}
var timeUpdated int64
if err := db.QueryRow(query, sessionID).Scan(&timeUpdated); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, composite, nil
}
return 0, composite, fmt.Errorf(
"loading opencode session mtime %s#%s: %w",
dbPath, sessionID, err,
)
}
return timeUpdated, composite, nil
}
// parseOpenCodeDBSession parses a single session by ID from the
// OpenCode SQLite database. The OpenCode-format provider owns this
// path; Kilo and MiMoCode reuse it and relabel the result.
func parseOpenCodeDBSession(
dbPath, sessionID, machine string,
) (*ParsedSession, []ParsedMessage, error) {
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return nil, nil, fmt.Errorf(
"opencode db not found: %s", dbPath,
)
}
db, err := openOpenCodeDB(dbPath)
if err != nil {
return nil, nil, err
}
defer db.Close()
projects, err := loadOpenCodeProjectsCached(db, dbPath)
if err != nil {
return nil, nil, fmt.Errorf(
"loading opencode projects: %w", err,
)
}
hasDirectory, err := openCodeSessionHasDirectoryCached(db, dbPath)
if err != nil {
return nil, nil, fmt.Errorf(
"probing opencode session schema: %w", err,
)
}
s, err := loadOneOpenCodeSession(db, sessionID, hasDirectory)
if err != nil {
return nil, nil, fmt.Errorf(
"loading opencode session %s: %w",
sessionID, err,
)
}
projectWorktree := strings.TrimSpace(projects[s.projectID])
cwd := resolveOpenCodeWorktree(s.directory, projectWorktree)
if !openCodeUsableWorktree(projectWorktree) {
projectWorktree = cwd
}
return buildOpenCodeSession(
db, s, cwd, projectWorktree, dbPath, machine,
)
}
// resolveOpenCodeWorktree picks the session working directory used for
// cwd/project. OpenCode's synthetic "global" project stores worktree="/",
// while session.directory still holds the real path the session ran in.
// Prefer a concrete session directory; fall back to the project worktree.
func resolveOpenCodeWorktree(
sessionDirectory, projectWorktree string,
) string {
if dir := strings.TrimSpace(sessionDirectory); openCodeUsableWorktree(dir) {
return dir
}
return strings.TrimSpace(projectWorktree)
}
func openCodeUsableWorktree(path string) bool {
if path == "" {
return false
}
// Root is OpenCode's global-project placeholder, not a real project cwd.
return path != string(filepath.Separator) && path != "/"
}
// parseOpenCodeStorageFile parses a file-backed OpenCode storage
// session rooted at storage/session/<project>/<session>.json. The
// OpenCode-format provider owns this path; Kilo and MiMoCode reuse it
// and relabel the result.
func parseOpenCodeStorageFile(
sessionPath, machine string,
) (*ParsedSession, []ParsedMessage, error) {
raw, err := os.ReadFile(sessionPath)
if err != nil {
return nil, nil, fmt.Errorf(
"reading opencode session file %s: %w",
sessionPath, err,
)
}
var sf openCodeStorageSessionFile
if err := json.Unmarshal(raw, &sf); err != nil {
return nil, nil, fmt.Errorf(
"decoding opencode session file %s: %w",
sessionPath, err,
)
}
if sf.ID == "" {
return nil, nil, fmt.Errorf(
"opencode session file %s missing id",
sessionPath,
)
}
root := filepath.Dir(filepath.Dir(filepath.Dir(
filepath.Dir(sessionPath),
)))
// OpenCode session sync replaces the full stored transcript.
// If a child JSON is truncated mid-write, skipping it here
// would silently drop previously persisted content until the
// next successful sync, so malformed children abort the parse.
msgs, err := loadOpenCodeStorageMessages(root, sf.ID)
if err != nil {
return nil, nil, err
}
parts, err := loadOpenCodeStorageParts(root, msgs)
if err != nil {
return nil, nil, err
}
fileMtime, err := OpenCodeSourceMtime(sessionPath)
if err != nil {
return nil, nil, err
}
sess, parsed, err := buildOpenCodeParsedSession(
openCodeSessionRow{
id: sf.ID,
parentID: sf.ParentID,
title: sf.Title,
timeCreated: sf.Time.Created,
timeUpdated: sf.Time.Updated,
},
sf.Directory,
sf.Directory,
sessionPath,
fileMtime,
machine,
msgs,
parts,
)
if err != nil || sess == nil {
return sess, parsed, err
}
sess.File.Hash = buildOpenCodeSessionFingerprint(
openCodeSessionRow{
id: sf.ID,
parentID: sf.ParentID,
title: sf.Title,
timeCreated: sf.Time.Created,
timeUpdated: sf.Time.Updated,
},
sf.Directory,
sf.Directory,
msgs,
parts,
)
return sess, parsed, nil
}
func openOpenCodeDB(dbPath string) (*sql.DB, error) {
dsn := "file:" + sqliteURIPath(dbPath) +
"?mode=ro&_busy_timeout=3000"
db, err := sql.Open("sqlite3", dsn)
if err != nil {
return nil, fmt.Errorf(
"opening opencode db %s: %w", dbPath, err,
)
}
return db, nil
}
// openCodeProject is a row from the opencode project table.
type openCodeProject struct {
id string
worktree string
}
func loadOpenCodeProjects(
db *sql.DB,
) (map[string]string, error) {
rows, err := db.Query(
"SELECT id, worktree FROM project",
)
if err != nil {
return nil, err
}
defer rows.Close()
projects := make(map[string]string)
for rows.Next() {
var p openCodeProject
if err := rows.Scan(&p.id, &p.worktree); err != nil {
return nil, err
}
projects[p.id] = p.worktree
}
return projects, rows.Err()
}
type openCodeProjectsCacheEntry struct {
state SQLiteContainerState
projects map[string]string
}
// openCodeProjectsCache memoizes the project table per shared SQLite DB,
// keyed by the container's change-detection state. The engine parses each
// session of a container through an independent provider instance, so
// without this cache every parsed session re-queried the full project
// table — the dominant per-session cost when re-verifying a changed
// container. Entries hold only a handful of small maps (one per configured
// container path) and are replaced in place.
var (
openCodeProjectsCacheMu sync.Mutex
openCodeProjectsCache = map[string]openCodeProjectsCacheEntry{}
)
// loadOpenCodeProjectsCached returns the project→worktree map for the
// shared DB at dbPath, reusing the previous load while the container state
// is unchanged. The state is captured before the query, so a write racing
// the load can only make cached data newer than its key — the next capture
// then mismatches and reloads. The returned map is shared and must be
// treated as read-only.
func loadOpenCodeProjectsCached(
db *sql.DB, dbPath string,
) (map[string]string, error) {
state, ok := StatSQLiteContainerState(dbPath)
if !ok {
return loadOpenCodeProjects(db)
}
openCodeProjectsCacheMu.Lock()
entry, hit := openCodeProjectsCache[dbPath]
openCodeProjectsCacheMu.Unlock()
if hit && entry.state == state {
return entry.projects, nil
}
projects, err := loadOpenCodeProjects(db)
if err != nil {
return nil, err
}
openCodeProjectsCacheMu.Lock()
openCodeProjectsCache[dbPath] = openCodeProjectsCacheEntry{
state: state,
projects: projects,
}
openCodeProjectsCacheMu.Unlock()
return projects, nil
}
// openCodeSessionRow is a row from the opencode session table.
type openCodeSessionRow struct {
id string
projectID string
parentID string
title string
directory string
timeCreated int64
timeUpdated int64
}
// openCodeSessionSchemaCacheEntry memoizes both schema probes for one
// container. Each probe has its own "resolved" flag so populating one never
// makes the other report a false negative from its zero value.
type openCodeSessionSchemaCacheEntry struct {
state SQLiteContainerState
hasDirectory bool
directoryOnce bool
hasComposite bool
compositeOnce bool
}
// openCodeSessionSchemaCache memoizes whether session.directory exists for
// each shared OpenCode SQLite path. Legacy OpenCode-family DBs (older
// OpenCode, Kilo, MiMoCode, ICodeMate) omit the column; probing once per
// container state avoids a PRAGMA on every session parse.
var (
openCodeSessionSchemaCacheMu sync.Mutex
openCodeSessionSchemaCache = map[string]openCodeSessionSchemaCacheEntry{}
)
func openCodeSessionHasDirectoryCached(
db *sql.DB, dbPath string,
) (bool, error) {
state, ok := StatSQLiteContainerState(dbPath)
if !ok {
return openCodeSessionTableHasDirectory(db)
}
openCodeSessionSchemaCacheMu.Lock()
entry, hit := openCodeSessionSchemaCache[dbPath]
openCodeSessionSchemaCacheMu.Unlock()
if hit && entry.state == state && entry.directoryOnce {
return entry.hasDirectory, nil
}
hasDirectory, err := openCodeSessionTableHasDirectory(db)
if err != nil {
return false, err
}
openCodeSessionSchemaCacheMu.Lock()
prev := openCodeSessionSchemaCache[dbPath]
if prev.state != state {
prev = openCodeSessionSchemaCacheEntry{}
}
prev.state = state
prev.hasDirectory = hasDirectory
prev.directoryOnce = true
openCodeSessionSchemaCache[dbPath] = prev
openCodeSessionSchemaCacheMu.Unlock()
return hasDirectory, nil
}
// openCodeCompositeMtimeExpr is the per-session change signal for a
// SQLite-backed OpenCode container. Every session in a root shares one
// physical opencode.db, so the container file's own size and mtime move
// whenever any single session is written and cannot discriminate between
// sessions. These four columns can:
//
// - session.time_updated — the session row itself
// - project.time_updated — the owning project (worktree renames re-resolve
// every session in that project, which is the correct scope; verified on a
// production container that this does not track ordinary session activity)
// - max(message.time_updated) / max(part.time_updated) — child content,
// including in-place edits that leave time_created untouched
//
// The child scans read only small columns; OpenCode keeps each part's `data`
// in SQLite overflow pages, so this does not read transcript bytes.
const openCodeCompositeMtimeExpr = `MAX(s.time_updated,
COALESCE(pr.time_updated, 0),
COALESCE(m.mx, 0),
COALESCE(p.mx, 0))`
const openCodeCompositeMtimeJoins = `
LEFT JOIN project pr ON pr.id = s.project_id
LEFT JOIN (
SELECT session_id, MAX(time_updated) mx FROM message GROUP BY session_id
) m ON m.session_id = s.id
LEFT JOIN (
SELECT session_id, MAX(time_updated) mx FROM part GROUP BY session_id
) p ON p.session_id = s.id`
// openCodeCompositeMtimeSupportedCached reports whether this container's schema
// carries every column openCodeCompositeMtimeExpr needs. Older OpenCode-family
// containers (Kilo, MiMoCode, ICodeMate, legacy OpenCode) omit the child
// time_updated columns; those keep the previous session-only mtime and the
// container-stat fallback in Fingerprint.
func openCodeCompositeMtimeSupportedCached(
db *sql.DB, dbPath string,
) (bool, error) {
state, ok := StatSQLiteContainerState(dbPath)
if !ok {
return openCodeSupportsCompositeMtime(db)
}
openCodeSessionSchemaCacheMu.Lock()
entry, hit := openCodeSessionSchemaCache[dbPath]
openCodeSessionSchemaCacheMu.Unlock()
if hit && entry.state == state && entry.compositeOnce {
return entry.hasComposite, nil
}
supported, err := openCodeSupportsCompositeMtime(db)
if err != nil {
return false, err
}
openCodeSessionSchemaCacheMu.Lock()
prev := openCodeSessionSchemaCache[dbPath]
if prev.state != state {
prev = openCodeSessionSchemaCacheEntry{state: state}
}
prev.state = state
prev.hasComposite = supported
prev.compositeOnce = true
openCodeSessionSchemaCache[dbPath] = prev
openCodeSessionSchemaCacheMu.Unlock()
return supported, nil
}
func openCodeSupportsCompositeMtime(db *sql.DB) (bool, error) {
for _, probe := range []struct{ table, column string }{
{"message", "time_updated"},
{"part", "time_updated"},
{"project", "time_updated"},
} {
has, err := openCodeTableHasColumn(db, probe.table, probe.column)
if err != nil || !has {
return false, err
}
}
return true, nil
}
// openCodeTableHasColumn reports whether table carries column. An unknown
// table yields no PRAGMA rows and reports false rather than erroring, so a
// container missing an optional table degrades to the legacy signal.
func openCodeTableHasColumn(
db *sql.DB, table, column string,
) (bool, error) {
rows, err := db.Query(`SELECT 1 FROM pragma_table_info(?) WHERE name = ?`,
table, column)
if err != nil {
return false, fmt.Errorf(
"listing opencode %s table info: %w", table, err,
)
}
defer rows.Close()
if rows.Next() {
return true, rows.Err()
}
return false, rows.Err()
}
func openCodeSessionTableHasDirectory(db *sql.DB) (bool, error) {
rows, err := db.Query(`PRAGMA table_info(session)`)
if err != nil {
return false, fmt.Errorf(
"listing opencode session table info: %w", err,
)
}
defer rows.Close()
for rows.Next() {
var (
cid int
name string
typeName string
notNull int
defaultV sql.NullString
primaryKey int
)
if err := rows.Scan(
&cid, &name, &typeName, ¬Null, &defaultV, &primaryKey,
); err != nil {
return false, fmt.Errorf(
"scanning opencode session table info: %w", err,
)
}
if strings.EqualFold(name, "directory") {
return true, nil
}
}
if err := rows.Err(); err != nil {
return false, err
}
return false, nil
}
func loadOneOpenCodeSession(
db *sql.DB, sessionID string, hasDirectory bool,
) (openCodeSessionRow, error) {
var (
row *sql.Row
s openCodeSessionRow
err error
)
if hasDirectory {
row = db.QueryRow(`
SELECT s.id, s.project_id,
COALESCE(s.parent_id, ''),
COALESCE(s.title, ''),
COALESCE(s.directory, ''),
s.time_created, s.time_updated
FROM session s
WHERE s.id = ?
`, sessionID)
err = row.Scan(
&s.id, &s.projectID, &s.parentID,
&s.title, &s.directory,
&s.timeCreated, &s.timeUpdated,
)
return s, err
}
// Legacy OpenCode-family schemas omit session.directory; cwd falls
// back to project.worktree via resolveOpenCodeWorktree.
row = db.QueryRow(`
SELECT s.id, s.project_id,
COALESCE(s.parent_id, ''),
COALESCE(s.title, ''),
s.time_created, s.time_updated
FROM session s
WHERE s.id = ?
`, sessionID)
err = row.Scan(
&s.id, &s.projectID, &s.parentID,
&s.title, &s.timeCreated, &s.timeUpdated,
)
return s, err
}
// openCodeMessageRow is a row from the opencode message table.
// The role is extracted from the JSON data column.
type openCodeMessageRow struct {
id string
data string
timeCreated int64
fileMtime int64
}
// openCodeMessageData holds the scalar fields we extract from
// the message data JSON blob. Token usage lives under `tokens`
// and is read separately via gjson so the parser can
// distinguish explicit zero fields from absent ones.
type openCodeMessageData struct {
Role string `json:"role"`
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
Model struct {
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
} `json:"model"`
}
// openCodePartRow is a row from the opencode part table.
// The part type is extracted from the JSON data column.
type openCodePartRow struct {
id string
messageID string
data string
timeCreated int64
fileMtime int64
}
type openCodeStorageFingerprint struct {
Session *openCodeStorageFingerprintSession `json:"session,omitempty"`
Messages []openCodeStorageFingerprintMessage `json:"messages"`
}
type openCodeStorageFingerprintSession struct {
ID string `json:"id,omitempty"`
ProjectID string `json:"project_id,omitempty"`
ParentID string `json:"parent_id,omitempty"`
Title string `json:"title,omitempty"`
Directory string `json:"directory,omitempty"`
Worktree string `json:"worktree,omitempty"`
TimeCreated int64 `json:"time_created,omitempty"`
TimeUpdated int64 `json:"time_updated,omitempty"`
}
type openCodeStorageFingerprintMessage struct {
ID string `json:"id"`
Time int64 `json:"time"`
Hash string `json:"hash,omitempty"`
Parts []openCodeStorageFingerprintPart `json:"parts,omitempty"`
}
type openCodeStorageFingerprintPart struct {
ID string `json:"id"`
Time int64 `json:"time"`
Hash string `json:"hash,omitempty"`
}
func loadOpenCodeMessages(
db *sql.DB, sessionID string,
) ([]openCodeMessageRow, error) {
rows, err := db.Query(`
SELECT id, data, time_created
FROM message
WHERE session_id = ?
ORDER BY time_created
`, sessionID)
if err != nil {
return nil, err
}
defer rows.Close()
var msgs []openCodeMessageRow
for rows.Next() {
var m openCodeMessageRow
if err := rows.Scan(
&m.id, &m.data, &m.timeCreated,
); err != nil {
return nil, err
}
msgs = append(msgs, m)
}
return msgs, rows.Err()
}
func loadOpenCodeParts(
db *sql.DB, sessionID string,
) (map[string][]openCodePartRow, error) {
rows, err := db.Query(`
SELECT p.id, p.message_id,
COALESCE(p.data, '{}'),
p.time_created
FROM part p
WHERE p.session_id = ?
ORDER BY p.time_created
`, sessionID)
if err != nil {
return nil, err
}
defer rows.Close()
parts := make(map[string][]openCodePartRow)
for rows.Next() {
var p openCodePartRow
if err := rows.Scan(
&p.id, &p.messageID,
&p.data, &p.timeCreated,
); err != nil {
return nil, err
}
parts[p.messageID] = append(
parts[p.messageID], p,
)
}
return parts, rows.Err()
}
func buildOpenCodeSession(
db *sql.DB,
s openCodeSessionRow,
cwd, projectWorktree, dbPath, machine string,
) (*ParsedSession, []ParsedMessage, error) {
msgs, err := loadOpenCodeMessages(db, s.id)
if err != nil {
return nil, nil, fmt.Errorf(
"loading messages for %s: %w", s.id, err,
)
}
parts, err := loadOpenCodeParts(db, s.id)
if err != nil {
return nil, nil, fmt.Errorf(
"loading parts for %s: %w", s.id, err,
)
}
// Stamp the same composite the fingerprint reports, so the stored
// file_mtime is directly comparable to it. Falling back to the session
// row's own time_updated keeps legacy containers on their prior value.
fileMtime := s.timeUpdated
if composite, _, err := openCodeSessionCompositeMtime(
db, dbPath, s.id,
); err != nil {
return nil, nil, err
} else if composite != 0 {
fileMtime = composite
}
sess, parsed, err := buildOpenCodeParsedSession(
s,
cwd,
projectWorktree,
dbPath+"#"+s.id,
fileMtime*1_000_000,
machine,
msgs,
parts,
)
if err != nil || sess == nil {
return sess, parsed, err
}
sess.File.Hash = buildOpenCodeSessionFingerprint(
s, cwd, projectWorktree, msgs, parts,
)
return sess, parsed, nil
}
func buildOpenCodeParsedSession(
s openCodeSessionRow,
cwd, projectWorktree, filePath string,
fileMtime int64,
machine string,
msgs []openCodeMessageRow,
parts map[string][]openCodePartRow,
) (*ParsedSession, []ParsedMessage, error) {
var (
parsed []ParsedMessage
firstMsg string
hasUserOrAst bool
ordinal int
)
// Prefer OpenCode's LLM-generated title when available.
// Skip default placeholders that match OpenCode's exact
// format: "New session - " or "Child session - " followed
// by an ISO-8601 timestamp.
if s.title != "" && !isOpenCodeDefaultTitle(s.title) {
firstMsg = truncate(s.title, 300)
}
for _, m := range msgs {
var md openCodeMessageData
if json.Unmarshal([]byte(m.data), &md) != nil {
continue
}
role := normalizeOpenCodeRole(md.Role)
if role == "" {
continue
}
hasUserOrAst = true
msgParts := parts[m.id]
sort.Slice(msgParts, func(a, b int) bool {
if msgParts[a].timeCreated ==
msgParts[b].timeCreated {
return msgParts[a].id < msgParts[b].id
}
return msgParts[a].timeCreated <
msgParts[b].timeCreated
})
pm := buildOpenCodeMessage(
ordinal, role, m.timeCreated, msgParts, cwd,
)
applyOpenCodeTokenUsage(&pm, md, m.data, msgParts)
if strings.TrimSpace(pm.Content) == "" &&
!pm.HasToolUse {
continue
}
if role == RoleUser && firstMsg == "" {
firstMsg = truncate(
strings.ReplaceAll(pm.Content, "\n", " "),
300,
)
}
parsed = append(parsed, pm)
ordinal++
}
if !hasUserOrAst || len(parsed) == 0 {
return nil, nil, nil
}
project := ExtractProjectFromCwd(projectWorktree)
if project == "" {
project = "unknown"
}
parentID := ""
if s.parentID != "" {
parentID = "opencode:" + s.parentID
}
startedAt := millisToTime(s.timeCreated)
endedAt := millisToTime(s.timeUpdated)
userCount := 0
for _, m := range parsed {
if m.Role == RoleUser && m.Content != "" {
userCount++
}
}
sess := &ParsedSession{
ID: "opencode:" + s.id,
Project: project,
Machine: machine,
Agent: AgentOpenCode,
Cwd: cwd,
ParentSessionID: parentID,
FirstMessage: firstMsg,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(parsed),
UserMessageCount: userCount,
File: FileInfo{
Path: filePath,
Mtime: fileMtime,
},
}
accumulateMessageTokenUsage(sess, parsed)
return sess, parsed, nil
}
// applyOpenCodeTokenUsage copies the assistant message's model
// id and per-message token counts into pm so the usage
// dashboard can attribute cost. OpenCode's token field names
// use a nested `cache.{read,write}` shape; this maps them onto
// the agentsview-native `cache_{read,creation}_input_tokens`
// keys that internal/db/usage.go expects.
//
// Coverage semantics match the claude parser contract: a field
// that is present at zero is preserved as "known zero" and
// sets its coverage flag, while a tokens object with no
// recognized fields (empty `{}` or a foreign schema) leaves
// TokenUsage empty so the usage query filter skips the row.
func applyOpenCodeTokenUsage(
pm *ParsedMessage,
md openCodeMessageData,
dataRaw string,
parts []openCodePartRow,
) {
if md.ModelID != "" {
pm.Model = md.ModelID
} else if md.Model.ModelID != "" {
pm.Model = md.Model.ModelID
}
raws := []string{dataRaw}
for _, part := range parts {
if extractOpenCodePartType(part.data) == "step-finish" {
raws = append(raws, part.data)
}
}
fields, ok := collectOpenCodeTokenFields(raws...)
if !ok {
return
}
normalized := map[string]int{
"input_tokens": fields.input,
"output_tokens": fields.output,
"cache_read_input_tokens": fields.cacheRead,
"cache_creation_input_tokens": fields.cacheCreate,
}
j, err := json.Marshal(normalized)
if err != nil {
return
}
pm.TokenUsage = j
pm.OutputTokens = fields.output
pm.HasOutputTokens = fields.hasOutput
pm.ContextTokens = fields.input +
fields.cacheRead + fields.cacheCreate
pm.HasContextTokens = fields.hasInput ||
fields.hasCacheRead || fields.hasCacheCreate
}
type openCodeTokenFields struct {
input int
output int
cacheRead int
cacheCreate int
hasInput bool
hasOutput bool
hasCacheRead bool
hasCacheCreate bool
}
func collectOpenCodeTokenFields(