OpenCode plugin to archive, list, read, and restore sessions — including sessions OpenCode itself can no longer bring back. The core problem: OpenCode's API ignores time_archived changes, making archiving one-way. This plugin writes directly to SQLite.
npm test # node --test test/ (47 tests, no install required)
npm run check # verifies both index.ts and src/db.ts load without syntax errors
npm run typecheck # tsc --noEmit (requires TypeScript installed)- Entry point must be at package root — OpenCode resolves local plugins but does not honor
main/exportspointing into subdirectories.index.tslives at/,src/db.tsis internal. - Zero runtime dependencies: declares
@opencode/pluginas optional peerDependency but does not import it; uses local structural types instead. - Dual SQLite driver:
bun:sqlite(Bun) ornode:sqlite(Node 22+). Resolved at runtime. - Schema-agnostic: discovers
session_v2(v2) orsession(v1) at runtime and introspects columns. No hardcoded schemas.
- Only
time_archivedandtime_updatedare ever written — never messages. - Every write takes a consistent snapshot first via
VACUUM INTO(WAL-safe). Backups land in~/.local/share/opencode/backups/. - Writes are transactional per-session; unknown ids are reported, not thrown.
Clearing time_archived alone is not enough. OpenCode orders sessions by time_updated DESC and pages per directory, so a session archived weeks ago stays buried. Restoring must also refresh time_updated to surface it.
| Command | Purpose |
|---|---|
/archived |
List archived sessions |
/archive [id…] |
Archive current session, or named ones |
/unarchive <id or title> |
Restore — refuses ambiguous terms |
/session <id or title> |
Print transcript (archived included) |
session_archive.list_archived— list, optionalsearchsession_archive.read— read transcript by id or searchsession_archive.archive— archive bysession_ids[]session_archive.unarchive— restore bysession_ids[]
Used by /archive, /unarchive, /transcript. Narrowest-first matching:
- Exact session id always wins
- Whole phrase against title
- Prefix match on title
- Substring on title/directory/id — only if unambiguous
Ambiguous terms resolve to nothing (not multiple sessions). This prevents /unarchive ZZ fix verify from restoring every session containing "fix".
test/db.test.ts— 36 tests against shared suite run twice (v1 + v2 schemas)test/resolve.test.ts— 11 tests for the argument resolver- Fixtures: each test file builds its own throwaway DB in a temp dir via
OPENCODE_DBenv var - Run with
node --test test/— no TypeScript compilation needed
OpenCode renders /model as a real popup. That popup is not bespoke — it is a
form with a multiselect field whose options are the model list, and the
server exposes the whole lifecycle over HTTP (POST /api/session/{id}/form,
GET .../form/{fid}, POST .../reply, DELETE ...). Form.Option is
{value, label, description}, which maps exactly onto a session row.
A form created by a plugin does not render. Verified twice on v2.0.24:
- Posted directly to the API outside any turn — stayed pending, never drawn.
- Created from inside a command execution, i.e. mid-turn, the state
/modeluses — still never drawn. The session showed no change at all.
The client evidently renders a form only in specific built-in flows. A plugin
also has no form key on its context; reaching the API means reading the
password from ~/.config/opencode/service.json and looping back to
127.0.0.1, which would be unacceptable to ship even if it worked.
The TUI event bus carries only command.execute, prompt.append,
session.select and toast.show, and a plugin's context exposes
event.subscribe with no publish, so a plugin cannot raise any UI itself.
Numbered text menus are the ceiling. That is a deliberate, tested decision.
The desktop command palette dispatches through tui.command.execute, whose
schema is a fixed enum of built-in names only:
session.list, session.new, session.share, session.interrupt, session.background,
session.compact, session.page.up, session.page.down, session.line.up,
session.line.down, session.half.page.up, session.half.page.down, session.first,
session.last, prompt.clear, prompt.submit, agent.cycle
No plugin command appears in that enum and it is compiled into the client, so
clicking /list, /archive or /unarchive in the palette does nothing at
all. The commands must be typed. A plugin cannot register into the enum.
This also plausibly explains an intermittent case where /archive 2 did
nothing while /archive 1 worked: if the autocomplete dropdown is still open
when Enter is pressed, the click path runs and matches nothing. Unverified, but
consistent.
It once looked anomalous: registered on the service, typed fine, but absent
from the palette while /list, /archive and /unarchive appeared. That was
wrong — none of the plugin's commands appear in the palette, and none can be
invoked by clicking one. /transcript was simply the one nobody had typed yet.
Do not rename it to "fix" the palette. Renaming changes nothing; the palette only dispatches the built-in enum listed above.
The desktop app registers opencode:// as a protocol handler, so
opencode://session/<id> looks like a way to give a plugin clickable navigation.
It does not work. The main process accepts the URL, filters for the opencode://
prefix, logs deep link received via open-url, and forwards it to the renderer.
The renderer parks it in a global and fires an event, then stops:
window.__OPENCODE__.deepLinks = [...(window.__OPENCODE__.deepLinks ?? []), ...urls]
window.dispatchEvent(new CustomEvent(`opencode:deep-link`, {detail: {urls}}))Extracting all 6,652 files from /usr/lib/opencode-desktop/app.asar and
searching every one: exactly one file writes deepLinks, exactly one dispatches
the event, and nothing listens. No navigation, no routing.
So there is no clickable navigation available to a plugin, and therefore no way to build a child-session picker with a usable way back. This also rules out anything else that would need the user to click somewhere.
To re-extract the archive (headers are a size-prefixed JSON, file bodies start
at 16 + headerLen):
import json, struct, pathlib
d = pathlib.Path("/usr/lib/opencode-desktop/app.asar").read_bytes()
hl = struct.unpack("<I", d[12:16])[0]
hdr = json.loads(d[16:16+hl].decode()); base = 16 + hl- Every tool MUST set
options: { namespace: NS }. The host builds a tool's id as<namespace>_<name>, falling back to a bare<name>whenoptions.namespaceis absent.editor.namespace({name})only records a display descriptor — it namespaces nothing. A tool namedreadwithout it replaces the host's own read tool and breaks every request that touches a file. This took the plugin offline once;test/namespacing.test.tsguards it, and it also forbids reusing a core tool name (bash,edit,glob,grep,list,patch,read,shell,write, …) even when namespaced. - Desktop app doesn't restart the background service — closing/reopening the window reuses the existing
opencode-cli serve --serviceprocess. Must runopencode reloador kill the service process to pick up config/plugin changes. - A plugin's config is read from the server's project root, not the subdirectory you
cdinto. When testing against a throwaway server, putopencode.jsonin the directory the server actually resolves as its location, or it is silently ignored. /api/pluginis the way to confirm a local plugin loaded (look forsource.type == "local"and the entry path). There is no tool-listing endpoint — verify core tools still work by prompting a throwaway session to use one.GET /api/session/{id}/messagereturns items in non-chronological order. Sort bytime.createdbefore reading the newest output, or you will read a stale message.- The
checkscript exists because the test suite only coverssrc/db.ts;index.tssyntax errors went undetected until manual load testing. - Template literals with nested quotes: prefer concatenation (
"foo " + bar + " baz") over`foo ${bar} baz`when the string contains both backticks and quotes.
npm testandnpm run check- Start a throwaway server:
(setsid opencode serve --port NNNN > log 2>&1 < /dev/null &)withopencode.jsonin the server's resolved project root. - Password comes from the
server password …line in the log; all calls use basic authopencode:$PW. - Confirm load:
GET /api/plugin→source.type == "local". - Confirm commands:
GET /api/command→ expectarchived, archive, session, unarchivealongsideinit, review. - Confirm no shadowing: prompt a session to use the core
readtool and check it still reads a file. - Confirm function: flip
time_archivedinsession_v2via/archiveand/unarchive. - Kill the server and delete every test session — they land in the real database.
index.ts # plugin entry — commands + tools, exports default + __resolve
src/db.ts # SessionStore, schema detection, backup, archive/unarchive
test/db.test.ts # DB layer tests (both schemas)
test/resolve.test.ts # Resolver tests
test/namespacing.test.ts # Guards tool namespacing / core-tool collisions
package.json # main: "./index.ts", exports: ".": "./index.ts"
tsconfig.json # noEmit, strict, include: src/** test/**
- Default DB:
~/.local/share/opencode/opencode.db(orXDG_DATA_HOME/opencode/opencode.db) - Override with
OPENCODE_DBenv var (used by tests) - Requires Node 22+ or Bun
This directory is not just a working copy — it is the live plugin source
that the user's OpenCode is executing from, configured by absolute path in
~/.config/opencode/opencode.json. A git checkout changes production.
The file watcher reloads the plugin on every save, so the moment a checkout lands, whatever is on disk is live. This has bitten twice:
masterpredated the namespacing fix, so checking it out registered bareread,archiveandunarchive, replacing the host's core read tool and breaking every request that touched a file.- A mid-merge checkout flashed stale tools before the pull completed.
Rule: develop on a branch, merge on GitHub, never switch branches in this
directory while OpenCode is running. master is not a place to visit locally.
If a branch must be checked out, stop OpenCode first, and verify afterwards:
curl -su "opencode:$(python3 -c "import json;print(json.load(open('$HOME/.config/opencode/service.json'))['password'])")" \
http://127.0.0.1:49374/api/command | python3 -c "import sys,json;print([c['name'] for c in json.load(sys.stdin)['data']])"Expect exactly ['init', 'review', 'save']. Anything else means a stale
checkout is live.