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.
Files changed (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/synth.py ADDED
@@ -0,0 +1,416 @@
1
+ """Synthetic transcript generator (fixtures and `compactlab demo`). Never reads real data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random
7
+ from datetime import UTC, datetime, timedelta
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ EPOCH = datetime(2026, 9, 1, 12, 0, tzinfo=UTC)
12
+ # Real compaction summaries run to thousands of tokens; pad the synthetic one to ~10k tokens.
13
+ SUMMARY_FILLER = "Context carried over: decisions, open tasks and file notes. " * 680
14
+ FILES = [f"/proj/src/mod{i}.py" for i in range(12)]
15
+
16
+
17
+ def _iso(dt: datetime) -> str:
18
+ return dt.isoformat().replace("+00:00", "Z")
19
+
20
+
21
+ def _lat(rng: random.Random, ctx: int) -> timedelta:
22
+ """Synthetic request latency: grows with context (prefill) plus noise."""
23
+ return timedelta(seconds=2.5 + 0.8 * ctx / 100_000 + rng.uniform(0, 4))
24
+
25
+
26
+ def _stamped(records: list[dict], t: datetime) -> list[dict]:
27
+ return [{"timestamp": _iso(t), **r} for r in records]
28
+
29
+
30
+ def _clat(rng: random.Random, pre: int) -> timedelta:
31
+ """Synthetic compaction latency: a summarizer call that reads the whole context and writes a long summary
32
+ (real logs show minutes, not seconds, for large contexts)."""
33
+ return timedelta(seconds=90 + 0.4 * pre / 1000 + rng.uniform(0, 30))
34
+
35
+
36
+ def _steps(rng: random.Random, n: int, start: int, hist_limit: int | None):
37
+ """Yield (ctx, gap_s, file, user_text, compacted_before). hist_limit simulates the user's old threshold."""
38
+ ctx = start
39
+ for _ in range(n):
40
+ compacted = False
41
+ pre = ctx
42
+ if hist_limit and ctx > hist_limit:
43
+ ctx, compacted = 40_000 + 12_000, True
44
+ ctx += int(rng.lognormvariate(8.6, 0.9))
45
+ r = rng.random()
46
+ gap = rng.choice([5, 8, 12, 20, 30, 60]) if r < 0.95 else (420 if r < 0.99 else 3600)
47
+ yield (
48
+ ctx,
49
+ gap,
50
+ rng.choice(FILES),
51
+ ("you forgot what I said about the config" if rng.random() < 0.04 else ""),
52
+ compacted,
53
+ pre,
54
+ )
55
+
56
+
57
+ def write_claude_code(
58
+ root: Path, n_main: int = 6, n_sub: int = 4, seed: int = 7, models=("claude-opus-5-5", "claude-sonnet-5-5")
59
+ ) -> list[Path]:
60
+ rng = random.Random(seed)
61
+ out = []
62
+ proj = root / "-proj-demo"
63
+ for i in range(n_main + n_sub):
64
+ sub = i >= n_main
65
+ sid = f"s{i:03d}"
66
+ path = (proj / sid / "subagents" / f"agent-{i}.jsonl") if sub else (proj / f"{sid}.jsonl")
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ model = models[i % len(models)]
69
+ n = rng.randint(25, 60) if sub else rng.randint(150, 300)
70
+ t = EPOCH + timedelta(days=i)
71
+ lines: list[dict[str, Any]] = []
72
+ for k, (ctx, gap, key, utext, compacted, pre) in enumerate(
73
+ _steps(rng, n, 30_000, None if sub else rng.choice([350_000, 450_000]))
74
+ ):
75
+ t += timedelta(seconds=gap)
76
+ if compacted:
77
+ t += _clat(rng, pre)
78
+ lines.append(
79
+ {
80
+ "type": "system",
81
+ "subtype": "compact_boundary",
82
+ "timestamp": _iso(t),
83
+ "compactMetadata": {"trigger": "auto", "preTokens": pre},
84
+ }
85
+ )
86
+ lines.append(
87
+ {
88
+ "type": "user",
89
+ "isCompactSummary": True,
90
+ "timestamp": _iso(t),
91
+ "message": {
92
+ "role": "user",
93
+ "content": "Summary: edited /proj/src/mod3.py; all tests "
94
+ "pass; verified the build. Next: finish /proj/src/mod4.py.\n" + SUMMARY_FILLER,
95
+ },
96
+ }
97
+ )
98
+ if utext:
99
+ lines.append({"type": "user", "timestamp": _iso(t), "message": {"role": "user", "content": utext}})
100
+ read = int(ctx * 0.9)
101
+ msg = {
102
+ "id": f"msg_{sid}_{k}",
103
+ "role": "assistant",
104
+ "model": model,
105
+ "usage": {
106
+ "input_tokens": 3,
107
+ "cache_read_input_tokens": read,
108
+ "cache_creation_input_tokens": ctx - read - 3,
109
+ "output_tokens": rng.randint(80, 900),
110
+ },
111
+ "content": [{"type": "tool_use", "id": f"tu_{sid}_{k}", "name": "Read", "input": {"file_path": key}}],
112
+ }
113
+ t += _lat(rng, ctx)
114
+ rec = {"type": "assistant", "timestamp": _iso(t), "isSidechain": sub, "message": msg}
115
+ lines.append(rec)
116
+ if k % 7 == 0:
117
+ lines.append(rec) # streaming duplicate with the same message id
118
+ lines.append(
119
+ {
120
+ "type": "user",
121
+ "timestamp": _iso(t),
122
+ "message": {
123
+ "role": "user",
124
+ "content": [
125
+ {
126
+ "type": "tool_result",
127
+ "tool_use_id": f"tu_{sid}_{k}",
128
+ "content": "x" * rng.randint(400, 8000),
129
+ }
130
+ ],
131
+ },
132
+ }
133
+ )
134
+ path.write_text("\n".join(json.dumps(x) for x in lines) + "\n")
135
+ out.append(path)
136
+ return out
137
+
138
+
139
+ def write_codex(root: Path, n: int = 4, seed: int = 11, model: str = "gpt-5-codex") -> list[Path]:
140
+ rng = random.Random(seed)
141
+ out = []
142
+ for i in range(n):
143
+ day = root / "2026" / "09" / f"{i + 1:02d}"
144
+ day.mkdir(parents=True, exist_ok=True)
145
+ path = day / f"rollout-2026-09-{i + 1:02d}T10-00-00-{i:04d}.jsonl"
146
+ t = EPOCH + timedelta(days=i)
147
+ lines = [
148
+ {"timestamp": _iso(t), "type": "session_meta", "payload": {"id": f"codex-{i}", "source": "cli"}},
149
+ {"timestamp": _iso(t), "type": "turn_context", "payload": {"model": model}},
150
+ ]
151
+ total = 0
152
+ # Real order: the model answers the last input (its latency), calls a tool, the tool runs, and the response's
153
+ # token_count is written after the tool's output. An idle gap is spent while that tool output is pending, so
154
+ # each step writes the previous step's output and token_count after its gap.
155
+ pending: list[dict] = []
156
+ for k, (ctx, gap, key, utext, compacted, pre) in enumerate(_steps(rng, rng.randint(80, 160), 20_000, 300_000)):
157
+ t += timedelta(seconds=gap)
158
+ lines += _stamped(pending, t)
159
+ if compacted:
160
+ t += _clat(rng, pre)
161
+ lines.append(
162
+ {
163
+ "timestamp": _iso(t),
164
+ "type": "compacted",
165
+ "payload": {"message": "Summary of work so far.\n" + SUMMARY_FILLER},
166
+ }
167
+ )
168
+ if utext:
169
+ lines.append(
170
+ {"timestamp": _iso(t), "type": "event_msg", "payload": {"type": "user_message", "message": utext}}
171
+ )
172
+ t += _lat(rng, ctx)
173
+ lines.append(
174
+ {
175
+ "timestamp": _iso(t),
176
+ "type": "response_item",
177
+ "payload": {
178
+ "type": "function_call",
179
+ "name": "shell",
180
+ "call_id": f"c{k}",
181
+ "arguments": json.dumps({"command": ["cat", key]}),
182
+ },
183
+ }
184
+ )
185
+ output = {"type": "function_call_output", "call_id": f"c{k}", "output": "y" * rng.randint(300, 4000)}
186
+ out_tok = rng.randint(50, 600)
187
+ total += ctx + out_tok
188
+ tok = {
189
+ "input_tokens": ctx,
190
+ "cached_input_tokens": int(ctx * 0.85),
191
+ "output_tokens": out_tok,
192
+ "reasoning_output_tokens": 0,
193
+ "total_tokens": ctx + out_tok,
194
+ }
195
+ info = {
196
+ "total_token_usage": {**tok, "total_tokens": total},
197
+ "last_token_usage": tok,
198
+ "model_context_window": 400_000,
199
+ }
200
+ ev = {"type": "event_msg", "payload": {"type": "token_count", "info": info}}
201
+ pending = [{"type": "response_item", "payload": output}, ev, ev] # Codex re-emits identical token_counts
202
+ t += timedelta(milliseconds=500) # the tool runs
203
+ lines += _stamped(pending, t)
204
+ path.write_text("\n".join(json.dumps(x) for x in lines) + "\n")
205
+ out.append(path)
206
+ return out
207
+
208
+
209
+ def write_dsh(root: Path, n: int = 4, seed: int = 13, model: str = "deepseek-v4-flash") -> list[Path]:
210
+ """DeepSeek Harness logs as plain JSONL (dsh writes this with persistenceCompression 'none')."""
211
+ rng = random.Random(seed)
212
+ out = []
213
+ for i in range(n):
214
+ sdir = root / "--proj--" / f"dsh-{i}"
215
+ sdir.mkdir(parents=True, exist_ok=True)
216
+ path = sdir / "session.v4.jsonl"
217
+ t = EPOCH + timedelta(days=i)
218
+ seq = 0
219
+
220
+ def ev(typ: str, data: dict[str, Any], when: datetime) -> dict[str, Any]:
221
+ nonlocal seq
222
+ seq += 1
223
+ return {"type": typ, "seq": seq - 1, "time": int(when.timestamp() * 1000), "data": data}
224
+
225
+ lines: list[dict[str, Any]] = [
226
+ {
227
+ "type": "session",
228
+ "version": 4,
229
+ "id": f"dsh-{i}",
230
+ "createdAt": int(t.timestamp() * 1000),
231
+ "cwd": "/proj",
232
+ "isSeeded": False,
233
+ "delegationDepth": 0,
234
+ },
235
+ ev("request/context", {"provider": "deepseek-official", "model": model, "contextWindow": 1_048_576}, t),
236
+ ]
237
+ steps = _steps(rng, rng.randint(80, 160), 20_000, 600_000)
238
+ for k, (ctx, gap, key, utext, compacted, pre) in enumerate(steps):
239
+ t += timedelta(seconds=gap)
240
+ if compacted:
241
+ lines.append(ev("compaction/start", {"compactionId": f"c{k}", "turn": k}, t))
242
+ t += _clat(rng, pre)
243
+ summary = {"compactionId": f"c{k}", "summary": "Summary of work so far.\n" + SUMMARY_FILLER,
244
+ "shadowedTokenCount": pre, "provider": "deepseek-official", "model": model} # fmt: skip
245
+ lines += [ev("compaction/summary", summary, t), ev("compaction/end", {"compactionId": f"c{k}"}, t)]
246
+ if utext:
247
+ lines.append(ev("user/message", {"content": [{"type": "text", "text": utext}]}, t))
248
+ body = "y" * rng.randint(300, 4000)
249
+ lines.append(ev("tool/result", {"message": {"role": "tool", "toolCallId": f"t{k - 1}",
250
+ "content": [{"type": "text", "text": body}]}}, t)) # fmt: skip
251
+ t += _lat(rng, ctx)
252
+ hit = int(ctx * 0.85)
253
+ usage = {"inputTokens": ctx - hit, "cacheReadTokens": hit, "outputTokens": rng.randint(50, 600)}
254
+ msg = {"role": "assistant", "source": {"kind": "model", "provider": "deepseek-official", "model": model}}
255
+ lines.append(ev("assistant/message", {"turn": k, "step": 1, "message": msg, "usage": usage}, t))
256
+ lines.append(
257
+ ev("tool/call", {"callId": f"t{k}", "name": "read", "arguments": json.dumps({"file_path": key})}, t)
258
+ )
259
+ path.write_text("\n".join(json.dumps(x) for x in lines) + "\n")
260
+ out.append(path)
261
+ return out
262
+
263
+
264
+ OPENCODE_SCHEMA = """
265
+ create table session (id text primary key, project_id text not null, parent_id text, time_created integer not null,
266
+ time_updated integer not null);
267
+ create table message (id text primary key, session_id text not null, time_created integer not null,
268
+ time_updated integer not null, data text not null);
269
+ create table part (id text primary key, message_id text not null, session_id text not null,
270
+ time_created integer not null, time_updated integer not null, data text not null);
271
+ """
272
+
273
+
274
+ def write_opencode(root: Path, n: int = 4, seed: int = 17, model: str = "anthropic/claude-sonnet-5-5") -> Path:
275
+ """An OpenCode 1.x database (only the tables and columns compactlab reads) with n main sessions, each with one
276
+ subagent session, steps with reasoning and a tool, and compactions past 600k."""
277
+ import sqlite3
278
+
279
+ rng = random.Random(seed)
280
+ provider, model_id = model.split("/", 1)
281
+ root.mkdir(parents=True, exist_ok=True)
282
+ path = root / "opencode.db"
283
+ path.unlink(missing_ok=True)
284
+ con = sqlite3.connect(path)
285
+ con.executescript(OPENCODE_SCHEMA)
286
+ ids = {"m": 0, "p": 0}
287
+
288
+ def ms(when: datetime) -> int:
289
+ return int(when.timestamp() * 1000)
290
+
291
+ def msg(sid: str, data: dict[str, Any], when: datetime) -> str:
292
+ ids["m"] += 1
293
+ mid = f"msg_{ids['m']:08d}"
294
+ con.execute("insert into message values (?,?,?,?,?)", (mid, sid, ms(when), ms(when), json.dumps(data)))
295
+ return mid
296
+
297
+ def part(sid: str, mid: str, data: dict[str, Any], when: datetime) -> None:
298
+ ids["p"] += 1
299
+ con.execute("insert into part values (?,?,?,?,?,?)",
300
+ (f"prt_{ids['p']:08d}", mid, sid, ms(when), ms(when), json.dumps(data))) # fmt: skip
301
+
302
+ def session(sid: str, parent: str | None, t: datetime, n_steps: int, limit: int | None) -> datetime:
303
+ start = t
304
+ user = {"role": "user", "time": {"created": ms(t)}, "agent": "build",
305
+ "model": {"providerID": provider, "modelID": model_id}} # fmt: skip
306
+ mid = msg(sid, user, t)
307
+ part(sid, mid, {"type": "text", "text": "refactor the module"}, t)
308
+ for k, (ctx, gap, key, utext, compacted, pre) in enumerate(_steps(rng, n_steps, 20_000, limit)):
309
+ t += timedelta(seconds=gap)
310
+ if compacted:
311
+ cu = msg(sid, user | {"time": {"created": ms(t)}}, t)
312
+ part(sid, cu, {"type": "compaction", "auto": True}, t)
313
+ done = t + _clat(rng, pre)
314
+ stok = {"input": pre, "output": 3000, "reasoning": 0, "cache": {"read": 0, "write": 0}}
315
+ summ = {"role": "assistant", "parentID": cu, "mode": "compaction", "agent": "compaction",
316
+ "summary": True, "finish": "stop", "providerID": provider, "modelID": model_id,
317
+ "time": {"created": ms(t), "completed": ms(done)}, "tokens": stok} # fmt: skip
318
+ sm = msg(sid, summ, t)
319
+ part(sid, sm, {"type": "step-start"}, t)
320
+ part(sid, sm, {"type": "text", "text": "## Objective\n" + SUMMARY_FILLER[:4000]}, done)
321
+ part(sid, sm, {"type": "step-finish", "reason": "stop", "cost": 0, "tokens": stok}, done)
322
+ t = done
323
+ if utext:
324
+ um = msg(sid, user | {"time": {"created": ms(t)}}, t)
325
+ part(sid, um, {"type": "text", "text": utext}, t)
326
+ lat = _lat(rng, ctx)
327
+ hit = int(ctx * 0.85)
328
+ tokens = {"input": ctx - hit - 500, "output": rng.randint(50, 600), "reasoning": rng.randint(0, 200),
329
+ "cache": {"read": hit, "write": 500}} # fmt: skip
330
+ am = {"role": "assistant", "parentID": mid, "mode": "build", "agent": "build", "finish": "tool-calls",
331
+ "providerID": provider, "modelID": model_id, "tokens": tokens,
332
+ "time": {"created": ms(t), "completed": ms(t + lat + timedelta(seconds=2))}} # fmt: skip
333
+ a = msg(sid, am, t)
334
+ part(sid, a, {"type": "step-start"}, t)
335
+ part(sid, a, {"type": "reasoning", "text": "thinking"}, t)
336
+ state = {"status": "completed", "input": {"filePath": key}, "output": "y" * rng.randint(300, 4000),
337
+ "time": {"start": ms(t + lat), "end": ms(t + lat + timedelta(seconds=1))}} # fmt: skip
338
+ part(sid, a, {"type": "tool", "tool": "read", "callID": f"c{k}", "state": state}, t + lat)
339
+ t += lat + timedelta(seconds=2)
340
+ part(sid, a, {"type": "step-finish", "reason": "tool-calls", "cost": 0.01, "tokens": tokens}, t)
341
+ con.execute("insert into session values (?,?,?,?,?)", (sid, "proj", parent, ms(start), ms(t)))
342
+ return t
343
+
344
+ for i in range(n):
345
+ t = session(f"ses_main{i}", None, EPOCH + timedelta(days=i), rng.randint(80, 160), 600_000)
346
+ session(f"ses_sub{i}", f"ses_main{i}", t, rng.randint(10, 30), None)
347
+ con.commit()
348
+ con.close()
349
+ return path
350
+
351
+
352
+ def write_gemini(root: Path, n: int = 3, seed: int = 19, model: str = "gemini-3-pro-preview") -> list[Path]:
353
+ """Gemini CLI JSONL chats under <root>/proj/chats: re-written messages, tool results as user messages, a subagent,
354
+ and compressions past 600k (the first session in the 0.46 checkpoint form, the others in the 0.70 patch form)."""
355
+ rng = random.Random(seed)
356
+ chats = root / "proj" / "chats"
357
+ chats.mkdir(parents=True, exist_ok=True)
358
+ out = []
359
+ for i in range(n):
360
+ t = EPOCH + timedelta(days=i)
361
+ sid = f"0000000{i}-aaaa-bbbb-cccc-dddddddddddd"
362
+ lines: list[dict[str, Any]] = [
363
+ {"sessionId": sid, "projectHash": "0" * 64, "startTime": _iso(t), "lastUpdated": _iso(t)},
364
+ {"id": f"u{i}-0", "timestamp": _iso(t), "type": "user", "content": [{"text": "add a test"}]},
365
+ ]
366
+ for k, (ctx, gap, key, utext, compacted, pre) in enumerate(_steps(rng, rng.randint(60, 120), 20_000, 600_000)):
367
+ t += timedelta(seconds=gap)
368
+ if compacted:
369
+ t += _clat(rng, pre)
370
+ snap = {
371
+ "id": f"s{i}-{k}",
372
+ "timestamp": _iso(t),
373
+ "type": "user",
374
+ "content": [{"text": "<state_snapshot>\n" + SUMMARY_FILLER[:4000] + "\n</state_snapshot>"}],
375
+ }
376
+ ack = {"id": f"a{i}-{k}", "timestamp": _iso(t), "type": "gemini",
377
+ "content": [{"text": "Got it. Thanks for the additional context!"}]} # fmt: skip
378
+ if i == 0:
379
+ lines += [{"$set": {"sessionId": sid}}, {"$set": {"messages": [snap, ack], "lastUpdated": _iso(t)}}]
380
+ else:
381
+ patch = {"removeIds": [f"g{i}-{k - 1}"], "orderIds": [snap["id"], ack["id"]]}
382
+ lines += [snap, ack, {"$patch": patch}]
383
+ if utext:
384
+ lines.append({"id": f"u{i}-{k}", "timestamp": _iso(t), "type": "user", "content": [{"text": utext}]})
385
+ t += _lat(rng, ctx)
386
+ base = {"id": f"g{i}-{k}", "timestamp": _iso(t), "type": "gemini", "content": "", "model": model}
387
+ tokens = {"input": ctx, "output": rng.randint(50, 600), "cached": int(ctx * 0.8),
388
+ "thoughts": rng.randint(0, 300), "tool": 0} # fmt: skip
389
+ tokens["total"] = tokens["input"] + tokens["output"] + tokens["thoughts"]
390
+ call = {
391
+ "id": f"read_file_{k}",
392
+ "name": "read_file",
393
+ "args": {"file_path": key},
394
+ "status": "success",
395
+ "timestamp": _iso(t),
396
+ "result": [{"functionResponse": {"response": {"output": "y" * 900}}}],
397
+ }
398
+ lines += [base, base | {"tokens": tokens}, base | {"tokens": tokens, "toolCalls": [call]}]
399
+ lines.append({"id": f"r{i}-{k}", "timestamp": _iso(t), "type": "user",
400
+ "content": [{"functionResponse": {"id": call["id"], "name": "read_file"}}]}) # fmt: skip
401
+ lines.append({"$set": {"lastUpdated": _iso(t)}})
402
+ path = chats / f"session-{EPOCH + timedelta(days=i):%Y-%m-%dT%H-%M}-{sid[:8]}.jsonl"
403
+ path.write_text("\n".join(json.dumps(x) for x in lines) + "\n")
404
+ out.append(path)
405
+ sub = chats / "00000000-aaaa-bbbb-cccc-dddddddddddd" / "sub-0001.jsonl"
406
+ sub.parent.mkdir(exist_ok=True)
407
+ t = EPOCH
408
+ rows: list[dict[str, Any]] = [{"sessionId": "sub-0001", "projectHash": "0" * 64, "startTime": _iso(t),
409
+ "lastUpdated": _iso(t), "kind": "subagent"}] # fmt: skip
410
+ for k in range(8):
411
+ t += timedelta(seconds=20)
412
+ rows.append({"id": f"sg{k}", "timestamp": _iso(t), "type": "gemini", "model": model,
413
+ "tokens": {"input": 30_000 + k * 4000, "output": 200, "cached": 20_000, "total": 0}}) # fmt: skip
414
+ sub.write_text("\n".join(json.dumps(x) for x in rows) + "\n")
415
+ out.append(sub)
416
+ return out
File without changes
@@ -0,0 +1,134 @@
1
+ """Colour capability, the palette, display width, and styled text as segments.
2
+
3
+ A line is a list of `(text, role)` segments. Widgets build lines; `Style.line` turns one into a string for the
4
+ terminal (truecolor, 256 or 16 colours, or none), so layout never depends on escape codes and width is measured on
5
+ the text alone. The roles carry the report's and the lens mod's colour language: clay accent, green saves, amber
6
+ adds, red broken guardrails, grey for the default and secondary text.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import unicodedata
14
+ from dataclasses import dataclass
15
+ from typing import IO, Any
16
+
17
+ Seg = tuple[str, Any] # (text, role); role is a palette key or None
18
+ Line = list[Seg]
19
+
20
+ # role -> truecolor (works on dark and light backgrounds), 16-colour SGR fallback
21
+ PALETTE: dict[str, tuple[tuple[int, int, int], str]] = {
22
+ "acc": ((217, 119, 87), "31"),
23
+ "good": ((95, 179, 127), "32"),
24
+ "warn": ((227, 165, 72), "33"),
25
+ "bad": ((242, 104, 92), "91"),
26
+ "dim": ((143, 140, 131), "90"),
27
+ "was": ((120, 116, 108), "90"),
28
+ "ink": ((236, 235, 228), "97"),
29
+ "frame": ((96, 93, 86), "90"),
30
+ "hl": ((255, 255, 255), "97"),
31
+ }
32
+ BOLD = {"title", "big", "hl"} # roles drawn bold (with the colour of their base role, see ROLE_BASE)
33
+ ROLE_BASE = {"title": "ink", "big": "ink", "good_b": "good", "warn_b": "warn", "acc_b": "acc", "bad_b": "bad"}
34
+ ANSI = re.compile(r"\x1b\[[0-9;]*m")
35
+
36
+
37
+ def cw(text: str) -> int:
38
+ """Display width: East Asian wide / fullwidth glyphs take two columns, combining marks none."""
39
+ w = 0
40
+ for ch in text:
41
+ if unicodedata.combining(ch):
42
+ continue
43
+ w += 2 if unicodedata.east_asian_width(ch) in "WF" else 1
44
+ return w
45
+
46
+
47
+ def width(line: Line) -> int:
48
+ return sum(cw(t) for t, _ in line)
49
+
50
+
51
+ def clip(line: Line, n: int) -> Line:
52
+ """The line cut to `n` columns, never splitting a wide glyph (an ellipsis marks the cut)."""
53
+ if width(line) <= n:
54
+ return line
55
+ out: Line = []
56
+ left = max(n - 1, 0)
57
+ for text, role in line:
58
+ if left <= 0:
59
+ break
60
+ part = ""
61
+ for ch in text:
62
+ c = cw(ch)
63
+ if c > left:
64
+ left = 0
65
+ break
66
+ part += ch
67
+ left -= c
68
+ if part:
69
+ out.append((part, role))
70
+ out.append(("…", "dim"))
71
+ return out
72
+
73
+
74
+ def pad(line: Line, n: int) -> Line:
75
+ """Clip or right-pad with spaces to exactly `n` columns."""
76
+ line = clip(line, n)
77
+ return [*line, (" " * (n - width(line)), None)] if width(line) < n else line
78
+
79
+
80
+ def plain(line: Line) -> str:
81
+ return "".join(t for t, _ in line)
82
+
83
+
84
+ def _cube(rgb: tuple[int, int, int]) -> int:
85
+ """Nearest xterm-256 colour cube index."""
86
+ r, g, b = (round(v / 255 * 5) for v in rgb)
87
+ return 16 + 36 * r + 6 * g + b
88
+
89
+
90
+ @dataclass
91
+ class Style:
92
+ depth: int = 0 # 0 none, 16, 256, 24 (truecolor)
93
+
94
+ @classmethod
95
+ def detect(cls, stream: IO[str] | None, mode: str = "auto") -> Style:
96
+ """`mode`: always / never / auto. Auto: no colour off a TTY, with NO_COLOR, or on a dumb terminal."""
97
+ if mode == "never":
98
+ return cls(0)
99
+ env = os.environ
100
+ if mode == "auto":
101
+ if "NO_COLOR" in env or env.get("TERM") == "dumb":
102
+ return cls(0)
103
+ if stream is None or not getattr(stream, "isatty", lambda: False)():
104
+ return cls(0)
105
+ ct, term = env.get("COLORTERM", "").lower(), env.get("TERM", "")
106
+ if ct in ("truecolor", "24bit"):
107
+ return cls(24)
108
+ if "256" in term:
109
+ return cls(256)
110
+ return cls(16 if mode == "auto" or term else 24)
111
+
112
+ def sgr(self, role: str | None) -> str:
113
+ if not self.depth or not role:
114
+ return ""
115
+ base = ROLE_BASE.get(role, role)
116
+ rgb, basic = PALETTE.get(base, PALETTE["ink"])
117
+ bold = "1;" if role in BOLD or role.endswith("_b") else ""
118
+ if self.depth == 24:
119
+ return f"\x1b[{bold}38;2;{rgb[0]};{rgb[1]};{rgb[2]}m"
120
+ if self.depth == 256:
121
+ return f"\x1b[{bold}38;5;{_cube(rgb)}m"
122
+ return f"\x1b[{bold}{basic}m"
123
+
124
+ def line(self, line: Line) -> str:
125
+ if not self.depth:
126
+ return plain(line)
127
+ out = []
128
+ for text, role in line:
129
+ s = self.sgr(role)
130
+ out.append(f"{s}{text}\x1b[0m" if s else text)
131
+ return "".join(out)
132
+
133
+ def lines(self, lines: list[Line]) -> str:
134
+ return "\n".join(self.line(x).rstrip() if not self.depth else self.line(x) for x in lines)