-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.py
More file actions
494 lines (443 loc) · 16.8 KB
/
cli.py
File metadata and controls
494 lines (443 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
from __future__ import annotations
import json
from pathlib import Path
import click
from click_default_group import DefaultGroup
import questionary
from codex_transcripts.gist import create_gist, inject_gist_preview_js
from codex_transcripts.rollout import (
calculate_resume_style_metrics,
format_resume_style_row,
format_resume_style_header,
format_updated_label,
get_session_id_from_filename,
list_session_rows,
)
from codex_transcripts.transcript import (
as_meta_dict,
default_output_dir,
generate_html_from_rollout,
generate_archive_index,
generate_json_from_rollout,
open_output,
output_auto_dir,
)
from codex_transcripts.tui import run_tui
def _print_stats(stats) -> None:
system = (
stats.system_rollout_types
or stats.system_event_types
or stats.system_response_item_types
)
system_total = (
sum(stats.system_rollout_types.values())
+ sum(stats.system_event_types.values())
+ sum(stats.system_response_item_types.values())
)
click.echo(
f"Parsed: {stats.total_lines} lines, {stats.emitted_loglines} transcript items; "
f"system: {system_total}"
)
if system:
click.echo("System record types (rendered as System cards):", err=True)
if stats.system_rollout_types:
click.echo(f"- rollout: {stats.system_rollout_types}", err=True)
if stats.system_event_types:
click.echo(f"- event_msg: {stats.system_event_types}", err=True)
if stats.system_response_item_types:
click.echo(f"- response_item: {stats.system_response_item_types}", err=True)
def _ensure_output_dir(
output: str | None,
*,
output_auto: bool,
rollout_path: Path,
) -> tuple[Path, bool]:
open_browser = False
if output is None:
out_dir = default_output_dir()
open_browser = True
return out_dir, open_browser
parent = Path(output).expanduser()
if output_auto:
session_id = get_session_id_from_filename(rollout_path)
out_dir = output_auto_dir(parent, session_id=session_id, filename=rollout_path.stem)
else:
out_dir = parent
out_dir.mkdir(parents=True, exist_ok=True)
return out_dir, open_browser
@click.group(cls=DefaultGroup, default="local", default_if_no_args=True)
@click.version_option(None, "-v", "--version", package_name="codex-transcripts")
def cli() -> None:
"""Convert Codex rollout JSONL sessions into browsable HTML transcripts.
\b
Examples:
codex-transcripts
codex-transcripts local --latest --open
codex-transcripts json ~/.codex/sessions/YYYY/MM/DD/rollout-...jsonl -o ./out --open
codex-transcripts local --latest --gist
codex-transcripts tui --latest # experimental/alpha
\b
Run without cloning (from a git URL):
uvx --from git+https://github.com/prateek/codex-transcripts codex-transcripts local --latest --open
"""
@cli.command("local")
@click.option("--codex-home", type=click.Path(path_type=Path), help="Override CODEX_HOME.")
@click.option("--limit", type=int, default=10, show_default=True, help="How many recent sessions to show.")
@click.option(
"--cwd",
"cwd_only",
is_flag=True,
help="Filter sessions to the current working directory (like `codex resume`).",
)
@click.option(
"--all",
"show_all",
is_flag=True,
help="(Deprecated) Search all sessions globally (default).",
)
@click.option("--include-archived/--no-include-archived", default=True, show_default=True)
@click.option("--query", help="Filter sessions by substring match (preview/cwd/branch/id/path).")
@click.option("--latest", is_flag=True, help="Use the most recent session (no interactive picker).")
@click.option("-o", "--output", type=click.Path(), help="Output directory (default: temp dir + open browser).")
@click.option(
"-a",
"--output-auto",
is_flag=True,
help="Auto-name output subdirectory based on session id / filename (uses -o as parent).",
)
@click.option("--repo", help="GitHub repo owner/name for commit links (auto-detected from session meta if omitted).")
@click.option("--open", "open_browser", is_flag=True, help="Open generated index.html in your browser.")
@click.option("--gist", is_flag=True, help="Upload HTML files to a GitHub Gist (requires gh auth).")
@click.option("--gist-public", is_flag=True, help="Create a public Gist (default: secret).")
@click.option(
"--include-source",
"--json",
"include_source",
is_flag=True,
help="Copy the source rollout file into the output directory.",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["html", "json"], case_sensitive=False),
default="html",
show_default=True,
help="Output format.",
)
@click.option(
"--style",
"output_style",
type=click.Choice(["viewer", "chat"], case_sensitive=False),
default="viewer",
show_default=True,
help="HTML style (viewer or chat).",
)
def local_cmd(
codex_home: Path | None,
limit: int,
cwd_only: bool,
show_all: bool,
include_archived: bool,
query: str | None,
latest: bool,
output: str | None,
output_auto: bool,
repo: str | None,
open_browser: bool,
gist: bool,
gist_public: bool,
include_source: bool,
output_format: str,
output_style: str,
) -> None:
if show_all and cwd_only:
raise click.ClickException("--all and --cwd are mutually exclusive.")
filter_cwd = Path.cwd() if cwd_only else None
rows = list_session_rows(
codex_home=codex_home,
limit=limit,
include_archived=include_archived,
query=query,
filter_cwd=filter_cwd,
)
if not rows:
raise click.ClickException("No Codex sessions found under ~/.codex/sessions (or CODEX_HOME).")
if output_format == "json" and (open_browser or gist):
raise click.ClickException("--open/--gist are only supported for HTML output.")
if output_format == "json" and output_style != "viewer":
raise click.ClickException("--style is only supported for HTML output.")
show_cwd = not cwd_only
metrics = calculate_resume_style_metrics(rows, show_cwd=show_cwd)
selected_paths: list[Path]
if latest:
selected_paths = [rows[0].path]
else:
click.echo(format_resume_style_header(metrics))
choices = [
questionary.Choice(
title=format_resume_style_row(r, metrics=metrics),
value=r.path,
)
for r in rows
]
selected_paths = questionary.checkbox(
"Select Codex sessions (space to toggle, enter to confirm):",
choices=choices,
validate=lambda a: True if a else "Select at least one session.",
).ask()
if not selected_paths:
raise click.ClickException("No session selected.")
# For now, if multiple sessions are selected, write each into its own subdirectory under -o (or temp).
# Single selection retains the original behavior.
if len(selected_paths) == 1:
selected = selected_paths[0]
out_dir, open_by_default = _ensure_output_dir(output, output_auto=output_auto, rollout_path=selected)
if output_format == "json":
out_path, meta, stats = generate_json_from_rollout(
selected,
out_dir,
include_source=include_source,
)
_print_stats(stats)
if meta is not None:
meta_path = out_dir / "session_meta.json"
meta_path.write_text(
json.dumps(as_meta_dict(meta), indent=2, ensure_ascii=False) + "\n"
)
click.echo(f"JSON: {out_path}")
click.echo(f"Output: {out_dir}")
return
out_dir, meta, stats = generate_html_from_rollout(
selected,
out_dir,
github_repo=repo,
include_json=include_source,
style=output_style,
)
_print_stats(stats)
if meta is not None:
meta_path = out_dir / "session_meta.json"
meta_path.write_text(json.dumps(as_meta_dict(meta), indent=2, ensure_ascii=False) + "\n")
if gist:
click.echo("Creating GitHub gist...")
inject_gist_preview_js(out_dir)
gist_id, gist_url = create_gist(out_dir, public=gist_public)
preview = f"https://gisthost.github.io/?{gist_id}/index.html"
click.echo(f"Gist: {gist_url}")
click.echo(f"Preview: {preview}")
if open_browser or open_by_default:
open_output(out_dir)
click.echo(f"Output: {out_dir}")
return
# Multi-selection: create output root and generate each session into an auto-named subdir.
if gist:
raise click.ClickException("Publishing multiple sessions to a single Gist is not supported yet. Re-run with a single selection or without --gist.")
root, open_by_default = _ensure_output_dir(output, output_auto=False, rollout_path=selected_paths[0])
rows_by_path = {r.path: r for r in rows}
sessions_index: list[dict[str, str]] = []
for p in selected_paths:
subdir = output_auto_dir(root, session_id=get_session_id_from_filename(p), filename=p.stem)
if output_format == "json":
out_path, meta, stats = generate_json_from_rollout(
p,
subdir,
include_source=include_source,
)
else:
out_dir, meta, stats = generate_html_from_rollout(
p,
subdir,
github_repo=repo,
include_json=include_source,
style=output_style,
)
out_path = out_dir / "index.html"
_print_stats(stats)
if meta is not None:
(subdir / "session_meta.json").write_text(
json.dumps(as_meta_dict(meta), indent=2, ensure_ascii=False) + "\n"
)
row = rows_by_path.get(p)
sessions_index.append(
{
"session_id": (row.session_id if row else get_session_id_from_filename(p)) or subdir.name,
"updated": format_updated_label(row) if row else "-",
"updated_ts": 0 if row is None or row.updated_at is None else row.updated_at.timestamp(),
"preview": (row.preview if row else p.name),
"href": f"{subdir.name}/{out_path.name}",
}
)
sessions_index.sort(key=lambda s: s.get("updated_ts", 0), reverse=True)
if output_format == "html":
generate_archive_index(root, sessions=sessions_index)
else:
(root / "index.json").write_text(
json.dumps({"format": "codex-transcripts.index.v1", "sessions": sessions_index}, indent=2, ensure_ascii=False)
+ "\n",
encoding="utf-8",
)
if open_browser or open_by_default:
if output_format == "html":
open_output(root)
click.echo(f"Output root: {root}")
@cli.command("tui")
@click.argument("path", required=False, type=click.Path(path_type=Path))
@click.option("--codex-home", type=click.Path(path_type=Path), help="Override CODEX_HOME (used when PATH is omitted).")
@click.option("--limit", type=int, default=50, show_default=True, help="How many recent sessions to show (when PATH is omitted).")
@click.option(
"--cwd",
"cwd_only",
is_flag=True,
help="Filter sessions to the current working directory (like `codex resume`).",
)
@click.option(
"--all",
"show_all",
is_flag=True,
help="(Deprecated) Search all sessions globally (default).",
)
@click.option("--include-archived/--no-include-archived", default=True, show_default=True)
@click.option("--query", help="Filter sessions by substring match (preview/cwd/branch/id/path) (when PATH is omitted).")
@click.option("--latest", is_flag=True, help="Use the most recent session (no interactive picker).")
def tui_cmd(
path: Path | None,
codex_home: Path | None,
limit: int,
cwd_only: bool,
show_all: bool,
include_archived: bool,
query: str | None,
latest: bool,
) -> None:
"""Interactive TUI transcript viewer (experimental/alpha; fold/unfold + filtering)."""
rollout_path: Path
if path is not None:
rollout_path = path
else:
if show_all and cwd_only:
raise click.ClickException("--all and --cwd are mutually exclusive.")
filter_cwd = Path.cwd() if cwd_only else None
rows = list_session_rows(
codex_home=codex_home,
limit=limit,
include_archived=include_archived,
query=query,
filter_cwd=filter_cwd,
)
if not rows:
raise click.ClickException("No Codex sessions found under ~/.codex/sessions (or CODEX_HOME).")
show_cwd = not cwd_only
metrics = calculate_resume_style_metrics(rows, show_cwd=show_cwd)
if latest:
rollout_path = rows[0].path
else:
click.echo(format_resume_style_header(metrics))
choices = [
questionary.Choice(
title=format_resume_style_row(r, metrics=metrics),
value=r.path,
)
for r in rows
]
selected: Path | None = questionary.select(
"Select a Codex session to view:", choices=choices, use_shortcuts=True
).ask()
if selected is None:
raise click.ClickException("No session selected.")
rollout_path = selected
if not rollout_path.exists():
raise click.ClickException(f"File not found: {rollout_path}")
run_tui(rollout_path=rollout_path)
@cli.command("json")
@click.argument("path", type=click.Path(path_type=Path))
@click.option("-o", "--output", type=click.Path(), help="Output directory (default: temp dir + open browser).")
@click.option(
"-a",
"--output-auto",
is_flag=True,
help="Auto-name output subdirectory based on session id / filename (uses -o as parent).",
)
@click.option("--repo", help="GitHub repo owner/name for commit links (auto-detected from session meta if omitted).")
@click.option("--open", "open_browser", is_flag=True, help="Open generated index.html in your browser.")
@click.option("--gist", is_flag=True, help="Upload HTML files to a GitHub Gist (requires gh auth).")
@click.option("--gist-public", is_flag=True, help="Create a public Gist (default: secret).")
@click.option(
"--include-source",
"--json",
"include_source",
is_flag=True,
help="Copy the source rollout file into the output directory.",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["html", "json"], case_sensitive=False),
default="html",
show_default=True,
help="Output format.",
)
@click.option(
"--style",
"output_style",
type=click.Choice(["viewer", "chat"], case_sensitive=False),
default="viewer",
show_default=True,
help="HTML style (viewer or chat).",
)
def json_cmd(
path: Path,
output: str | None,
output_auto: bool,
repo: str | None,
open_browser: bool,
gist: bool,
gist_public: bool,
include_source: bool,
output_format: str,
output_style: str,
) -> None:
if not path.exists():
raise click.ClickException(f"File not found: {path}")
if output_format == "json" and (open_browser or gist):
raise click.ClickException("--open/--gist are only supported for HTML output.")
if output_format == "json" and output_style != "viewer":
raise click.ClickException("--style is only supported for HTML output.")
out_dir, open_by_default = _ensure_output_dir(output, output_auto=output_auto, rollout_path=path)
if output_format == "json":
out_path, meta, stats = generate_json_from_rollout(
path,
out_dir,
include_source=include_source,
)
_print_stats(stats)
if meta is not None:
meta_path = out_dir / "session_meta.json"
meta_path.write_text(json.dumps(as_meta_dict(meta), indent=2, ensure_ascii=False) + "\n")
click.echo(f"JSON: {out_path}")
click.echo(f"Output: {out_dir}")
return
out_dir, meta, stats = generate_html_from_rollout(
path,
out_dir,
github_repo=repo,
include_json=include_source,
style=output_style,
)
_print_stats(stats)
if meta is not None:
meta_path = out_dir / "session_meta.json"
meta_path.write_text(json.dumps(as_meta_dict(meta), indent=2, ensure_ascii=False) + "\n")
if gist:
click.echo("Creating GitHub gist...")
inject_gist_preview_js(out_dir)
gist_id, gist_url = create_gist(out_dir, public=gist_public)
preview = f"https://gisthost.github.io/?{gist_id}/index.html"
click.echo(f"Gist: {gist_url}")
click.echo(f"Preview: {preview}")
if open_browser or open_by_default:
open_output(out_dir)
click.echo(f"Output: {out_dir}")
def main() -> None:
cli()
if __name__ == "__main__":
main()