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,226 @@
|
|
|
1
|
+
"""Claude Code adapter.
|
|
2
|
+
|
|
3
|
+
Transcripts: `$CLAUDE_CONFIG_DIR/projects` (comma-separated dirs allowed), else `~/.claude/projects`
|
|
4
|
+
and the legacy `~/.config/claude/projects`. Files under a `subagents/` directory are subagent runs.
|
|
5
|
+
See `data/harness_formats.json` for the format facts this relies on and their verification status.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ..model import Compaction, Session, Turn
|
|
14
|
+
from .base import Adapter, BadRecord, Parser, count, env_roots, parse_ts, register
|
|
15
|
+
|
|
16
|
+
KNOWN_TYPES = {"user", "assistant", "system", "summary", "file-history-snapshot", "attachment", "progress"}
|
|
17
|
+
# Idle compaction (`idleCompaction`, on by default) summarizes a long conversation left idle on the one-hour cache
|
|
18
|
+
# while that cache is still warm (about 55 min in) and applies the summary when the user returns. In the log it is an
|
|
19
|
+
# "auto" boundary written on return, an hour or more after the last turn, that took almost no time (the summary was
|
|
20
|
+
# ready; newer versions also say `precomputed: true`). A boundary on return that did take a summarizer call's time is
|
|
21
|
+
# the threshold: the context was already over it.
|
|
22
|
+
IDLE_GAP_S = 50 * 60
|
|
23
|
+
IDLE_DONE_MS = 5000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _text_of(content: Any) -> str:
|
|
27
|
+
if isinstance(content, str):
|
|
28
|
+
return content
|
|
29
|
+
if isinstance(content, list):
|
|
30
|
+
return " ".join(str(b.get("text", "")) for b in content if isinstance(b, dict) and b.get("type") == "text")
|
|
31
|
+
return ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _tool_key(block: dict[str, Any]) -> str:
|
|
35
|
+
inp = block.get("input")
|
|
36
|
+
inp = inp if isinstance(inp, dict) else {}
|
|
37
|
+
arg = inp.get("file_path") or inp.get("path") or inp.get("pattern") or inp.get("command") or inp.get("query") or ""
|
|
38
|
+
return f"{block.get('name', '?')}:{str(arg)[:200]}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ClaudeParser(Parser):
|
|
42
|
+
version = 5 # 5: idle compactions, compaction duration from durationMs
|
|
43
|
+
rewrites_history = True # resumes, rewinds and /compact can append copies of earlier messages
|
|
44
|
+
|
|
45
|
+
def __init__(self, path: str):
|
|
46
|
+
role = "subagent" if "subagents" in Path(path).parts else "main"
|
|
47
|
+
self.session = Session(id=Path(path).stem, harness="claude-code", role=role, path=path)
|
|
48
|
+
self.seen: set[str] = set()
|
|
49
|
+
self.replayed_summary = False
|
|
50
|
+
self.boundaries: set[tuple[str, float | None, Any]] = set() # Claude Code re-writes old boundaries later
|
|
51
|
+
self.pending_user = ""
|
|
52
|
+
self.tool_turn: dict[str, int] = {}
|
|
53
|
+
self.last_input_ts: float | None = None # last user / tool-result / system line
|
|
54
|
+
|
|
55
|
+
def feed(self, d: dict[str, Any]) -> None:
|
|
56
|
+
s = self.session
|
|
57
|
+
typ = d.get("type")
|
|
58
|
+
if typ not in KNOWN_TYPES:
|
|
59
|
+
self.note_unknown(s, str(typ))
|
|
60
|
+
if s.parent_id is None and d.get("parentSessionId"):
|
|
61
|
+
s.parent_id = str(d["parentSessionId"])
|
|
62
|
+
if d.get("cwd"):
|
|
63
|
+
self.cwd = str(d["cwd"])
|
|
64
|
+
ts = parse_ts(d.get("timestamp"))
|
|
65
|
+
if typ == "system" and d.get("subtype") == "compact_boundary":
|
|
66
|
+
meta = d.get("compactMetadata")
|
|
67
|
+
meta = meta if isinstance(meta, dict) else {}
|
|
68
|
+
key = (str(d.get("uuid") or ""), ts, meta.get("preTokens"))
|
|
69
|
+
if key in self.boundaries:
|
|
70
|
+
self.replayed_summary = True # its summary line is re-written too
|
|
71
|
+
return
|
|
72
|
+
self.boundaries.add(key)
|
|
73
|
+
try:
|
|
74
|
+
pre = count(meta.get("preTokens")) if meta.get("preTokens") is not None else None
|
|
75
|
+
except BadRecord:
|
|
76
|
+
s.parse_errors += 1
|
|
77
|
+
return
|
|
78
|
+
trigger = str(meta["trigger"]) if meta.get("trigger") in ("auto", "manual") else ""
|
|
79
|
+
ms = meta.get("durationMs")
|
|
80
|
+
ms = float(ms) if isinstance(ms, (int, float)) and not isinstance(ms, bool) and ms >= 0 else None
|
|
81
|
+
last_turn = s.turns[-1].ts if s.turns else None
|
|
82
|
+
idle = (
|
|
83
|
+
trigger == "auto"
|
|
84
|
+
and bool(ts and last_turn and ts - last_turn >= IDLE_GAP_S)
|
|
85
|
+
and (meta.get("precomputed") is True or (ms is not None and ms < IDLE_DONE_MS))
|
|
86
|
+
)
|
|
87
|
+
if ms is not None:
|
|
88
|
+
dur: float | None = ms / 1000
|
|
89
|
+
else:
|
|
90
|
+
dur = (ts - self.last_input_ts) if (ts and self.last_input_ts) else None
|
|
91
|
+
s.compactions.append(
|
|
92
|
+
Compaction(
|
|
93
|
+
turn_index=len(s.turns),
|
|
94
|
+
pre_tokens=pre,
|
|
95
|
+
ts=ts,
|
|
96
|
+
duration_s=None if idle or dur is None or not 0 < dur <= 900 else dur,
|
|
97
|
+
trigger=trigger,
|
|
98
|
+
idle=idle,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
self.last_input_ts = ts
|
|
102
|
+
return
|
|
103
|
+
m = d.get("message")
|
|
104
|
+
if not isinstance(m, dict):
|
|
105
|
+
return
|
|
106
|
+
if m.get("role") == "user":
|
|
107
|
+
self._user(d, m)
|
|
108
|
+
if ts:
|
|
109
|
+
self.last_input_ts = ts
|
|
110
|
+
elif m.get("role") == "assistant":
|
|
111
|
+
self._assistant(d, m)
|
|
112
|
+
|
|
113
|
+
def _user(self, d: dict[str, Any], m: dict[str, Any]) -> None:
|
|
114
|
+
s = self.session
|
|
115
|
+
content = m.get("content")
|
|
116
|
+
text = _text_of(content)
|
|
117
|
+
if d.get("isCompactSummary"):
|
|
118
|
+
if self.replayed_summary:
|
|
119
|
+
self.replayed_summary = False
|
|
120
|
+
elif s.compactions:
|
|
121
|
+
s.compactions[-1].set_summary(text)
|
|
122
|
+
return
|
|
123
|
+
if isinstance(content, list):
|
|
124
|
+
for b in content:
|
|
125
|
+
if isinstance(b, dict) and b.get("type") == "tool_result":
|
|
126
|
+
idx = self.tool_turn.get(str(b.get("tool_use_id")))
|
|
127
|
+
if idx is not None and idx < len(s.turns):
|
|
128
|
+
c = b.get("content")
|
|
129
|
+
body = c if isinstance(c, str) else _text_of(c)
|
|
130
|
+
s.turns[idx].snippets.append(body[:400])
|
|
131
|
+
s.turns[idx].tool_result_tokens.append(len(body) // 4)
|
|
132
|
+
if text and not d.get("isMeta"):
|
|
133
|
+
self.pending_user = text
|
|
134
|
+
|
|
135
|
+
def _assistant(self, d: dict[str, Any], m: dict[str, Any]) -> None:
|
|
136
|
+
s = self.session
|
|
137
|
+
mid = m.get("id")
|
|
138
|
+
key = f"{mid}:{d.get('requestId', '')}" if mid else ""
|
|
139
|
+
# Streaming writes the same API response several times; message id (+ request id) identifies it.
|
|
140
|
+
if key and key in self.seen:
|
|
141
|
+
return
|
|
142
|
+
u = m.get("usage")
|
|
143
|
+
u = u if isinstance(u, dict) else {}
|
|
144
|
+
try:
|
|
145
|
+
cr = count(u.get("cache_read_input_tokens"))
|
|
146
|
+
cw = count(u.get("cache_creation_input_tokens"))
|
|
147
|
+
tiers = u.get("cache_creation")
|
|
148
|
+
tiers = tiers if isinstance(tiers, dict) else {}
|
|
149
|
+
cw_1h = min(count(tiers.get("ephemeral_1h_input_tokens")), cw)
|
|
150
|
+
ctx = count(u.get("input_tokens")) + cr + cw
|
|
151
|
+
out = count(u.get("output_tokens"))
|
|
152
|
+
except BadRecord:
|
|
153
|
+
s.parse_errors += 1 # skipped; a clean re-emission of the same message may still count
|
|
154
|
+
return
|
|
155
|
+
if key:
|
|
156
|
+
self.seen.add(key)
|
|
157
|
+
if ctx == 0:
|
|
158
|
+
return
|
|
159
|
+
t = Turn(
|
|
160
|
+
ts=parse_ts(d.get("timestamp")),
|
|
161
|
+
ctx=ctx,
|
|
162
|
+
cache_read=cr,
|
|
163
|
+
cache_write=cw,
|
|
164
|
+
cache_write_1h=cw_1h,
|
|
165
|
+
output=out,
|
|
166
|
+
start_ts=self.last_input_ts,
|
|
167
|
+
model=str(m.get("model") or "unknown"),
|
|
168
|
+
user_text=self.pending_user,
|
|
169
|
+
)
|
|
170
|
+
self.pending_user = ""
|
|
171
|
+
content = m.get("content")
|
|
172
|
+
if isinstance(content, list):
|
|
173
|
+
for b in content:
|
|
174
|
+
if isinstance(b, dict) and b.get("type") == "tool_use":
|
|
175
|
+
t.tool_keys.append(_tool_key(b))
|
|
176
|
+
if b.get("id"):
|
|
177
|
+
self.tool_turn[str(b["id"])] = len(s.turns)
|
|
178
|
+
cmd = (b.get("input") or {}).get("command")
|
|
179
|
+
if cmd:
|
|
180
|
+
t.snippets.append(f"$ {str(cmd)[:200]}")
|
|
181
|
+
s.turns.append(t)
|
|
182
|
+
|
|
183
|
+
def finish(self) -> Session:
|
|
184
|
+
from ..model import snapshot
|
|
185
|
+
|
|
186
|
+
return snapshot(self.session)
|
|
187
|
+
|
|
188
|
+
def dump(self) -> dict[str, Any]:
|
|
189
|
+
from ..model import session_to_dict
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
"path": self.session.path,
|
|
193
|
+
"session": session_to_dict(self.session),
|
|
194
|
+
"seen": sorted(self.seen),
|
|
195
|
+
"pending_user": self.pending_user,
|
|
196
|
+
"tool_turn": self.tool_turn,
|
|
197
|
+
"last_input_ts": self.last_input_ts,
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def load(cls, state: dict[str, Any]) -> ClaudeParser:
|
|
202
|
+
from ..model import session_from_dict
|
|
203
|
+
|
|
204
|
+
p = cls(state["path"])
|
|
205
|
+
if "session" in state:
|
|
206
|
+
p.session = session_from_dict(state["session"])
|
|
207
|
+
p.seen = set(state.get("seen", []))
|
|
208
|
+
p.pending_user = state.get("pending_user", "")
|
|
209
|
+
p.tool_turn = dict(state.get("tool_turn", {}))
|
|
210
|
+
p.last_input_ts = state.get("last_input_ts")
|
|
211
|
+
return p
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@register
|
|
215
|
+
class ClaudeCodeAdapter(Adapter):
|
|
216
|
+
name = "claude-code"
|
|
217
|
+
parser_cls = ClaudeParser
|
|
218
|
+
|
|
219
|
+
@classmethod
|
|
220
|
+
def default_roots(cls) -> list[Path]:
|
|
221
|
+
return env_roots("CLAUDE_CONFIG_DIR", "projects", ["~/.claude/projects", "~/.config/claude/projects"])
|
|
222
|
+
|
|
223
|
+
@classmethod
|
|
224
|
+
def config_paths(cls) -> list[Path]:
|
|
225
|
+
base = env_roots("CLAUDE_CONFIG_DIR", "", ["~/.claude"])
|
|
226
|
+
return [b / "settings.json" for b in base]
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Codex adapter: `$CODEX_HOME/sessions` (default `~/.codex/sessions`) and `archived_sessions`.
|
|
2
|
+
|
|
3
|
+
Rollout lines are `{"timestamp", "type", "payload"}`. Token usage comes from
|
|
4
|
+
`event_msg/token_count` with `info.total_token_usage` (cumulative) and `info.last_token_usage`
|
|
5
|
+
(this request). We use `last_token_usage` as the per-request context size and only fall back to
|
|
6
|
+
the delta of cumulative totals when `last` is missing. Identical re-emitted snapshots are skipped.
|
|
7
|
+
OpenAI semantics: `input_tokens` already includes `cached_input_tokens`.
|
|
8
|
+
|
|
9
|
+
Forks and subagents can start with a copied parent prefix. Signals handled here (ideas from
|
|
10
|
+
CodexBar's rollout-shape analysis, re-implemented): a `forked_from_id` on session_meta, a
|
|
11
|
+
zero-usage opening snapshot (inherited context, not new usage), and an embedded ancestor
|
|
12
|
+
`session_meta` with a different id, after which replayed usage is dropped until the next
|
|
13
|
+
`turn_context`. These are heuristics; see data/harness_formats.json for verification status.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from ..model import Compaction, Session, Turn
|
|
23
|
+
from .base import Adapter, BadRecord, Parser, count, env_roots, parse_ts, register
|
|
24
|
+
|
|
25
|
+
KNOWN_TYPES = {"session_meta", "turn_context", "event_msg", "response_item", "compacted"}
|
|
26
|
+
KNOWN_EVENTS = {
|
|
27
|
+
"token_count",
|
|
28
|
+
"user_message",
|
|
29
|
+
"agent_message",
|
|
30
|
+
"agent_reasoning",
|
|
31
|
+
"context_compacted",
|
|
32
|
+
"task_started",
|
|
33
|
+
"task_complete",
|
|
34
|
+
"turn_aborted",
|
|
35
|
+
"exec_command_begin",
|
|
36
|
+
"exec_command_end",
|
|
37
|
+
}
|
|
38
|
+
PARENT_KEYS = ("forked_from_id", "forkedFromId", "parent_session_id", "parentSessionId")
|
|
39
|
+
TOOL_OUTPUTS = ("function_call_output", "custom_tool_call_output")
|
|
40
|
+
MODEL_OUTPUTS = ("reasoning", "function_call", "custom_tool_call") # plus an assistant message
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _output_text(out: Any) -> str:
|
|
44
|
+
"""A tool output as text: a string as is; a list of content blocks as its text blocks (an image's base64 payload
|
|
45
|
+
is not context text); anything else as JSON."""
|
|
46
|
+
if isinstance(out, str):
|
|
47
|
+
return out
|
|
48
|
+
if isinstance(out, list):
|
|
49
|
+
return "".join(str(b.get("text", "")) for b in out if isinstance(b, dict) and isinstance(b.get("text"), str))
|
|
50
|
+
return json.dumps(out)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _dur(start: float | None, end: float | None) -> float | None:
|
|
54
|
+
if start is None or end is None:
|
|
55
|
+
return None
|
|
56
|
+
d = end - start
|
|
57
|
+
return d if 0 < d <= 900 else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _spawn_parent(src: Any) -> str | None:
|
|
61
|
+
"""A subagent's parent when only its spawn record names it (`source.subagent.thread_spawn.parent_thread_id`)."""
|
|
62
|
+
sub = src.get("subagent") if isinstance(src, dict) else None
|
|
63
|
+
spawn = sub.get("thread_spawn") if isinstance(sub, dict) else None
|
|
64
|
+
pid = spawn.get("parent_thread_id") if isinstance(spawn, dict) else None
|
|
65
|
+
return str(pid) if pid else None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _is_subagent(src: Any) -> bool:
|
|
69
|
+
if isinstance(src, str):
|
|
70
|
+
return src.strip().lower() == "subagent"
|
|
71
|
+
if isinstance(src, dict):
|
|
72
|
+
return "subagent" in src
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class CodexParser(Parser):
|
|
77
|
+
version = 6 # 5: custom_tool_call(_output), list outputs, response timing; 6: model_provider
|
|
78
|
+
head_records = 1 # session_meta: which session this file is (a fork's copied history names other ones)
|
|
79
|
+
|
|
80
|
+
def __init__(self, path: str):
|
|
81
|
+
self.session = Session(id=Path(path).stem, harness="codex", role="main", path=path)
|
|
82
|
+
self.model = "unknown"
|
|
83
|
+
self.leaf_id: str | None = None
|
|
84
|
+
self.last_total: list[int] | None = None # [input, cached, output, total]
|
|
85
|
+
self.pending_tools: list[list[str]] = []
|
|
86
|
+
self.pending_user = ""
|
|
87
|
+
self.call_turn: dict[str, int] = {}
|
|
88
|
+
self.replaying = False
|
|
89
|
+
self.last_input_ts: float | None = None # last user message / tool output
|
|
90
|
+
# the response being generated: the input it answers and its last output item. Codex writes a response's
|
|
91
|
+
# token_count after its tool already ran, so token_count minus the last input would time the tool, not the model
|
|
92
|
+
self.resp_start: float | None = None
|
|
93
|
+
self.resp_end: float | None = None
|
|
94
|
+
self.pending_results: dict[str, list[Any]] = {} # call_id -> [snippet, tokens] for a call not yet in a turn
|
|
95
|
+
|
|
96
|
+
def feed(self, d: dict[str, Any]) -> None:
|
|
97
|
+
s = self.session
|
|
98
|
+
p = d.get("payload")
|
|
99
|
+
typ = str(d.get("type"))
|
|
100
|
+
if typ not in KNOWN_TYPES:
|
|
101
|
+
self.note_unknown(s, typ)
|
|
102
|
+
return
|
|
103
|
+
if not isinstance(p, dict):
|
|
104
|
+
return
|
|
105
|
+
ts = parse_ts(d.get("timestamp"))
|
|
106
|
+
if typ == "session_meta":
|
|
107
|
+
sid = str(p.get("id") or "")
|
|
108
|
+
if self.leaf_id is None:
|
|
109
|
+
self.leaf_id = sid or s.id
|
|
110
|
+
s.id = self.leaf_id
|
|
111
|
+
s.role = "subagent" if _is_subagent(p.get("source")) else s.role
|
|
112
|
+
s.parent_id = next((str(p[k]) for k in PARENT_KEYS if p.get(k)), None) or _spawn_parent(p.get("source"))
|
|
113
|
+
s.platform = str(p["model_provider"]) if p.get("model_provider") else None
|
|
114
|
+
self.cwd = str(p["cwd"]) if p.get("cwd") else None
|
|
115
|
+
elif sid and sid != self.leaf_id:
|
|
116
|
+
self.replaying = True # embedded ancestor metadata: what follows is copied history
|
|
117
|
+
elif typ == "turn_context":
|
|
118
|
+
self.model = str(p.get("model") or self.model)
|
|
119
|
+
self.replaying = False
|
|
120
|
+
self.cwd = str(p["cwd"]) if p.get("cwd") else self.cwd
|
|
121
|
+
elif typ == "compacted" or (typ == "event_msg" and p.get("type") == "context_compacted"):
|
|
122
|
+
if self.replaying:
|
|
123
|
+
return
|
|
124
|
+
msg = str(p.get("message") or "") if typ == "compacted" else ""
|
|
125
|
+
if s.compactions and s.compactions[-1].turn_index == len(s.turns):
|
|
126
|
+
if not s.compactions[-1].summary_len: # a lean compaction keeps only the summary's length
|
|
127
|
+
s.compactions[-1].set_summary(msg)
|
|
128
|
+
else:
|
|
129
|
+
s.compactions.append(
|
|
130
|
+
Compaction(
|
|
131
|
+
turn_index=len(s.turns),
|
|
132
|
+
ts=ts,
|
|
133
|
+
summary_text=msg,
|
|
134
|
+
pre_tokens=s.turns[-1].ctx if s.turns else None,
|
|
135
|
+
duration_s=_dur(self.last_input_ts, ts),
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
139
|
+
elif typ == "response_item":
|
|
140
|
+
self._item(p)
|
|
141
|
+
pt, role = p.get("type"), p.get("role")
|
|
142
|
+
if pt in MODEL_OUTPUTS or (pt == "message" and role == "assistant"):
|
|
143
|
+
if self.resp_end is None:
|
|
144
|
+
self.resp_start = self.last_input_ts
|
|
145
|
+
self.resp_end = ts or self.resp_end
|
|
146
|
+
elif pt in TOOL_OUTPUTS or (pt == "message" and role == "user"):
|
|
147
|
+
if pt == "message": # a new prompt: a response without a token_count (aborted) is over
|
|
148
|
+
self.resp_start = self.resp_end = None
|
|
149
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
150
|
+
elif typ == "event_msg":
|
|
151
|
+
et = str(p.get("type"))
|
|
152
|
+
if et not in KNOWN_EVENTS:
|
|
153
|
+
self.note_unknown(s, f"event_msg:{et}")
|
|
154
|
+
if et in ("user_message", "turn_aborted"): # either way, a response in progress ended without usage
|
|
155
|
+
self.resp_start = self.resp_end = None
|
|
156
|
+
if et == "user_message":
|
|
157
|
+
self.pending_user = str(p.get("message") or "")
|
|
158
|
+
self.last_input_ts = ts or self.last_input_ts
|
|
159
|
+
elif et == "token_count":
|
|
160
|
+
self._tokens(p, ts)
|
|
161
|
+
|
|
162
|
+
def _item(self, p: dict[str, Any]) -> None:
|
|
163
|
+
s = self.session
|
|
164
|
+
pt = p.get("type")
|
|
165
|
+
if pt == "function_call":
|
|
166
|
+
args = p.get("arguments")
|
|
167
|
+
try:
|
|
168
|
+
a = json.loads(args) if isinstance(args, str) else (args or {})
|
|
169
|
+
except ValueError:
|
|
170
|
+
a = {}
|
|
171
|
+
cmd = (a.get("command") or a.get("cmd")) if isinstance(a, dict) else None
|
|
172
|
+
if isinstance(cmd, list):
|
|
173
|
+
cmd = " ".join(map(str, cmd))
|
|
174
|
+
self.pending_tools.append([str(p.get("call_id", "")), f"{p.get('name', '?')}:{str(cmd or args)[:200]}"])
|
|
175
|
+
elif pt == "custom_tool_call": # freeform tools (e.g. `exec`): the input is the raw text
|
|
176
|
+
self.pending_tools.append(
|
|
177
|
+
[str(p.get("call_id", "")), f"{p.get('name', '?')}:{str(p.get('input', ''))[:200]}"]
|
|
178
|
+
)
|
|
179
|
+
elif pt in TOOL_OUTPUTS:
|
|
180
|
+
body = _output_text(p.get("output"))
|
|
181
|
+
cid = str(p.get("call_id", ""))
|
|
182
|
+
if cid not in self.call_turn and any(c == cid for c, _ in self.pending_tools):
|
|
183
|
+
self.pending_results[cid] = [body[:400], len(body) // 4] # its turn comes with the next token_count
|
|
184
|
+
elif s.turns:
|
|
185
|
+
idx = self.call_turn.get(cid, len(s.turns) - 1)
|
|
186
|
+
s.turns[idx].snippets.append(body[:400])
|
|
187
|
+
s.turns[idx].tool_result_tokens.append(len(body) // 4)
|
|
188
|
+
elif pt == "message" and p.get("role") == "user":
|
|
189
|
+
c = p.get("content")
|
|
190
|
+
if isinstance(c, list):
|
|
191
|
+
self.pending_user = " ".join(str(b.get("text", "")) for b in c if isinstance(b, dict))
|
|
192
|
+
|
|
193
|
+
def _tokens(self, p: dict[str, Any], ts: float | None) -> None:
|
|
194
|
+
s = self.session
|
|
195
|
+
info = p.get("info")
|
|
196
|
+
if not isinstance(info, dict):
|
|
197
|
+
return
|
|
198
|
+
try:
|
|
199
|
+
tot = info.get("total_token_usage") or {}
|
|
200
|
+
last = info.get("last_token_usage")
|
|
201
|
+
if not isinstance(tot, dict) or not (last is None or isinstance(last, dict)):
|
|
202
|
+
raise BadRecord("usage is not an object")
|
|
203
|
+
cur = [count(tot.get(k)) for k in ("input_tokens", "cached_input_tokens", "output_tokens", "total_tokens")]
|
|
204
|
+
window = count(info.get("model_context_window"))
|
|
205
|
+
lastv = (
|
|
206
|
+
[count(last.get(k)) for k in ("input_tokens", "cached_input_tokens", "output_tokens")]
|
|
207
|
+
if last is not None
|
|
208
|
+
else None
|
|
209
|
+
)
|
|
210
|
+
except BadRecord:
|
|
211
|
+
s.parse_errors += 1
|
|
212
|
+
return
|
|
213
|
+
if tot and cur == self.last_total:
|
|
214
|
+
return # identical re-emission
|
|
215
|
+
prev, self.last_total = self.last_total, (cur if tot else self.last_total)
|
|
216
|
+
if window:
|
|
217
|
+
s.context_window = window
|
|
218
|
+
if lastv is not None:
|
|
219
|
+
inp, cached, out = lastv
|
|
220
|
+
elif tot and prev:
|
|
221
|
+
inp, cached, out = cur[0] - prev[0], cur[1] - prev[1], cur[2] - prev[2]
|
|
222
|
+
else:
|
|
223
|
+
return
|
|
224
|
+
start, end = (self.resp_start, self.resp_end) if self.resp_end is not None else (self.last_input_ts, ts)
|
|
225
|
+
self.resp_start = self.resp_end = None
|
|
226
|
+
if self.replaying or (inp == 0 and out == 0):
|
|
227
|
+
s.skipped_inherited += 1 # copied parent prefix or zero-usage inherited opening
|
|
228
|
+
self.pending_tools, self.pending_results = [], {}
|
|
229
|
+
return
|
|
230
|
+
t = Turn(
|
|
231
|
+
ts=end,
|
|
232
|
+
ctx=inp,
|
|
233
|
+
cache_read=cached,
|
|
234
|
+
cache_write=0,
|
|
235
|
+
output=out,
|
|
236
|
+
model=self.model,
|
|
237
|
+
user_text=self.pending_user,
|
|
238
|
+
start_ts=start,
|
|
239
|
+
)
|
|
240
|
+
self.pending_user = ""
|
|
241
|
+
for cid, key in self.pending_tools:
|
|
242
|
+
t.tool_keys.append(key)
|
|
243
|
+
self.call_turn[cid] = len(s.turns)
|
|
244
|
+
if cid in self.pending_results:
|
|
245
|
+
snippet, toks = self.pending_results.pop(cid)
|
|
246
|
+
t.snippets.append(snippet)
|
|
247
|
+
t.tool_result_tokens.append(toks)
|
|
248
|
+
self.pending_tools, self.pending_results = [], {}
|
|
249
|
+
s.turns.append(t)
|
|
250
|
+
|
|
251
|
+
def finish(self) -> Session:
|
|
252
|
+
from ..model import snapshot
|
|
253
|
+
|
|
254
|
+
return snapshot(self.session)
|
|
255
|
+
|
|
256
|
+
def dump(self) -> dict[str, Any]:
|
|
257
|
+
from ..model import session_to_dict
|
|
258
|
+
|
|
259
|
+
st = {k: v for k, v in self.__dict__.items() if k not in ("session", "cwd")} # paths stay out of the cache
|
|
260
|
+
return {"path": self.session.path, "session": session_to_dict(self.session), **st}
|
|
261
|
+
|
|
262
|
+
@classmethod
|
|
263
|
+
def load(cls, state: dict[str, Any]) -> CodexParser:
|
|
264
|
+
from ..model import session_from_dict
|
|
265
|
+
|
|
266
|
+
p = cls(state["path"])
|
|
267
|
+
if "session" in state:
|
|
268
|
+
p.session = session_from_dict(state["session"])
|
|
269
|
+
for k in (
|
|
270
|
+
"model",
|
|
271
|
+
"leaf_id",
|
|
272
|
+
"last_total",
|
|
273
|
+
"pending_tools",
|
|
274
|
+
"pending_user",
|
|
275
|
+
"call_turn",
|
|
276
|
+
"replaying",
|
|
277
|
+
"last_input_ts",
|
|
278
|
+
"resp_start",
|
|
279
|
+
"resp_end",
|
|
280
|
+
"pending_results",
|
|
281
|
+
):
|
|
282
|
+
setattr(p, k, state.get(k, getattr(p, k)))
|
|
283
|
+
return p
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@register
|
|
287
|
+
class CodexAdapter(Adapter):
|
|
288
|
+
name = "codex"
|
|
289
|
+
parser_cls = CodexParser
|
|
290
|
+
|
|
291
|
+
@classmethod
|
|
292
|
+
def default_roots(cls) -> list[Path]:
|
|
293
|
+
base = env_roots("CODEX_HOME", "", ["~/.codex"])
|
|
294
|
+
return [b / sub for b in base for sub in ("sessions", "archived_sessions")]
|
|
295
|
+
|
|
296
|
+
@classmethod
|
|
297
|
+
def config_paths(cls) -> list[Path]:
|
|
298
|
+
return [b / "config.toml" for b in env_roots("CODEX_HOME", "", ["~/.codex"])]
|