Files

693 lines
32 KiB
Python

"""
opencode sessions → v1 transcripts (the opencode harness's "runner mirror",
like ``runner/cli.mjs`` is pi's; the format is ``docs/transcript-format.md``).
opencode V2 keeps everything in one SQLite file (``opencode.db``): a
``session_v2`` row per session and a ``session_message`` row per message,
where each assistant row is **one model step** — its text, reasoning and tool
calls, each tool call carrying its own result, plus the step's tokens once it
ends. A background thread here polls every opencode account's database and
**appends** v1 events to
<MIRROR_DIR>/<account>/<cwd slug>/<uuid>.jsonl
<MIRROR_DIR>/<account>/<cwd slug>/<uuid>/subagents/agent-<id>.jsonl (+ .meta.json)
which the backend imports like any other transcript source (one dir per
account, so each conversation is stamped with its account at import).
Append-only, the way a live Claude transcript grows — the backend parses a
growing file incrementally, so nothing already written is ever rewritten:
* a user message → a ``prompt``, once;
* a step → **whole**, once it has ended (``time.completed``: opencode writes
its tokens only then, after its tools ran): its ``call``, its blocks and its
``usage`` together, then a ``tool_result`` per call. A step that never ends
(its turn ended, was interrupted or failed first) goes out as it stands
when the turn's end shows, its usage later if it ever comes;
* a failed step → an API-error call (``failed``, its ``error``, the turn's
end), an interrupted turn → ``turn_end: interrupted``, any other end of a
turn (opencode's ``idle`` row) → ``turn_end: done``, what the hub reads as
the conversation having finished.
Every group of events carries ``ocKey``, the key of what it mirrored, on its
first event, so the set of what a file already holds is rebuilt from the
file itself — a restart, or a lost state file, can't duplicate a record.
``state/<account>.json`` only remembers each settled session's event
sequence, so a restart doesn't re-read the whole database. A file written
before v1 (Claude-Code-shaped records) gets a v1 header line before the first
v1 line appended to it (``transcript_v1.Out``).
**Session ids.** A run the sidecar launches is created as ``ses_<uuid>`` —
the conversation's own UUID, so the mirror needs no mapping. A fork gets an id
opencode mints; the fork route records ``uuid → ses_…`` in ``ids.json``.
Anything else (a session started in a terminal) is keyed by a UUID derived
from its id (``uuid5``).
**Cost.** opencode records $0 for a subscription step, so no cost goes out
for it: the backend prices the tokens at the API list price. A step on a
metered provider carries opencode's own figure (``usage.cost``).
"""
from __future__ import annotations
import datetime
import json
import logging
import os
import pathlib
import re
import sqlite3
import time
import uuid as uuidlib
import mirror_base as mb
from . import tools
import transcript_v1 as v1
log = logging.getLogger("opencode-mirror")
POLL_S = float(os.environ.get("SIDECAR_OPENCODE_MIRROR_POLL_S", "2"))
# How long an unmapped fork waits for the fork route to record its id.
FORK_MAP_WAIT_MS = 60_000
NAMESPACE = uuidlib.UUID("8a5c0f4e-6a0b-4f9a-a6a2-4b1f0c3d7e21")
_SES_UUID_RE = re.compile(r"^ses_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$")
_THINK_RE = re.compile(r"<think>(.*?)(?:</think>|$)", re.S)
# opencode's error types → the claude CLI's `error` names the parser maps.
_ERROR_NAMES = {"provider.auth": "authentication_failed",
"provider.rate-limit": "rate_limit", "provider.quota": "rate_limit",
"provider.overloaded": "overloaded", "provider.server": "server_error"}
def session_uuid(ses_id: str, forks: dict[str, str]) -> str:
"""The conversation UUID an opencode session is mirrored under."""
m = _SES_UUID_RE.match(ses_id or "")
if m:
return m.group(1)
return forks.get(ses_id) or str(uuidlib.uuid5(NAMESPACE, ses_id))
def cwd_slug(cwd: str) -> str:
"""Claude Code's project-dir spelling of a cwd (every non-alphanumeric → ``-``)."""
return mb.cwd_slug(cwd)
def _iso(ms) -> str:
return mb.iso_from_ms(ms)
def _git_branch(cwd: str) -> str | None:
return mb.git_branch(cwd, timeout=5)
def model_id(model: dict | None) -> str | None:
"""The model a step ran on, as the backend prices it: a bare id for a
first-party provider (``gpt-5.5``, ``claude-…``), the id as opencode has
it for OpenRouter (``openai/gpt-oss-20b``), ``provider/id`` otherwise."""
m = model or {}
mid, prov = m.get("id"), m.get("providerID")
if not mid:
return None
if prov in (None, "openai", "anthropic", "openrouter"):
return mid
return f"{prov}/{mid}"
def _split_think(text: str) -> list[dict]:
"""A text block with inline ``<think>`` (local models) → thinking + text."""
if "<think>" not in text:
return [{"type": "text", "text": text}] if text.strip() else []
out, cursor = [], 0
for m in _THINK_RE.finditer(text):
if text[cursor:m.start()].strip():
out.append({"type": "text", "text": text[cursor:m.start()]})
if m.group(1).strip():
out.append({"type": "thinking", "thinking": m.group(1).strip()})
cursor = m.end()
if text[cursor:].strip():
out.append({"type": "text", "text": text[cursor:].strip()})
return out
def clean_title(title: str | None) -> str | None:
t = _THINK_RE.sub("", title or "").strip()
return t or None
class _Session:
"""What the mirror knows about one session while it is being mirrored."""
def __init__(self, path: pathlib.Path, root_uuid: str, cwd: str,
agent_id: str | None, version: str | None = None):
self.path = path
self.root_uuid = root_uuid
self.cwd = cwd
self.agent_id = agent_id # set for a subagent (sidechain)
self.version = version
# A step failed since the last user message (read off the rows, in
# order — a restart replays them from the first): the idle row that
# closes the failed turn repeats that error, so it writes nothing.
self.rows_error = False
self.branch = _git_branch(cwd) if cwd and os.path.isdir(cwd) else None
self.low_seq = 0 # every row below it is fully mirrored
self.out = v1.Out(path, {"id": root_uuid, "harness": "opencode",
"harnessVersion": version, "cwd": cwd, "branch": self.branch,
**({"sidechain": True, "agent": agent_id} if agent_id else {})},
"ocKey")
# Steps still running when this pass read them (msg id → row data):
# flushed as they stand when a later row shows their turn is over.
self.waiting: dict[str, dict] = {}
@property
def keys(self) -> set[str]:
return self.out.keys
@property
def title(self) -> str | None:
return self.out.title
# Rows that mean the steps before them are over: the turn's end, a new turn,
# the next step (a step's own tools run inside its row).
_TURN_OVER = ("idle", "user", "assistant")
class AccountMirror:
"""Mirror one opencode account's database into its transcripts dir."""
def __init__(self, account: str, db_path: pathlib.Path, out_dir: pathlib.Path,
state_dir: pathlib.Path, forks_path: pathlib.Path | None = None):
self.account = account
self.db_path = db_path
self.out_dir = out_dir
self.state_path = state_dir / f"{account}.json"
self.forks_path = forks_path
self._db: sqlite3.Connection | None = None
self._data_version = None
self._sessions: dict[str, _Session] = {}
self._deferred: set[str] = set()
self._settled = self._read_state()
self._forks: dict[str, str] = {}
self._forks_mtime = 0.0
# ── database ──
def _conn(self) -> sqlite3.Connection | None:
if self._db is not None:
return self._db
if not self.db_path.is_file():
return None
db = sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True, timeout=5,
isolation_level=None, check_same_thread=False)
db.row_factory = sqlite3.Row
db.execute("PRAGMA query_only=1")
self._db = db
return db
def close(self) -> None:
if self._db is not None:
self._db.close()
self._db = None
def _read_state(self) -> dict[str, int]:
return mb.read_state(self.state_path, "settled")
def _write_state(self) -> None:
mb.write_state(self.state_path, {"settled": self._settled})
def _load_forks(self) -> None:
if not self.forks_path:
return
try:
m = self.forks_path.stat().st_mtime
except OSError:
return
if m == self._forks_mtime:
return
try:
raw = json.loads(self.forks_path.read_text())
self._forks = {ses: u for u, ses in raw.items() if isinstance(ses, str)}
self._forks_mtime = m
except (OSError, ValueError, AttributeError):
pass
# ── one poll ──
def tick(self, force: bool = False) -> int:
"""Mirror whatever changed since the last tick; the records written."""
db = self._conn()
if db is None:
return 0
try:
dv = db.execute("PRAGMA data_version").fetchone()[0]
if dv == self._data_version and not force:
return 0
self._data_version = dv
self._load_forks()
rows = db.execute(
"SELECT s.id, s.parent_id, s.fork_session_id, s.directory, s.title, s.agent,"
" s.version, s.time_created, COALESCE(e.seq, 0) AS seq FROM session_v2 s"
" LEFT JOIN event_sequence e ON e.aggregate_id = s.id").fetchall()
except sqlite3.Error as e:
log.warning("opencode db %s: %s", self.db_path, e)
self.close()
return 0
by_id = {r["id"]: r for r in rows}
written = 0
changed = False
# Parents before children: a child's file goes under its root's dir.
for r in sorted(rows, key=lambda r: (self._depth(r, by_id), r["time_created"] or 0)):
sid = r["id"]
if not force and self._settled.get(sid) == r["seq"] and sid not in self._deferred:
continue
try:
n, settled = self._mirror(r, by_id)
except Exception as e: # one bad session never stops the others
log.warning("mirror %s/%s: %s", self.account, sid, e)
continue
written += n
if settled and self._settled.get(sid) != r["seq"]:
self._settled[sid] = r["seq"]
changed = True
elif not settled and sid in self._settled:
del self._settled[sid]
changed = True
if changed:
self._write_state()
return written
@staticmethod
def _depth(r, by_id) -> int:
d, seen = 0, set()
while r is not None and r["parent_id"] and r["id"] not in seen:
seen.add(r["id"])
r = by_id.get(r["parent_id"])
d += 1
return d
def _root(self, r, by_id):
seen = set()
while r["parent_id"] and r["parent_id"] in by_id and r["id"] not in seen:
seen.add(r["id"])
r = by_id[r["parent_id"]]
return r
# ── one session ──
def _session(self, r, by_id) -> _Session | None:
sid = r["id"]
s = self._sessions.get(sid)
if s is not None:
return s
root = self._root(r, by_id)
if root["fork_session_id"] and root["id"] not in self._forks \
and time.time() * 1000 - (root["time_created"] or 0) < FORK_MAP_WAIT_MS:
# The fork route writes `ids.json` only once opencode answered with
# the fork's id: filing it now (under a derived id) would put it
# under the wrong conversation for good. A fork made elsewhere
# (the TUI) is filed under its derived id once the window passed.
self._deferred.add(r["id"])
return None
if r["id"] == root["id"]:
self._deferred.discard(r["id"])
root_uuid = session_uuid(root["id"], self._forks)
cwd = root["directory"] or ""
if r["id"] == root["id"]:
path = self._find_file(root_uuid) or (
self.out_dir / cwd_slug(cwd) / f"{root_uuid}.jsonl")
s = _Session(path, root_uuid, r["directory"] or cwd, None, r["version"])
else:
root_s = self._session(root, by_id)
if root_s is None:
return None
agent_id = sid[4:] if sid.startswith("ses_") else sid
meta = self._child_meta(r, by_id)
if meta is None:
return None # its spawning call isn't known yet
path = root_s.path.with_suffix("") / "subagents" / f"agent-{agent_id}.jsonl"
meta_path = path.with_name(f"agent-{agent_id}.meta.json")
if not meta_path.exists():
meta_path.parent.mkdir(parents=True, exist_ok=True)
meta_path.write_text(json.dumps(meta))
s = _Session(path, root_uuid, r["directory"] or cwd, agent_id, r["version"])
self._sessions[sid] = s
return s
def _find_file(self, root_uuid: str) -> pathlib.Path | None:
try:
return next(self.out_dir.glob(f"*/{root_uuid}.jsonl"), None)
except OSError:
return None
def _child_meta(self, r, by_id) -> dict | None:
"""``agent-<id>.meta.json`` for a subagent session — None until the
parent's ``subagent`` call that spawned it can be named. The meta is
written once and cached by the backend, so it must carry the link."""
parent = by_id.get(r["parent_id"])
if parent is None:
return None
call = self._spawning_call(r, parent["id"])
if call is None:
self._deferred.add(r["id"])
return None
self._deferred.discard(r["id"])
depth = self._depth(r, by_id)
meta = {"agentType": r["agent"] or "general", "description": r["title"] or "",
"toolUseId": call, "spawnDepth": depth, "harness": "opencode"}
if parent["parent_id"]:
pid = parent["id"]
meta["parentAgentId"] = pid[4:] if pid.startswith("ses_") else pid
return meta
def _spawning_call(self, child, parent_id: str) -> str | None:
"""The parent's ``subagent`` call id for a child session: the call
whose settled metadata names it, else (still running — opencode keeps
the child id out of the database until then) the running call with the
child's description that started just before it."""
rows = self._db.execute(
"SELECT data FROM session_message WHERE session_id=? AND type='assistant'"
" AND (data LIKE '%subagent%' OR data LIKE '%\"task\"%')",
(parent_id,)).fetchall()
best, best_gap = None, None
for row in rows:
try:
d = json.loads(row["data"])
except ValueError:
continue
for it in d.get("content") or []:
if it.get("type") != "tool" or it.get("name") not in ("subagent", "task"):
continue
st = it.get("state") or {}
if (st.get("metadata") or {}).get("sessionID") == child["id"]:
return it.get("id")
inp = st.get("input") if isinstance(st.get("input"), dict) else {}
if st.get("status") != "running" or inp.get("description") != child["title"]:
continue
ran = (it.get("time") or {}).get("ran") or (it.get("time") or {}).get("created") or 0
gap = (child["time_created"] or 0) - ran
rank = (gap < 0, abs(gap))
if gap >= -2000 and (best_gap is None or rank < best_gap):
best, best_gap = it.get("id"), rank
return best
def _mirror(self, r, by_id) -> tuple[int, bool]:
s = self._session(r, by_id)
if s is None:
return 0, False
out: list[tuple] = []
title = clean_title(r["title"])
if title and title != s.title and not s.agent_id and f"title:{title}" not in s.keys:
out.append((f"title:{title}", [{"t": "meta", "kind": "title", "data": title}]))
rows = self._db.execute(
"SELECT id, type, seq, time_created, data FROM session_message"
" WHERE session_id=? AND seq>=? ORDER BY seq", (r["id"], s.low_seq)).fetchall()
low = None
s.waiting = {}
for row in rows:
try:
d = json.loads(row["data"])
if s.waiting and row["type"] in _TURN_OVER:
# A later row: the steps still running before it are over.
for mid, wd in list(s.waiting.items()):
if mid != row["id"]:
self._assistant(s, mid, wd, out, flush=True)
settled = self._message(s, row["id"], row["type"], d, out, by_id)
except Exception as e: # a shape we don't know: skip that row only
log.warning("mirror %s/%s: skipping %s: %s", self.account, r["id"], row["id"], e)
continue
if not settled and low is None:
low = row["seq"]
if rows:
s.low_seq = low if low is not None else rows[-1]["seq"] + 1
n = s.out.append(out)
return n, low is None and r["id"] not in self._deferred
# ── one message ──
def _message(self, s: _Session, mid: str, typ: str, d: dict, out: list,
by_id) -> bool:
"""Append the groups for one message; True once nothing more will come."""
t = d.get("time") or {}
if typ == "user":
s.rows_error = False
text = str(d.get("text") or "").rstrip()
if s.agent_id and text.startswith(tools.SUBAGENT_PREFIX):
text = text[len(tools.SUBAGENT_PREFIX):]
for f in d.get("files") if isinstance(d.get("files"), list) else []:
if isinstance(f, dict):
text += f"\n[attached {f.get('mime') or 'file'}: {f.get('name') or 'file'}]"
for sk in d.get("skills") if isinstance(d.get("skills"), list) else []:
if isinstance(sk, dict) and sk.get("id"):
text = f"@{sk['id']} {text}" if f"@{sk['id']}" not in text else text
out.append((f"user:{mid}", v1.prompt_events(text, _iso(t.get("created")))))
return True
if typ == "synthetic":
at = _iso(t.get("created"))
meta = d.get("metadata") or {}
if meta.get("source") == "subagent" and meta.get("childID"):
call = self._background_call(s, meta["childID"])
if call:
out.append((f"done:{mid}", [{"t": "inject", "at": at, "kind": "task_done",
"notes": [{"taskIds": [], "toolUseId": call,
"status": meta.get("state") or "completed",
"summary": None, "event": None,
"exitCode": None}]}]))
# Injected context (continue prompts, nested AGENTS.md, results of
# background work) — kept, as a reminder the thread doesn't show.
out.append((f"syn:{mid}", [{"t": "inject", "at": at, "kind": "reminder",
"text": d.get("text") or ""}]))
return True
if typ == "assistant":
return self._assistant(s, mid, d, out)
if typ == "compaction":
return self._compaction(mid, d, out)
if typ == "idle":
at = _iso(t.get("created"))
if d.get("outcome") == "interrupted":
out.append((f"idle:{mid}", [{"t": "turn_end", "at": at, "reason": "interrupted"}]))
return True
if d.get("outcome") == "failed" and isinstance(d.get("error"), dict) \
and not s.rows_error:
out.append((f"idle:{mid}", self._api_error(f"idle:{mid}", t.get("created"),
d["error"], s)))
# The session went idle: its turn is over — what Claude Code's
# `stop_hook_summary` / `turn_duration` say, read by the hub as the
# conversation having finished (no DONE needed).
out.append((f"end:{mid}", [{"t": "turn_end", "at": at, "reason": "done"}]))
return True
if typ == "shell":
if d.get("status") == "running":
return False
o = d.get("output")
o = str((o.get("output") if isinstance(o, dict) else o) or "")
out.append((f"shell:{mid}", v1.prompt_events(
f"`! {d.get('command') or ''}`\n\n```\n{o[-4000:]}\n```", _iso(t.get("created")))))
return True
if typ == "skill":
at = _iso(t.get("created"))
command = f"<command-name>/{d.get('skill') or d.get('name') or 'skill'}</command-name>"
cmd = v1.slash_command(command)
out.append((f"skill:{mid}", v1.prompt_events(command, at)))
body = d.get("text") or ""
if cmd is not None and not body.lstrip().startswith("<"):
ev = v1.skill_inject(cmd["name"], None, body, at,
invoked={"args": cmd["args"], "at": at})
else:
ev = {"t": "inject", "at": at, "kind": "note", "text": body}
out.append((f"skillbody:{mid}", [ev]))
return True
# system / agent-switched / model-switched / location-switched: the
# thread derives model switches from the steps themselves.
return True
def _background_call(self, s: _Session, child_id: str) -> str | None:
rows = self._db.execute(
"SELECT data FROM session_message WHERE session_id=(SELECT parent_id FROM"
" session_v2 WHERE id=?) AND type='assistant' AND data LIKE ?",
(child_id, f"%{child_id}%")).fetchall()
for row in rows:
try:
d = json.loads(row["data"])
except ValueError:
continue
for it in d.get("content") or []:
if (((it.get("state") or {}).get("metadata") or {}).get("sessionID")) == child_id:
return it.get("id")
return None
def _assistant(self, s: _Session, mid: str, d: dict, out: list,
flush: bool = False) -> bool:
"""One step. Written whole once it has ended; ``flush``: its turn is
over while it never ended — written as it stands."""
t = d.get("time") or {}
model = model_id(d.get("model"))
variant = (d.get("model") or {}).get("variant")
effort = variant if variant and variant != "default" else None
tokens = d.get("tokens")
done = bool(t.get("completed"))
streamed = done or bool(t.get("streamed"))
err = d.get("error") if isinstance(d.get("error"), dict) else {}
aborted = err.get("type") == "aborted"
if err and not aborted:
s.rows_error = True
at = _iso(t.get("streamed") or t.get("completed") or t.get("created"))
blocks, calls = [], []
for it in d.get("content") if isinstance(d.get("content"), list) else []:
if not isinstance(it, dict):
continue
if it.get("type") == "text":
for b in _split_think(str(it.get("text") or "")):
if b["type"] == "thinking":
blocks.append({"t": "thinking", "at": at, "text": b["thinking"]})
else:
blocks.append(v1.text(at, b["text"]))
elif it.get("type") == "reasoning" and (it.get("text") or "").strip():
blocks.append({"t": "thinking", "at": at, "text": it["text"]})
elif it.get("type") == "tool":
st = it.get("state") if isinstance(it.get("state"), dict) else {}
inp = st.get("input")
if st.get("status") == "streaming":
try:
inp = json.loads(inp) if isinstance(inp, str) and inp else {}
except ValueError:
inp = {}
mapped = tools.map_call(it.get("name"), inp, s.cwd, str(it.get("id")))
for cid, name, cinp in mapped:
blocks.append(v1.tool_call(at, cid, name, it.get("name") or "tool", cinp,
"opencode"))
calls.append((it, mapped))
settled = True
usage = None
if tokens:
c = tokens.get("cache") or {}
usage = {"input": tokens.get("input") or 0,
"output": (tokens.get("output") or 0) + (tokens.get("reasoning") or 0),
"cacheRead": c.get("read") or 0,
"cacheWrite": c.get("write") or 0,
"reasoning": tokens.get("reasoning") or 0}
if isinstance(d.get("cost"), (int, float)) and d["cost"] > 0:
usage["cost"] = {"usd": d["cost"], "source": "provider"}
call = {"at": at, "id": mid, "request": mid, "model": model, "effort": effort,
"empty": not blocks}
step_key, usage_key = f"step:{mid}", f"usage:{mid}"
written = {k for g in out for k in ([g[0]] if isinstance(g[0], str) else g[0] or [])}
have_usage = usage_key in s.keys or usage_key in written
if step_key not in s.keys and step_key not in written:
if not done:
if not (err or flush):
s.waiting[mid] = d
return False # still running: written whole once it ends
if not (streamed and blocks):
return False # it never got past the model's stream
s.waiting.pop(mid, None)
# A call that failed or was aborted and left nothing (no content,
# no tokens) is not written: its API error below, or the turn's
# interrupt, says it all.
if not (err and not blocks and usage is None):
uid = str(uuidlib.uuid5(NAMESPACE, f"{s.path}:{step_key}"))
blocks = [{**b, "id": uid} if b["t"] == "text" and not b.get("paused") else b
for b in blocks]
whole = done and usage is not None
out.append(([step_key, usage_key] if whole else step_key,
v1.step(call, blocks, usage if whole else None)))
have_usage = have_usage or whole
for it, mapped in calls:
st = it.get("state") if isinstance(it.get("state"), dict) else {}
if st.get("status") not in ("completed", "error"):
settled = False
continue
text, is_err = tools.result_text(st)
name = it.get("name")
if name in ("subagent", "task") and not is_err:
text = tools.subagent_report(text)
if (st.get("metadata") or {}).get("status") == "running":
text = f"Async agent launched (opencode background subagent)\n{text}"
when = _iso((it.get("time") or {}).get("completed") or t.get("completed"))
for cid, _n, _i in mapped:
out.append((f"result:{cid}", [v1.tool_result(when, cid, text, is_err)]))
if name == "skill" and not is_err:
body = tools.skill_body(text)
folder = (st.get("metadata") or {}).get("directory") or ""
skill = (it.get("state") or {}).get("input") or {}
skill = (skill.get("id") or skill.get("name")) if isinstance(skill, dict) else None
full = f"Base directory for this skill: {folder}\n\n{body}"
ev = (v1.skill_inject(skill, str(it.get("id")), full, when) if skill
else v1.skill_inject(None, None, full, when))
out.append((f"skillbody:{it.get('id')}", [ev]))
if done and usage is not None and not have_usage:
# The usage of a step written before it ended.
uat = _iso(t.get("completed"))
out.append((usage_key, v1.step({**call, "at": uat, "empty": True}, [], usage)))
if err and not aborted:
out.append((f"error:{mid}", self._api_error(f"error:{mid}",
t.get("completed") or t.get("created"),
err, s)))
return settled and done
def _api_error(self, key: str, ms, err: dict, s: _Session) -> list[dict]:
status = err.get("status")
msg = err.get("message") or err.get("type") or "request failed"
resets = _resets_at(err)
text = f"API Error: {status} {msg}" if status else f"API Error: {msg}"
if resets:
text += f" · resets {resets}"
return v1.api_error(key, _iso(ms), _ERROR_NAMES.get(err.get("type") or "", "unknown"),
text, str(uuidlib.uuid5(NAMESPACE, f"{s.path}:{key}")))
def _compaction(self, mid: str, d: dict, out: list) -> bool:
if d.get("status") == "running":
return False
t = d.get("time") or {}
at = _iso(t.get("created"))
tokens = d.get("tokens") or {}
if tokens:
c = tokens.get("cache") or {}
key = f"compaction:{mid}"
out.append((key, v1.step(
{"at": at, "id": key, "request": key, "model": model_id(d.get("model")),
"empty": True}, [],
{"input": tokens.get("input") or 0,
"output": (tokens.get("output") or 0) + (tokens.get("reasoning") or 0),
"cacheRead": c.get("read") or 0, "cacheWrite": c.get("write") or 0})))
if d.get("status") == "completed" and d.get("summary"):
text = ("This session is being continued from a previous conversation "
f"({d.get('reason') or 'auto'} compaction). The summary below covers the "
f"earlier portion of the conversation.\n\n{d['summary']}")
out.append((f"summary:{mid}", [{"t": "inject", "at": at, "kind": "compact_summary",
"text": v1.compact_summary_text(text)}]))
return True
def _resets_at(err: dict) -> str | None:
"""When a usage limit lifts, from the raw error body ChatGPT sent
(``resets_at`` epoch seconds, or ``resets_in_seconds``)."""
resp = err.get("response")
body = resp.get("body") if isinstance(resp, dict) else None
try:
e = json.loads(body) if isinstance(body, str) else {}
e = e.get("error") if isinstance(e, dict) else None
if not isinstance(e, dict):
return None
at = e.get("resets_at")
if not at and e.get("resets_in_seconds"):
at = time.time() + float(e["resets_in_seconds"])
if not at:
return None
return datetime.datetime.fromtimestamp(float(at), datetime.timezone.utc) \
.strftime("%Y-%m-%d %H:%M UTC")
except (ValueError, TypeError, OverflowError, OSError):
return None
class MirrorThread(mb.PollThread):
"""Polls every account's mirror every POLL_S seconds. A worker's account
proxied through the hub joins later (``add``)."""
def __init__(self, mirrors: list[AccountMirror]):
super().__init__(mirrors, name="opencode-mirror", poll_s=lambda: POLL_S,
on_error=lambda m, e: log.exception("opencode mirror %s", m.account))
if __name__ == "__main__": # one pass, for a manual check: <db> <out dir>
import sys
logging.basicConfig(level=logging.INFO)
m = AccountMirror(sys.argv[3] if len(sys.argv) > 3 else "default",
pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]),
pathlib.Path(sys.argv[2]) / ".state")
print(m.tick(force=True), "records")