opencode-db 0.3.0__tar.gz → 0.4.4__tar.gz

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.
Files changed (36) hide show
  1. opencode_db-0.4.4/PKG-INFO +695 -0
  2. opencode_db-0.4.4/opencode_db.egg-info/PKG-INFO +695 -0
  3. {opencode_db-0.3.0 → opencode_db-0.4.4}/pyproject.toml +7 -1
  4. opencode_db-0.3.0/PKG-INFO +0 -7
  5. opencode_db-0.3.0/opencode_db.egg-info/PKG-INFO +0 -7
  6. {opencode_db-0.3.0 → opencode_db-0.4.4}/LICENSE +0 -0
  7. {opencode_db-0.3.0 → opencode_db-0.4.4}/README.md +0 -0
  8. {opencode_db-0.3.0 → opencode_db-0.4.4}/cli.py +0 -0
  9. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_costs.py +0 -0
  10. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_delete.py +0 -0
  11. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_export.py +0 -0
  12. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_help.py +0 -0
  13. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_info.py +0 -0
  14. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_list.py +0 -0
  15. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_projects.py +0 -0
  16. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_prune.py +0 -0
  17. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_search.py +0 -0
  18. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_stats.py +0 -0
  19. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_todos.py +0 -0
  20. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_tree.py +0 -0
  21. {opencode_db-0.3.0 → opencode_db-0.4.4}/cmd_vacuum.py +0 -0
  22. {opencode_db-0.3.0 → opencode_db-0.4.4}/commands/__init__.py +0 -0
  23. {opencode_db-0.3.0 → opencode_db-0.4.4}/config.py +0 -0
  24. {opencode_db-0.3.0 → opencode_db-0.4.4}/db.py +0 -0
  25. {opencode_db-0.3.0 → opencode_db-0.4.4}/formatters.py +0 -0
  26. {opencode_db-0.3.0 → opencode_db-0.4.4}/i18n.py +0 -0
  27. {opencode_db-0.3.0 → opencode_db-0.4.4}/opencode_db.egg-info/SOURCES.txt +0 -0
  28. {opencode_db-0.3.0 → opencode_db-0.4.4}/opencode_db.egg-info/dependency_links.txt +0 -0
  29. {opencode_db-0.3.0 → opencode_db-0.4.4}/opencode_db.egg-info/entry_points.txt +0 -0
  30. {opencode_db-0.3.0 → opencode_db-0.4.4}/opencode_db.egg-info/top_level.txt +0 -0
  31. {opencode_db-0.3.0 → opencode_db-0.4.4}/setup.cfg +0 -0
  32. {opencode_db-0.3.0 → opencode_db-0.4.4}/tests/test_commands.py +0 -0
  33. {opencode_db-0.3.0 → opencode_db-0.4.4}/tests/test_db.py +0 -0
  34. {opencode_db-0.3.0 → opencode_db-0.4.4}/tests/test_i18n.py +0 -0
  35. {opencode_db-0.3.0 → opencode_db-0.4.4}/tests/test_utils.py +0 -0
  36. {opencode_db-0.3.0 → opencode_db-0.4.4}/utils.py +0 -0
@@ -0,0 +1,695 @@
1
+ Metadata-Version: 2.4
2
+ Name: opencode-db
3
+ Version: 0.4.4
4
+ Summary: OpenCode database CLI manager — browse, export, analyze, clean up sessions
5
+ Project-URL: Homepage, https://github.com/VasilevNStas/opencode-db
6
+ Project-URL: Source, https://github.com/VasilevNStas/opencode-db
7
+ Project-URL: Tracker, https://github.com/VasilevNStas/opencode-db/issues
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # opencode-db
14
+
15
+ [![test](https://github.com/VasilevNStas/opencode-db/actions/workflows/test.yml/badge.svg)](https://github.com/VasilevNStas/opencode-db/actions/workflows/test.yml)
16
+ [![release](https://github.com/VasilevNStas/opencode-db/actions/workflows/release.yml/badge.svg)](https://github.com/VasilevNStas/opencode-db/actions/workflows/release.yml)
17
+ [![PyPI](https://img.shields.io/pypi/v/opencode-db)](https://pypi.org/project/opencode-db/)
18
+ [![Python](https://img.shields.io/badge/python-3.12%2B-blue)](https://www.python.org/downloads/)
19
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
20
+
21
+ **OpenCode database manager: browse, export, analyze, and clean up sessions.**
22
+
23
+ `opencode-db` is a CLI utility that connects to OpenCode's local SQLite database and lets you inspect your agent sessions, export conversations to Markdown, track token usage and costs, and manage storage by deleting old sessions or optimizing the database.
24
+
25
+ ```
26
+ opencode-db help # full reference with examples
27
+ opencode-db list # list recent sessions
28
+ opencode-db stats # database summary
29
+ opencode-db export # save a dialog to .md (interactive)
30
+ opencode-db costs --total # total token costs
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ ### Requirements
38
+
39
+ - Python 3.12+
40
+ - OpenCode (must have been run at least once — the database is created automatically)
41
+ - macOS / Linux
42
+
43
+ ### One-command install (recommended)
44
+
45
+ ```bash
46
+ curl -fsSL https://raw.githubusercontent.com/VasilevNStas/opencode-db/master/install.sh | sh
47
+ ```
48
+
49
+ Downloads everything to `~/.local/share/opencode-db/` and creates `~/.local/bin/opencode-db`.
50
+
51
+ ### pip / pipx install
52
+
53
+ ```bash
54
+ pipx install opencode-db
55
+ # or
56
+ pip install opencode-db
57
+ ```
58
+
59
+ [Zero external dependencies](https://treyhunner.com/2015/12/python-imports-and-path-manipulation/) — pure Python standard library only.
60
+
61
+ ### Manual install
62
+
63
+ 1. Download the latest release from GitHub or clone the repo:
64
+
65
+ ```bash
66
+ git clone https://github.com/VasilevNStas/opencode-db.git ~/.local/share/opencode-db
67
+ ```
68
+
69
+ 2. Create a launcher at `~/.local/bin/opencode-db`:
70
+
71
+ ```bash
72
+ cat > ~/.local/bin/opencode-db << 'SCRIPT'
73
+ #!/usr/bin/env python3
74
+ import sys, os
75
+ PKG_DIR = os.path.expanduser("~/.local/share/opencode-db")
76
+ if PKG_DIR not in sys.path:
77
+ sys.path.insert(0, PKG_DIR)
78
+ import cli
79
+ sys.exit(cli.main())
80
+ SCRIPT
81
+ chmod +x ~/.local/bin/opencode-db
82
+ ```
83
+
84
+ 3. Make sure `~/.local/bin` is in your `$PATH`:
85
+
86
+ ```bash
87
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
88
+ source ~/.zshrc
89
+ ```
90
+
91
+ 4. Verify:
92
+
93
+ ```bash
94
+ opencode-db --help
95
+ ```
96
+
97
+ ---
98
+
99
+ ## Quick start
100
+
101
+ ```bash
102
+ # List recent sessions
103
+ opencode-db list
104
+
105
+ # Detailed session info (accepts partial ID)
106
+ opencode-db info ses_1c9d
107
+
108
+ # Save a dialog in Markdown
109
+ opencode-db export ses_1c9d --force
110
+
111
+ # Total token costs
112
+ opencode-db costs --total
113
+
114
+ # Database statistics
115
+ opencode-db stats
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Commands
121
+
122
+ ### `list` — list sessions
123
+
124
+ Displays a table of recent sessions: ID, title, project, model, last activity, message count, and cost.
125
+
126
+ ```bash
127
+ opencode-db list # last 25 sessions
128
+ opencode-db list --limit 10 # last 10
129
+ opencode-db list --all # every session
130
+ opencode-db list --sort cost # sort by cost (descending)
131
+ opencode-db list --project proj_xxx # filter by project
132
+ opencode-db list --agent build # filter by agent type
133
+ opencode-db list --model deepseek # filter by model name
134
+ opencode-db list --json # JSON output
135
+ ```
136
+
137
+ | Flag | Description | Default |
138
+ |---|---|---|
139
+ | `--limit N` | Number of sessions to show | 25 |
140
+ | `--offset N` | How many to skip | 0 |
141
+ | `--project ID` | Filter by project | — |
142
+ | `--agent NAME` | Filter by agent type | — |
143
+ | `--model NAME` | Filter by model name | — |
144
+ | `--sort {date,cost,tokens,messages}` | Sort order | date |
145
+ | `--json` | Output as JSON | — |
146
+ | `--all` | Show all (overrides --limit) | — |
147
+
148
+ ---
149
+
150
+ ### `info` — detailed session information
151
+
152
+ Shows metadata, message and token statistics, cost, code changes, child sessions, and todo items.
153
+
154
+ ```bash
155
+ opencode-db info ses_1c9d9fa58ffe # by full ID
156
+ opencode-db info ses_1c9d # by ID prefix
157
+ opencode-db info ses_1c9d --json # JSON output
158
+ ```
159
+
160
+ Example output:
161
+
162
+ ```
163
+ ============================================================
164
+ Анализ export-dialog скрипта
165
+ ============================================================
166
+ ID: ses_1c9d9fa58ffeiqsrHGVg8MPZes
167
+ Проект: global (global)
168
+ Модель: deepseek-reasoner
169
+ Агент: plan
170
+ Версия: 1.15.1
171
+ Создана: 2026-05-17 13:35:22
172
+ Активна: 2026-05-17 14:13:23
173
+ Длит-сть: 38 мин
174
+
175
+ ────────────────────────────────────────────────────────
176
+ Сообщений: 43
177
+ Частей: 224
178
+ ────────────────────────────────────────────────────────
179
+ Токены ввода: 82 026
180
+ Токены вывода: 36 837
181
+ Токены reasoning: 17 211
182
+ Кэш (чтение): 2 077 312
183
+ Всего токенов: 118 863
184
+ Стоимость: $0.085
185
+ ```
186
+
187
+ ---
188
+
189
+ ### `export` — export dialog to Markdown
190
+
191
+ Saves a conversation to `opencode-YYYY-MM-DD_HH.MM.SS.md` in the current directory.
192
+
193
+ **Three ways to pick a session:**
194
+
195
+ | Mode | Example | Description |
196
+ |---|---|---|
197
+ | By ID | `export ses_1c9d` | Explicit session ID (full or prefix) |
198
+ | Latest | `export --latest` | Most recent session |
199
+ | Interactive | `export` (no args) | Pick from a numbered list |
200
+
201
+ ```bash
202
+ opencode-db export ses_1c9d # export by ID
203
+ opencode-db export --latest # export the most recent session
204
+ opencode-db export --latest --force # overwrite if the file exists
205
+ opencode-db export --latest --full # full output, no truncation
206
+ opencode-db export --latest -n "bug fix" # add a note to log.md
207
+ opencode-db export # interactive picker
208
+ opencode-db export --full # full output (don't truncate tool outputs)
209
+ opencode-db export -o ~/backup # save to a different directory
210
+ ```
211
+
212
+ The file format is Markdown with a metadata header (date, model, ID) followed by messages in chronological order with speaker labels (user/assistant), model reasoning blocks, and tool calls with their results.
213
+
214
+ If the project directory contains `.obsidian`, a `log.md` file is automatically created or appended with a project snapshot (AGENTS.md summary, file and directory counts).
215
+
216
+ | Flag | Description | Default |
217
+ |---|---|---|
218
+ | `session_id` | Session ID (optional — interactive mode if omitted) | — |
219
+ | `--latest`, `-l` | Export the most recent session | — |
220
+ | `--full`, `-F` | Full output (do not truncate long tool outputs) | — |
221
+ | `--force`, `-f` | Overwrite the file if it exists | — |
222
+ | `--note`, `-n` | Description for log.md | — |
223
+ | `--output`, `-o` | Output directory | `os.getcwd()` |
224
+
225
+ ---
226
+
227
+ ### `delete` — delete a session
228
+
229
+ Removes a session and all related data (messages, parts, todos) thanks to CASCADE constraints in the database schema.
230
+
231
+ ```bash
232
+ opencode-db delete ses_1c9d --dry-run # show what would be deleted
233
+ opencode-db delete ses_1c9d # delete with confirmation
234
+ opencode-db delete ses_1c9d --force # delete without confirmation
235
+ ```
236
+
237
+ | Flag | Description |
238
+ |---|---|
239
+ | `--dry-run` | Only show what would be deleted |
240
+ | `--force`, `-f` | Skip confirmation prompt |
241
+
242
+ ---
243
+
244
+ ### `costs` — token cost analysis
245
+
246
+ Breaks down tokens and cost by session, project, or entire database.
247
+
248
+ ```bash
249
+ opencode-db costs ses_1c9d # single session
250
+ opencode-db costs --total # all sessions combined
251
+ opencode-db costs --project proj_xxx # filter by project
252
+ opencode-db costs # top sessions by cost
253
+ opencode-db costs --limit 10 # top 10
254
+ opencode-db costs ses_1c9d --json # JSON output
255
+ ```
256
+
257
+ Costs are taken directly from the database (`session.cost`), which stores the actual cost calculated by the model provider. No manual pricing table is needed.
258
+
259
+ | Flag | Description | Default |
260
+ |---|---|---|
261
+ | `session_id` | Session ID (optional) | — |
262
+ | `--project` | Filter by project | — |
263
+ | `--total` | Total across all sessions | — |
264
+ | `--limit N` | Max rows in list mode | 30 |
265
+ | `--json` | JSON output | — |
266
+
267
+ ---
268
+
269
+ ### `prune` — bulk cleanup of old sessions
270
+
271
+ Deletes sessions by age, project, or keeps a specified number of the most recent ones.
272
+
273
+ ```bash
274
+ opencode-db prune --older-than 30d --dry-run # preview deletions
275
+ opencode-db prune --older-than 90d # delete sessions older than 90 days
276
+ opencode-db prune --older-than 6m # older than 6 months
277
+ opencode-db prune --older-than 1y # older than 1 year
278
+ opencode-db prune --keep-last 20 # keep the 20 most recent
279
+ opencode-db prune --older-than 30d --keep-last 10 # combined filters
280
+ opencode-db prune --project proj_xxx # per project
281
+ opencode-db prune --older-than 30d --force # skip confirmation
282
+ ```
283
+
284
+ Time spec formats: `30d` (days), `6m` (months), `1y` (years).
285
+
286
+ | Flag | Description |
287
+ |---|---|
288
+ | `--older-than SPEC` | Delete sessions older than the given duration |
289
+ | `--keep-last N` | Keep N most recent sessions |
290
+ | `--project ID` | Limit to a specific project |
291
+ | `--dry-run` | Only show what would be deleted |
292
+ | `--force`, `-f` | Skip confirmation prompt |
293
+
294
+ ---
295
+
296
+ ### `search` — search across messages
297
+
298
+ Searches message text and tool call parameters (case-insensitive).
299
+
300
+ ```bash
301
+ opencode-db search "deployment" # search all sessions
302
+ opencode-db search "deployment" --limit 5 # first 5 results
303
+ opencode-db search "deployment" --session ses_1c9d # single session
304
+ opencode-db search "deployment" --json # JSON output
305
+ ```
306
+
307
+ | Flag | Description | Default |
308
+ |---|---|---|
309
+ | `query` | Search text | required |
310
+ | `--session ID` | Limit to a session | — |
311
+ | `--limit N` | Max results | 30 |
312
+ | `--json` | JSON output | — |
313
+
314
+ ---
315
+
316
+ ### `tree` — session tree (branching)
317
+
318
+ Shows the session hierarchy via the `parent_id` field. Useful for understanding which sessions spawned from which.
319
+
320
+ ```bash
321
+ opencode-db tree # all root sessions with their children
322
+ opencode-db tree ses_1c9d # branch from a specific session
323
+ opencode-db tree --project proj_xxx # filter by project
324
+ opencode-db tree --depth 3 # max depth of 3 levels
325
+ ```
326
+
327
+ Example output:
328
+
329
+ ```
330
+ 🌳 Все корневые сессии (ветвление)
331
+ ───────────────────────────────────────────────────────
332
+ ses_1ed78233fffe 2026-05-10 Starting a project
333
+ └─ ses_1ed5d1a05ffe 2026-05-10 Create README and meta files (@general subagent)
334
+ └─ ses_1ed5c6c29ffe 2026-05-10 Create Module 01 Fundamentals (@general subagent)
335
+ └─ ses_1ed5b7adbffe 2026-05-10 Create Module 02 Anatomy (@general subagent)
336
+ ...
337
+ ```
338
+
339
+ | Flag | Description | Default |
340
+ |---|---|---|
341
+ | `session_id` | Start from this session (optional) | — |
342
+ | `--depth N` | Maximum depth | 5 |
343
+ | `--project ID` | Filter by project | — |
344
+
345
+ ---
346
+
347
+ ### `projects` — list projects
348
+
349
+ Shows all projects in the database with session counts, tokens, and costs.
350
+
351
+ ```bash
352
+ opencode-db projects # project table
353
+ opencode-db projects --json # JSON output
354
+ ```
355
+
356
+ | Flag | Description |
357
+ |---|---|
358
+ | `--json` | JSON output |
359
+
360
+ ---
361
+
362
+ ### `stats` — database statistics
363
+
364
+ Summary of the entire database: session, message, part, project, and todo counts; total tokens and cost; first and last session dates; top models and agents.
365
+
366
+ ```bash
367
+ opencode-db stats # summary
368
+ opencode-db stats --json # JSON output
369
+ ```
370
+
371
+ | Flag | Description |
372
+ |---|---|
373
+ | `--json` | JSON output |
374
+
375
+ ---
376
+
377
+ ### `todos` — view tasks from sessions
378
+
379
+ Displays todo items created during OpenCode sessions.
380
+
381
+ ```bash
382
+ opencode-db todos # all tasks
383
+ opencode-db todos ses_1c9d # tasks for a specific session
384
+ opencode-db todos --status pending # pending only
385
+ opencode-db todos --json # JSON output
386
+ ```
387
+
388
+ | Flag | Description | Default |
389
+ |---|---|---|
390
+ | `session_id` | Session ID (optional) | — |
391
+ | `--status {pending,completed,cancelled}` | Filter by status | — |
392
+ | `--limit N` | Max entries | 30 |
393
+ | `--json` | JSON output | — |
394
+
395
+ ---
396
+
397
+ ### `vacuum` — database optimization
398
+
399
+ Runs `VACUUM`, `REINDEX`, and `ANALYZE` to reclaim disk space and optimize query performance. Especially useful after bulk deletions (prune, delete).
400
+
401
+ ```bash
402
+ opencode-db vacuum # with confirmation
403
+ opencode-db vacuum --force # without confirmation
404
+ ```
405
+
406
+ | Flag | Description |
407
+ |---|---|
408
+ | `--force`, `-f` | Skip confirmation |
409
+
410
+ ---
411
+
412
+ ### `help` — detailed reference
413
+
414
+ Displays all commands with descriptions, flags, and usage examples. Works both in the terminal and inside OpenCode's TUI via `/bash opencode-db help`.
415
+
416
+ ```bash
417
+ opencode-db help # full reference for all commands
418
+ opencode-db help export # reference for a specific command
419
+ opencode-db help --json # JSON reference
420
+ ```
421
+
422
+ Example output:
423
+
424
+ ```
425
+ ╔══════════════════════════════════════════════════════════╗
426
+ ║ opencode-db — справка ║
427
+ ╚══════════════════════════════════════════════════════════╝
428
+
429
+ Использование: opencode-db <команда> [флаги]
430
+
431
+ list Список сессий
432
+ opencode-db list # Сессии за последнее время
433
+ opencode-db list --sort cost # Сортировка по стоимости
434
+ opencode-db list --json # Вывод в JSON
435
+
436
+ export Экспорт диалога в Markdown
437
+ opencode-db export <session_id> # Экспорт по ID
438
+ opencode-db export --latest # Самая свежая сессия
439
+ opencode-db export # Интерактивный выбор
440
+ opencode-db export --full # Полный вывод без обрезания
441
+
442
+ costs Анализ расходов на токены
443
+ opencode-db costs <session_id> # Детально по сессии
444
+ opencode-db costs --total # Сумма по всей БД
445
+
446
+ ...
447
+ ```
448
+
449
+ ---
450
+
451
+ ## Command reference summary
452
+
453
+ | Command | Description | Key flags |
454
+ |---|---|---|
455
+ | `list` | List sessions with filtering | `--limit`, `--sort`, `--project`, `--json`, `--all` |
456
+ | `info` | Detailed session info | `--json` |
457
+ | `export` | Export dialog to Markdown | `--latest`, `--full`, `--force`, `--note`, `--output` |
458
+ | `delete` | Delete a session | `--dry-run`, `--force` |
459
+ | `costs` | Token cost analysis | `--total`, `--project`, `--json` |
460
+ | `prune` | Bulk session cleanup | `--older-than`, `--keep-last`, `--dry-run` |
461
+ | `search` | Search message text | `--session`, `--json` |
462
+ | `tree` | Session branching tree | `--depth`, `--project` |
463
+ | `projects` | Project overview | `--json` |
464
+ | `stats` | Database statistics | `--json` |
465
+ | `todos` | View session tasks | `--status`, `--json` |
466
+ | `vacuum` | Database optimization | `--force` |
467
+ | `help` | Detailed reference | `<command>`, `--json` |
468
+
469
+ ---
470
+
471
+ ## Project architecture
472
+
473
+ ```
474
+ ~/.local/bin/opencode-db ← entry point (in $PATH)
475
+ │
476
+ ~/.local/share/opencode-db/ ← all source code
477
+ │
478
+ ├── __init__.py ← executable entry point
479
+ ├── __main__.py ← python -m opencode_db
480
+ ├── cli.py ← argparse + command dispatcher
481
+ │
482
+ ├── config.py ← constants and paths
483
+ ├── db.py ← SQLite queries
484
+ ├── utils.py ← date/token formatting, validation
485
+ ├── formatters.py ← tables, JSON, Markdown, snapshots
486
+ ├── i18n.py ← localization (EN/RU, 238 keys)
487
+ │
488
+ ├── commands/
489
+ │ └── __init__.py ← command registry
490
+ │
491
+ ├── cmd_list.py ← opencode-db list
492
+ ├── cmd_info.py ← opencode-db info
493
+ ├── cmd_export.py ← opencode-db export
494
+ ├── cmd_delete.py ← opencode-db delete
495
+ ├── cmd_costs.py ← opencode-db costs
496
+ ├── cmd_prune.py ← opencode-db prune
497
+ ├── cmd_search.py ← opencode-db search
498
+ ├── cmd_tree.py ← opencode-db tree
499
+ ├── cmd_projects.py ← opencode-db projects
500
+ ├── cmd_stats.py ← opencode-db stats
501
+ ├── cmd_todos.py ← opencode-db todos
502
+ ├── cmd_vacuum.py ← opencode-db vacuum
503
+ └── cmd_help.py ← opencode-db help
504
+
505
+ README.md ← this file (English)
506
+ README.ru.md ← documentation in Russian
507
+ opencode-db-commands.json ← OpenCode TUI custom commands config
508
+ ```
509
+
510
+ ### How it works
511
+
512
+ 1. The launcher script at `~/.local/bin/opencode-db` (a shebang Python script) adds `~/.local/share/opencode-db/` to `sys.path` and calls `cli.main()`.
513
+ 2. `cli.py` builds an `argparse` parser with subparsers from every command module and dispatches the call.
514
+ 3. Each command is a separate `cmd_*.py` module exporting two functions: `register(subparsers)` and `run(args, db)`.
515
+ 4. `db.py` opens a connection to OpenCode's SQLite database (`~/.local/share/opencode/opencode.db`).
516
+ 5. Destructive operations (`delete`, `prune`) always require confirmation (or `--force`).
517
+
518
+ ### Database schema (key tables)
519
+
520
+ ```
521
+ session — sessions: id, title, model (JSON), agent, cost, tokens_*, parent_id, summary_*
522
+ message — messages: id, session_id, time_created, data (JSON: role, agent)
523
+ part — message parts: id, message_id, session_id, data (JSON: type, text, state)
524
+ todo — tasks: session_id, content, status, priority
525
+ project — projects: id, worktree, name
526
+ ```
527
+
528
+ ---
529
+
530
+ ## Using inside OpenCode TUI
531
+
532
+ `opencode-db` can be used directly from OpenCode's terminal interface in two ways.
533
+
534
+ ### Direct execution (no AI, no tokens)
535
+
536
+ Use the built-in `/bash` tool in the OpenCode chat:
537
+
538
+ ```
539
+ /bash opencode-db list
540
+ /bash opencode-db info ses_1c9d
541
+ /bash opencode-db costs --total
542
+ /bash opencode-db export --latest --force
543
+ ```
544
+
545
+ This runs the command directly and shows the output — **no tokens are consumed**.
546
+
547
+ ### Custom `/db` command (uses AI, consumes tokens)
548
+
549
+ Add the commands from `opencode-db-commands.json` to your project's `opencode.json`:
550
+
551
+ ```json
552
+ {
553
+ "command": {
554
+ "db": {
555
+ "template": "!`opencode-db {{input}} --json`\n\nPresent the data clearly.",
556
+ "description": "OpenCode database: list, info, stats, costs, search...",
557
+ "agent": "explore",
558
+ "model": "deepseek/deepseek-chat"
559
+ }
560
+ }
561
+ }
562
+ ```
563
+
564
+ Then in the TUI:
565
+
566
+ ```
567
+ /db list --limit 5 → shows recent sessions
568
+ /db info ses_1c9d → session details
569
+ /db costs --total → total costs
570
+ /db search "bug" → search messages
571
+ ```
572
+
573
+ > ⚠️ **Warning:** the `/db` command sends the command output through the AI model. This consumes tokens (typically 500–5000 input tokens depending on the amount of data). Use `/bash opencode-db ...` when you only need to see the data without AI processing.
574
+
575
+ A ready-to-use config file is provided at:
576
+ ```
577
+ ~/.local/share/opencode-db/opencode-db-commands.json
578
+ ```
579
+
580
+ ---
581
+
582
+ ## Safety
583
+
584
+ | Principle | Implementation |
585
+ |---|---|
586
+ | Confirmation required | `delete` and `prune` always prompt for confirmation |
587
+ | Dry-run mode | `--dry-run` shows results without making changes |
588
+ | Read-only by default | `list`, `info`, `costs`, `search`, `tree`, `projects`, `stats`, `todos` are read-only |
589
+ | Partial ID resolution | Ambiguous prefixes are rejected with an error message |
590
+ | No external dependencies | Pure Python standard library — zero runtime deps |
591
+
592
+ ---
593
+
594
+ ## Language
595
+
596
+ The CLI supports both Russian and English output.
597
+
598
+ - **Default**: Russian (matching OpenCode's interface language)
599
+ - **English**: use `--lang en` flag, e.g. `opencode-db --lang en list`
600
+
601
+ ```bash
602
+ opencode-db list # Russian (default)
603
+ opencode-db --lang en list # English
604
+ opencode-db --lang en help # English help text
605
+ opencode-db --lang en stats # English statistics
606
+ ```
607
+
608
+ The `--lang` flag applies to any command. All 238 UI strings are translated. Data content (session titles, project names, etc.) remains in its original language.
609
+
610
+ The language can also be set via environment variable `OPENCODE_DB_LANG=en`.
611
+
612
+ ---
613
+
614
+ ## Dependencies
615
+
616
+ - **Python 3.12+** — standard library only
617
+ - **SQLite** — built-in `sqlite3` module
618
+ - **OpenCode** — must be installed and run at least once (creates the database)
619
+
620
+ No `npm`, `brew`, or any other package manager required.
621
+
622
+ ---
623
+
624
+ ## Troubleshooting
625
+
626
+ ### "База OpenCode не найдена" (database not found)
627
+
628
+ ```
629
+ ❌ База OpenCode не найдена: ~/.local/share/opencode/opencode.db
630
+ ```
631
+
632
+ OpenCode has not been started yet, or the database is stored in a non-standard location. Make sure:
633
+ - OpenCode is installed and has been launched at least once
634
+ - The file `~/.local/share/opencode/opencode.db` exists
635
+
636
+ ### "Найдено несколько сессий с префиксом" (multiple sessions match prefix)
637
+
638
+ ```
639
+ ❌ Найдено несколько сессий с префиксом ses_1c9d:
640
+ ses_1c9d9fa58ffeiqsrHGVg8MPZes
641
+ ses_1c9d8fa58ffeabc123def456xyz
642
+ ```
643
+
644
+ Use a longer prefix or the full session ID (use `list --json` to find it).
645
+
646
+ ### VACUUM fails
647
+
648
+ If the database is being used by another process (e.g., OpenCode is running), VACUUM may fail. Close OpenCode and try again.
649
+
650
+ ---
651
+
652
+ ## Development
653
+
654
+ ### Adding a new command
655
+
656
+ 1. Create `cmd_xxx.py`:
657
+
658
+ ```python
659
+ def register(subparsers):
660
+ p = subparsers.add_parser("xxx", help="Description")
661
+ p.add_argument("--flag", type=str)
662
+
663
+ def run(args, db):
664
+ # your logic here
665
+ return 0
666
+ ```
667
+
668
+ 2. Register it in `commands/__init__.py`:
669
+
670
+ ```python
671
+ import cmd_xxx
672
+ COMMANDS["xxx"] = cmd_xxx
673
+ ```
674
+
675
+ The command will appear in `--help` automatically.
676
+
677
+ ### Running without installation
678
+
679
+ ```bash
680
+ python3 ~/.local/share/opencode-db list
681
+ ```
682
+
683
+ Or as a module:
684
+
685
+ ```bash
686
+ python3 -m opencode_db list
687
+ ```
688
+
689
+ ---
690
+
691
+ ## Лицензия / License
692
+
693
+ MIT — подробнее в файле [LICENSE](LICENSE)
694
+
695
+ © 2026 Vasilev Stas — код можно свободно использовать, изменять и распространять