compactlab 0.2.0__py3-none-any.whl
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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""DeepSeek Harness (`dsh`) adapter. Experimental: built from the published types and the project's own
|
|
2
|
+
snapshot logs, not yet checked against a real user's history.
|
|
3
|
+
|
|
4
|
+
Logs: `$DSH_HOME/sessions` (default `~/.dsh/sessions`), laid out as
|
|
5
|
+
`--<cwd>--/<session>/session[.vN].jsonl[.zstd]`. Only the newest generation (highest `vN`, none = 0) of a
|
|
6
|
+
session is read. `.jsonl.zstd` is a chain of independent zstd frames (header frame, then one per append
|
|
7
|
+
batch); it is decoded with the standard library on Python 3.14+ (`compression.zstd`), else with the `zstd`
|
|
8
|
+
command, else skipped and reported by `doctor`. A torn last frame is dropped, as dsh itself does.
|
|
9
|
+
|
|
10
|
+
Rows: a `session` header (`id`, `parentSession`, `origin: "subagent"`, `isSeeded`), then events
|
|
11
|
+
`{type, seq, time, data}`. Usage is `assistant/message` → `data.usage` with DISJOINT counts:
|
|
12
|
+
`inputTokens` (uncached), `cacheReadTokens`, `cacheWriteTokens`, `outputTokens`. Compactions are
|
|
13
|
+
`compaction/start|summary|end`; a summary followed by an `end` with `error` is dropped. A seeded fork copies
|
|
14
|
+
its parent's events up to `session/end-seed`; usage before that marker is not counted.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib.util
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import shutil
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
from collections.abc import Iterator
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from ..model import Compaction, Session, Turn
|
|
30
|
+
from .base import Adapter, Parser, env_roots, parse_lines, parse_ts, register
|
|
31
|
+
|
|
32
|
+
KNOWN_TYPES = {
|
|
33
|
+
"session",
|
|
34
|
+
"assistant/message",
|
|
35
|
+
"assistant/attempt",
|
|
36
|
+
"user/message",
|
|
37
|
+
"system/message",
|
|
38
|
+
"developer/message",
|
|
39
|
+
"tool/call",
|
|
40
|
+
"tool/result",
|
|
41
|
+
"compaction/start",
|
|
42
|
+
"compaction/summary",
|
|
43
|
+
"compaction/end",
|
|
44
|
+
"session/end-seed",
|
|
45
|
+
"request/header",
|
|
46
|
+
"request/context",
|
|
47
|
+
"turn/start",
|
|
48
|
+
"turn/end",
|
|
49
|
+
"step/start",
|
|
50
|
+
"step/end",
|
|
51
|
+
"agent/inbox/spliced",
|
|
52
|
+
"session/title",
|
|
53
|
+
"session/title-llm-request",
|
|
54
|
+
"sandbox/mode",
|
|
55
|
+
"approval/policy",
|
|
56
|
+
"permission/preset",
|
|
57
|
+
"model/selection",
|
|
58
|
+
"working-directory/change",
|
|
59
|
+
"goal/change",
|
|
60
|
+
"image/offload",
|
|
61
|
+
"job/registered",
|
|
62
|
+
"job/settled",
|
|
63
|
+
"subagent/catalog",
|
|
64
|
+
"subagent/descriptor",
|
|
65
|
+
}
|
|
66
|
+
_GEN = re.compile(r"^session(?:\.v(\d+))?\.jsonl(\.zstd)?$")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _text_of(content: Any) -> str:
|
|
70
|
+
if isinstance(content, str):
|
|
71
|
+
return content
|
|
72
|
+
if isinstance(content, list):
|
|
73
|
+
return " ".join(str(b.get("text", "")) for b in content if isinstance(b, dict) and b.get("type") == "text")
|
|
74
|
+
return ""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _stream_time(data: dict[str, Any]) -> float | None:
|
|
78
|
+
"""Latest chunk time in an embedded provider stream (rows may lack their own `time`)."""
|
|
79
|
+
best = None
|
|
80
|
+
for c in data.get("stream") or []:
|
|
81
|
+
if isinstance(c, dict):
|
|
82
|
+
for k in ("time", "time0"):
|
|
83
|
+
v = c.get(k)
|
|
84
|
+
if isinstance(v, (int, float)) and v > 0 and (best is None or v > best):
|
|
85
|
+
best = v
|
|
86
|
+
return parse_ts(best) if best else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def zstd_decode(raw: bytes) -> bytes | None:
|
|
90
|
+
"""Decode concatenated zstd frames, keeping every complete frame. None when no decoder is available."""
|
|
91
|
+
try:
|
|
92
|
+
from compression import zstd # type: ignore[import-not-found] # Python 3.14+
|
|
93
|
+
except ImportError:
|
|
94
|
+
exe = shutil.which("zstd")
|
|
95
|
+
if not exe:
|
|
96
|
+
return None
|
|
97
|
+
r = subprocess.run([exe, "-dcq"], input=raw, capture_output=True, check=False)
|
|
98
|
+
return r.stdout # on a torn tail zstd exits non-zero after writing what it could decode
|
|
99
|
+
out = bytearray()
|
|
100
|
+
while raw:
|
|
101
|
+
d = zstd.ZstdDecompressor()
|
|
102
|
+
try:
|
|
103
|
+
chunk = d.decompress(raw)
|
|
104
|
+
except zstd.ZstdError:
|
|
105
|
+
break
|
|
106
|
+
if not d.eof:
|
|
107
|
+
break # torn last frame: dsh truncates it too
|
|
108
|
+
out += chunk
|
|
109
|
+
raw = d.unused_data
|
|
110
|
+
return bytes(out)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def zstd_available() -> bool:
|
|
114
|
+
stdlib = sys.version_info >= (3, 14) and importlib.util.find_spec("compression.zstd") is not None
|
|
115
|
+
return stdlib or shutil.which("zstd") is not None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class DshParser(Parser):
|
|
119
|
+
version = 1
|
|
120
|
+
|
|
121
|
+
def __init__(self, path: str):
|
|
122
|
+
self.session = Session(id=Path(path).parent.name, harness="dsh", role="main", path=path)
|
|
123
|
+
self.model = "unknown"
|
|
124
|
+
self.seeded = False
|
|
125
|
+
self.pending_user = ""
|
|
126
|
+
self.call_turn: dict[str, int] = {}
|
|
127
|
+
self.last_input_ts: float | None = None
|
|
128
|
+
self.compact_start: float | None = None
|
|
129
|
+
|
|
130
|
+
def feed(self, d: dict[str, Any]) -> None:
|
|
131
|
+
s = self.session
|
|
132
|
+
typ = str(d.get("type"))
|
|
133
|
+
raw = d.get("data")
|
|
134
|
+
data: dict[str, Any] = raw if isinstance(raw, dict) else {}
|
|
135
|
+
if typ not in KNOWN_TYPES:
|
|
136
|
+
self.note_unknown(s, typ)
|
|
137
|
+
return
|
|
138
|
+
ts = parse_ts(d.get("time"))
|
|
139
|
+
if typ == "session":
|
|
140
|
+
s.id = str(d.get("id") or s.id)
|
|
141
|
+
s.parent_id = str(d["parentSession"]) if d.get("parentSession") else None
|
|
142
|
+
s.role = "subagent" if d.get("origin") == "subagent" else "main"
|
|
143
|
+
self.seeded = bool(d.get("isSeeded"))
|
|
144
|
+
elif typ == "session/end-seed":
|
|
145
|
+
self.seeded = False
|
|
146
|
+
elif typ == "request/context":
|
|
147
|
+
self.model = str(data.get("model") or self.model)
|
|
148
|
+
if data.get("contextWindow"):
|
|
149
|
+
s.context_window = int(data["contextWindow"])
|
|
150
|
+
elif typ in ("user/message", "tool/result"):
|
|
151
|
+
if typ == "user/message":
|
|
152
|
+
self.pending_user = _text_of(data.get("content"))
|
|
153
|
+
else:
|
|
154
|
+
self._tool_result(data)
|
|
155
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
156
|
+
elif typ == "tool/call" and s.turns and not self.seeded:
|
|
157
|
+
key = f"{data.get('name', '?')}:{self._arg(data.get('arguments'))}"
|
|
158
|
+
s.turns[-1].tool_keys.append(key)
|
|
159
|
+
self.call_turn[str(data.get("callId", ""))] = len(s.turns) - 1
|
|
160
|
+
elif typ == "assistant/message":
|
|
161
|
+
self._assistant(data, ts)
|
|
162
|
+
elif typ == "compaction/start":
|
|
163
|
+
self.compact_start = ts
|
|
164
|
+
elif typ == "compaction/summary" and not self.seeded:
|
|
165
|
+
s.compactions.append(
|
|
166
|
+
Compaction(
|
|
167
|
+
turn_index=len(s.turns),
|
|
168
|
+
pre_tokens=s.turns[-1].ctx if s.turns else None,
|
|
169
|
+
ts=ts,
|
|
170
|
+
summary_text=str(data.get("summary") or _text_of(data.get("rawOutput")))[:2000],
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
elif typ == "compaction/end" and not self.seeded:
|
|
174
|
+
c = s.compactions[-1] if s.compactions else None
|
|
175
|
+
if c is not None and c.turn_index == len(s.turns):
|
|
176
|
+
if data.get("error"):
|
|
177
|
+
s.compactions.pop()
|
|
178
|
+
elif ts and self.compact_start and 0 < ts - self.compact_start <= 900:
|
|
179
|
+
c.duration_s = ts - self.compact_start
|
|
180
|
+
self.compact_start = None
|
|
181
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def _arg(args: Any) -> str:
|
|
185
|
+
try:
|
|
186
|
+
a = json.loads(args) if isinstance(args, str) else (args or {})
|
|
187
|
+
except ValueError:
|
|
188
|
+
return str(args)[:200]
|
|
189
|
+
if isinstance(a, dict):
|
|
190
|
+
v = a.get("file_path") or a.get("path") or a.get("pattern") or a.get("command") or a.get("query") or ""
|
|
191
|
+
return str(v)[:200]
|
|
192
|
+
return str(a)[:200]
|
|
193
|
+
|
|
194
|
+
def _tool_result(self, data: dict[str, Any]) -> None:
|
|
195
|
+
s = self.session
|
|
196
|
+
m = data.get("message") or {}
|
|
197
|
+
if self.seeded or not s.turns or not isinstance(m, dict):
|
|
198
|
+
return
|
|
199
|
+
body = _text_of(m.get("content"))
|
|
200
|
+
idx = self.call_turn.get(str(m.get("toolCallId", "")), len(s.turns) - 1)
|
|
201
|
+
s.turns[idx].snippets.append(body[:400])
|
|
202
|
+
s.turns[idx].tool_result_tokens.append(len(body) // 4)
|
|
203
|
+
|
|
204
|
+
def _assistant(self, data: dict[str, Any], ts: float | None) -> None:
|
|
205
|
+
s = self.session
|
|
206
|
+
u = data.get("usage")
|
|
207
|
+
if not isinstance(u, dict):
|
|
208
|
+
return
|
|
209
|
+
if self.seeded:
|
|
210
|
+
s.skipped_inherited += 1 # copied from the parent session
|
|
211
|
+
return
|
|
212
|
+
inp, cr, cw, out = (
|
|
213
|
+
int(u.get(k) or 0) for k in ("inputTokens", "cacheReadTokens", "cacheWriteTokens", "outputTokens")
|
|
214
|
+
)
|
|
215
|
+
src = (data.get("message") or {}).get("source") or {}
|
|
216
|
+
model = str(src.get("model") or self.model)
|
|
217
|
+
s.turns.append(
|
|
218
|
+
Turn(
|
|
219
|
+
ts=ts or _stream_time(data),
|
|
220
|
+
ctx=inp + cr + cw,
|
|
221
|
+
cache_read=cr,
|
|
222
|
+
cache_write=cw,
|
|
223
|
+
output=out,
|
|
224
|
+
model=model,
|
|
225
|
+
user_text=self.pending_user,
|
|
226
|
+
start_ts=self.last_input_ts,
|
|
227
|
+
)
|
|
228
|
+
)
|
|
229
|
+
self.pending_user = ""
|
|
230
|
+
|
|
231
|
+
def finish(self) -> Session:
|
|
232
|
+
from ..model import snapshot
|
|
233
|
+
|
|
234
|
+
return snapshot(self.session)
|
|
235
|
+
|
|
236
|
+
def dump(self) -> dict[str, Any]:
|
|
237
|
+
from ..model import session_to_dict
|
|
238
|
+
|
|
239
|
+
st = {k: v for k, v in self.__dict__.items() if k != "session"}
|
|
240
|
+
return {"path": self.session.path, "session": session_to_dict(self.session), **st}
|
|
241
|
+
|
|
242
|
+
@classmethod
|
|
243
|
+
def load(cls, state: dict[str, Any]) -> DshParser:
|
|
244
|
+
from ..model import session_from_dict
|
|
245
|
+
|
|
246
|
+
p = cls(state["path"])
|
|
247
|
+
if "session" in state:
|
|
248
|
+
p.session = session_from_dict(state["session"])
|
|
249
|
+
for k in ("model", "seeded", "pending_user", "call_turn", "last_input_ts", "compact_start"):
|
|
250
|
+
setattr(p, k, state.get(k, getattr(p, k)))
|
|
251
|
+
return p
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@register
|
|
255
|
+
class DshAdapter(Adapter):
|
|
256
|
+
name = "dsh"
|
|
257
|
+
parser_cls = DshParser
|
|
258
|
+
resumable = False # zstd frames: re-parse a changed file from the start
|
|
259
|
+
|
|
260
|
+
@classmethod
|
|
261
|
+
def default_roots(cls) -> list[Path]:
|
|
262
|
+
return env_roots("DSH_HOME", "sessions", ["~/.dsh/sessions"])
|
|
263
|
+
|
|
264
|
+
def find_files(self) -> Iterator[Path]:
|
|
265
|
+
"""The newest generation of each session directory."""
|
|
266
|
+
best: dict[Path, tuple[int, Path]] = {}
|
|
267
|
+
for r in self.roots:
|
|
268
|
+
if not r.exists():
|
|
269
|
+
continue
|
|
270
|
+
for f in r.rglob("session*.jsonl*"):
|
|
271
|
+
m = _GEN.match(f.name)
|
|
272
|
+
if not m:
|
|
273
|
+
continue
|
|
274
|
+
gen = int(m.group(1) or 0)
|
|
275
|
+
if f.parent not in best or gen > best[f.parent][0]:
|
|
276
|
+
best[f.parent] = (gen, f)
|
|
277
|
+
for _, f in sorted(best.values(), key=lambda x: str(x[1])):
|
|
278
|
+
yield f
|
|
279
|
+
|
|
280
|
+
def read_records(self, path: Path, parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
281
|
+
raw = path.read_bytes()
|
|
282
|
+
if path.suffix == ".zstd":
|
|
283
|
+
dec = zstd_decode(raw)
|
|
284
|
+
if dec is None:
|
|
285
|
+
return # no decoder; doctor says so
|
|
286
|
+
raw = dec
|
|
287
|
+
yield from parse_lines(iter(raw.splitlines()), parser) # a torn last line counts as a parse error
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Gemini CLI adapter. Experimental: built from the public source (v0.46.0 and v0.70.0); no real chat log was
|
|
2
|
+
available to check it against.
|
|
3
|
+
|
|
4
|
+
Logs: `$GEMINI_CLI_HOME/.gemini/tmp` (default `~/.gemini/tmp`), as
|
|
5
|
+
`<project>/chats/session-<YYYY-MM-DDTHH-MM>-<id8>.jsonl`; a subagent run is `<project>/chats/<parent session>/
|
|
6
|
+
<session>.jsonl` with `kind: "subagent"` in its header. `<project>` is a slug from `~/.gemini/projects.json` (older
|
|
7
|
+
versions used a SHA-256 of the project root). Older versions wrote one `session-*.json` document instead; it is read
|
|
8
|
+
the same way unless a `.jsonl` of the same name replaced it.
|
|
9
|
+
|
|
10
|
+
Lines: a header `{sessionId, projectHash, startTime, lastUpdated, kind?}`, message lines `{id, timestamp, type, ...}`
|
|
11
|
+
with type `user | gemini | info | error | warning`, and updates `{"$set": ...}`, `{"$rewindTo": id}`, `{"$patch": ...}`
|
|
12
|
+
(0.70+). A message is written again with the same id when its tokens or tool calls are attached; the last line wins,
|
|
13
|
+
so turns are keyed by id. Each `gemini` message is one API call with `tokens {input, output, cached, thoughts, tool,
|
|
14
|
+
total}`, where `input` is the whole prompt INCLUDING `cached` (Gemini's promptTokenCount). Tool results come back as
|
|
15
|
+
`user` messages made of functionResponse parts.
|
|
16
|
+
|
|
17
|
+
Compression leaves no explicit record. Its summary is a synthetic user message whose text holds `<state_snapshot>`:
|
|
18
|
+
appended as a line (0.70+, followed by a `$patch` that removes the old ids) or inside a `{"$set": {"messages": [...]}}`
|
|
19
|
+
checkpoint (0.46). The summary call's own usage is not written, and `/compress` looks the same as an automatic one.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
from collections.abc import Iterator
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from ..model import Compaction, Session, Turn
|
|
30
|
+
from .base import Adapter, BadRecord, Parser, _bump_error, count, env_roots, iter_jsonl, parse_ts, register
|
|
31
|
+
|
|
32
|
+
MESSAGE_TYPES = {"user", "gemini", "info", "error", "warning"}
|
|
33
|
+
SNAPSHOT = "<state_snapshot>"
|
|
34
|
+
_ARG_KEYS = ("file_path", "absolute_path", "path", "dir_path", "pattern", "command", "query", "url")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def token_limit(model: str) -> int:
|
|
38
|
+
"""Gemini CLI's own window for a model (core/tokenLimits.ts): 256k for Gemma 4, else 1,048,576."""
|
|
39
|
+
return 256_000 if "gemma-4" in (model or "").lower() else 1_048_576
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _obj(v: Any) -> dict[str, Any]:
|
|
43
|
+
return v if isinstance(v, dict) else {}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parts(content: Any) -> list[Any]:
|
|
47
|
+
if isinstance(content, list):
|
|
48
|
+
return content
|
|
49
|
+
return [content] if content else []
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _text(content: Any) -> str:
|
|
53
|
+
out = []
|
|
54
|
+
for p in _parts(content):
|
|
55
|
+
if isinstance(p, str):
|
|
56
|
+
out.append(p)
|
|
57
|
+
elif isinstance(p, dict) and isinstance(p.get("text"), str):
|
|
58
|
+
out.append(p["text"])
|
|
59
|
+
return " ".join(out)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_tool_result(content: Any) -> bool:
|
|
63
|
+
return any(isinstance(p, dict) and "functionResponse" in p for p in _parts(content))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _tool_key(call: dict[str, Any]) -> str:
|
|
67
|
+
args = _obj(call.get("args"))
|
|
68
|
+
arg = next((args[k] for k in _ARG_KEYS if args.get(k)), "")
|
|
69
|
+
return f"{call.get('name', '?')}:{str(arg)[:200]}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class GeminiParser(Parser):
|
|
73
|
+
version = 1
|
|
74
|
+
|
|
75
|
+
def __init__(self, path: str):
|
|
76
|
+
p = Path(path)
|
|
77
|
+
sub = p.parent.name != "chats" and p.parent.parent.name == "chats"
|
|
78
|
+
self.session = Session(id=p.stem, harness="gemini-cli", role="subagent" if sub else "main", path=path)
|
|
79
|
+
if sub:
|
|
80
|
+
self.session.parent_id = p.parent.name
|
|
81
|
+
self.turn_of: dict[str, int] = {} # gemini message id -> turn index
|
|
82
|
+
self.users: list[str] = [] # user message ids already read
|
|
83
|
+
self.snapshots: list[str] = [] # summary message ids already counted as a compaction
|
|
84
|
+
self.pending_user = ""
|
|
85
|
+
self.last_input_ts: float | None = None
|
|
86
|
+
|
|
87
|
+
def feed(self, d: dict[str, Any]) -> None:
|
|
88
|
+
s = self.session
|
|
89
|
+
try:
|
|
90
|
+
if "$set" in d:
|
|
91
|
+
msgs = _obj(d["$set"]).get("messages")
|
|
92
|
+
for m in msgs if isinstance(msgs, list) else []:
|
|
93
|
+
if isinstance(m, dict) and m.get("type") == "user" and SNAPSHOT in _text(m.get("content")):
|
|
94
|
+
self._compaction(m) # a 0.46 checkpoint that replaced the history
|
|
95
|
+
elif "$rewindTo" in d or "$patch" in d:
|
|
96
|
+
pass # rewinds and patches change the saved history, not what was billed
|
|
97
|
+
elif "id" in d and "type" in d:
|
|
98
|
+
self._message(d)
|
|
99
|
+
elif "sessionId" in d:
|
|
100
|
+
s.id = str(d["sessionId"])
|
|
101
|
+
if d.get("kind") == "subagent":
|
|
102
|
+
s.role = "subagent"
|
|
103
|
+
else:
|
|
104
|
+
self.note_unknown(s, "record")
|
|
105
|
+
except BadRecord:
|
|
106
|
+
s.parse_errors += 1
|
|
107
|
+
|
|
108
|
+
def _message(self, d: dict[str, Any]) -> None:
|
|
109
|
+
typ, mid, ts = str(d.get("type")), str(d.get("id")), parse_ts(d.get("timestamp"))
|
|
110
|
+
if typ not in MESSAGE_TYPES:
|
|
111
|
+
self.note_unknown(self.session, f"message:{typ}")
|
|
112
|
+
elif typ == "user":
|
|
113
|
+
text = _text(d.get("content"))
|
|
114
|
+
if SNAPSHOT in text:
|
|
115
|
+
self._compaction(d)
|
|
116
|
+
elif mid not in self.users:
|
|
117
|
+
self.users.append(mid)
|
|
118
|
+
if _is_tool_result(d.get("content")):
|
|
119
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
120
|
+
else:
|
|
121
|
+
self.pending_user = (self.pending_user + " " + text).strip()
|
|
122
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
123
|
+
elif typ == "gemini":
|
|
124
|
+
self._gemini(d, mid, ts)
|
|
125
|
+
|
|
126
|
+
def _gemini(self, d: dict[str, Any], mid: str, ts: float | None) -> None:
|
|
127
|
+
s = self.session
|
|
128
|
+
tk = d.get("tokens")
|
|
129
|
+
idx = self.turn_of.get(mid)
|
|
130
|
+
if not isinstance(tk, dict):
|
|
131
|
+
if idx is not None and d.get("toolCalls"):
|
|
132
|
+
self._replace(idx, tool_calls=d["toolCalls"])
|
|
133
|
+
return
|
|
134
|
+
inp, cached, tool = count(tk.get("input")), count(tk.get("cached")), count(tk.get("tool"))
|
|
135
|
+
out = count(tk.get("output")) + count(tk.get("thoughts"))
|
|
136
|
+
if inp + out == 0:
|
|
137
|
+
return
|
|
138
|
+
calls = [c for c in d.get("toolCalls") or [] if isinstance(c, dict)]
|
|
139
|
+
model = str(d.get("model") or (s.turns[-1].model if s.turns else "unknown"))
|
|
140
|
+
turn = Turn(
|
|
141
|
+
ts=ts,
|
|
142
|
+
ctx=inp + tool,
|
|
143
|
+
cache_read=min(cached, inp),
|
|
144
|
+
output=out,
|
|
145
|
+
model=model,
|
|
146
|
+
tool_keys=[_tool_key(c) for c in calls],
|
|
147
|
+
tool_result_tokens=[len(json.dumps(c.get("result"), default=str)) // 4 for c in calls],
|
|
148
|
+
snippets=[json.dumps(c.get("result"), default=str)[:400] for c in calls if c.get("result")],
|
|
149
|
+
user_text=self.pending_user,
|
|
150
|
+
start_ts=self.last_input_ts,
|
|
151
|
+
)
|
|
152
|
+
if idx is None:
|
|
153
|
+
self.turn_of[mid] = len(s.turns)
|
|
154
|
+
s.turns.append(turn)
|
|
155
|
+
self.pending_user = ""
|
|
156
|
+
else: # the same call written again: keep where it started, take the newer counts and tools
|
|
157
|
+
old = s.turns[idx]
|
|
158
|
+
turn.user_text, turn.correction = old.user_text, old.correction
|
|
159
|
+
turn.start_ts, turn.ts = old.start_ts, old.ts or ts
|
|
160
|
+
s.turns[idx] = turn
|
|
161
|
+
|
|
162
|
+
def _replace(self, idx: int, tool_calls: Any) -> None:
|
|
163
|
+
old = self.session.turns[idx]
|
|
164
|
+
calls = [c for c in tool_calls if isinstance(c, dict)] if isinstance(tool_calls, list) else []
|
|
165
|
+
self.session.turns[idx] = Turn(
|
|
166
|
+
**{
|
|
167
|
+
**vars(old),
|
|
168
|
+
"tool_keys": [_tool_key(c) for c in calls],
|
|
169
|
+
"tool_result_tokens": [len(json.dumps(c.get("result"), default=str)) // 4 for c in calls],
|
|
170
|
+
"snippets": [json.dumps(c.get("result"), default=str)[:400] for c in calls if c.get("result")],
|
|
171
|
+
}
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _compaction(self, m: dict[str, Any]) -> None:
|
|
175
|
+
mid = str(m.get("id"))
|
|
176
|
+
if mid in self.snapshots:
|
|
177
|
+
return
|
|
178
|
+
self.snapshots.append(mid)
|
|
179
|
+
s = self.session
|
|
180
|
+
ts = parse_ts(m.get("timestamp"))
|
|
181
|
+
if s.compactions and s.compactions[-1].turn_index == len(s.turns):
|
|
182
|
+
return # the 0.46 checkpoint after an appended summary: the same compaction
|
|
183
|
+
s.compactions.append(
|
|
184
|
+
Compaction(
|
|
185
|
+
turn_index=len(s.turns),
|
|
186
|
+
pre_tokens=s.turns[-1].ctx if s.turns else None,
|
|
187
|
+
ts=ts,
|
|
188
|
+
summary_text=_text(m.get("content"))[:2000],
|
|
189
|
+
)
|
|
190
|
+
)
|
|
191
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
192
|
+
|
|
193
|
+
def finish(self) -> Session:
|
|
194
|
+
from ..model import snapshot
|
|
195
|
+
|
|
196
|
+
out = snapshot(self.session)
|
|
197
|
+
if out.turns: # the window of the model the session is grouped under (its most-used one), not the largest
|
|
198
|
+
out.context_window = token_limit(out.model)
|
|
199
|
+
return out
|
|
200
|
+
|
|
201
|
+
def dump(self) -> dict[str, Any]:
|
|
202
|
+
from ..model import session_to_dict
|
|
203
|
+
|
|
204
|
+
st = {k: v for k, v in self.__dict__.items() if k != "session"}
|
|
205
|
+
return {"path": self.session.path, "session": session_to_dict(self.session), **st}
|
|
206
|
+
|
|
207
|
+
@classmethod
|
|
208
|
+
def load(cls, state: dict[str, Any]) -> GeminiParser:
|
|
209
|
+
from ..model import session_from_dict
|
|
210
|
+
|
|
211
|
+
p = cls(state["path"])
|
|
212
|
+
if "session" in state:
|
|
213
|
+
p.session = session_from_dict(state["session"])
|
|
214
|
+
for k in ("turn_of", "users", "snapshots", "pending_user", "last_input_ts"):
|
|
215
|
+
setattr(p, k, state.get(k, getattr(p, k)))
|
|
216
|
+
return p
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@register
|
|
220
|
+
class GeminiAdapter(Adapter):
|
|
221
|
+
name = "gemini-cli"
|
|
222
|
+
parser_cls = GeminiParser
|
|
223
|
+
resumable = False # a legacy .json session is rewritten in place; re-parse a changed file from the start
|
|
224
|
+
|
|
225
|
+
@classmethod
|
|
226
|
+
def default_roots(cls) -> list[Path]:
|
|
227
|
+
return env_roots("GEMINI_CLI_HOME", ".gemini/tmp", ["~/.gemini/tmp"])
|
|
228
|
+
|
|
229
|
+
@classmethod
|
|
230
|
+
def config_paths(cls) -> list[Path]:
|
|
231
|
+
return [r.parent / "settings.json" for r in cls.default_roots()]
|
|
232
|
+
|
|
233
|
+
def find_files(self) -> Iterator[Path]:
|
|
234
|
+
for r in self.roots:
|
|
235
|
+
if not r.exists():
|
|
236
|
+
continue
|
|
237
|
+
files = [*r.glob("*/chats/*.jsonl"), *r.glob("*/chats/*/*.jsonl")]
|
|
238
|
+
stems = {(f.parent, f.stem) for f in files}
|
|
239
|
+
files += [f for f in r.glob("*/chats/session-*.json") if (f.parent, f.stem) not in stems]
|
|
240
|
+
yield from sorted(files)
|
|
241
|
+
|
|
242
|
+
def read_records(self, path: Path, parser: Parser | None = None) -> Iterator[dict[str, Any]]:
|
|
243
|
+
if path.suffix != ".json":
|
|
244
|
+
yield from iter_jsonl(path, parser)
|
|
245
|
+
return
|
|
246
|
+
try:
|
|
247
|
+
doc = json.loads(path.read_bytes())
|
|
248
|
+
except (ValueError, UnicodeDecodeError):
|
|
249
|
+
_bump_error(parser)
|
|
250
|
+
return
|
|
251
|
+
if not isinstance(doc, dict):
|
|
252
|
+
_bump_error(parser)
|
|
253
|
+
return
|
|
254
|
+
yield {k: v for k, v in doc.items() if k != "messages"}
|
|
255
|
+
for m in doc.get("messages") or []:
|
|
256
|
+
if isinstance(m, dict):
|
|
257
|
+
yield m
|
|
258
|
+
else:
|
|
259
|
+
_bump_error(parser)
|