-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcli.py
More file actions
1100 lines (946 loc) · 37.5 KB
/
Copy pathcli.py
File metadata and controls
1100 lines (946 loc) · 37.5 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CLI for lapdog subcommands"""
import argparse
import json
import os
from pathlib import Path
import shutil
import shlex
import signal
import subprocess
import sys
import time
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import urllib.error
import urllib.request
import uuid
from lapdog import backfill_claude
from lapdog import backfill_codex
from lapdog import backfill_pi
from lapdog import codex_args
from lapdog import tracer_inject
from lapdog.lapdog_ascii_art import build_running_banner
from lapdog.paths import CODEX_APP_CURSOR_FILE
from lapdog.paths import LAPDOG_DIR
from lapdog.paths import LOG_FILE
from lapdog.paths import PID_FILE
LAPDOG_COMMANDS = ["start", "stop", "status", "claude", "pi", "codex", "uninstall"]
LAPDOG_USAGE = (
"Usage: lapdog [OPTIONS] <command> [command-args...]\n"
"Options must appear before <command>. Arguments after <command> are forwarded.\n"
" start Start lapdog (background)\n"
" stop Stop lapdog (started by 'lapdog start' or 'lapdog claude')\n"
" status Show lapdog status (from /info)\n"
" claude Start lapdog in background if needed, then launch Claude with intercept\n"
" pi Start lapdog in background if needed, install extension, then launch pi\n"
" codex Start lapdog in background if needed, then launch Codex with tracing\n"
" uninstall Stop lapdog and remove all state it wrote (~/.lapdog, Claude hooks, pi extension, Codex watchers)\n"
"\n"
"Any other command is treated as an app to run with tracing instrumentation:\n"
" lapdog python app.py\n"
)
_PROXY_SESSION_WARNING_LINES = ["Keep Lapdog running; stopping it can break proxied model calls."]
LAPDOG_PLUGIN_NAME = "lapdog@lapdog"
LAPDOG_MARKETPLACE_SOURCE = "DataDog/dd-apm-test-agent"
def _lapdog_claude_code_plugin_installed() -> bool:
"""Return True if the lapdog Claude Code plugin is installed for this user."""
installed_path = Path.home() / ".claude" / "plugins" / "installed_plugins.json"
if not installed_path.exists():
return False
try:
with installed_path.open() as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
return False
return bool(LAPDOG_PLUGIN_NAME in (data.get("plugins") or {}))
def _ensure_lapdog_claude_code_plugin_installed() -> None:
"""Install the lapdog Claude Code plugin if missing. Best-effort: failures warn and continue."""
if _lapdog_claude_code_plugin_installed():
return
claude_bin = shutil.which("claude")
if not claude_bin:
# _run_claude will print a clearer error in a moment.
return
print("[lapdog] Installing Claude Code plugin 'lapdog'...", file=sys.stderr)
commands = [
[claude_bin, "plugin", "marketplace", "add", LAPDOG_MARKETPLACE_SOURCE],
[claude_bin, "plugin", "install", LAPDOG_PLUGIN_NAME],
]
for cmd in commands:
try:
subprocess.run(cmd, check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
detail = (e.stderr or e.stdout or "").strip()
print(
f"[lapdog] '{' '.join(cmd[1:])}' failed (rc={e.returncode}): {detail}",
file=sys.stderr,
)
print(
"[lapdog] Continuing without plugin; LLM calls will still be captured "
"but Claude Code hook events (tool calls, prompts, sessions, permissions) "
"will not. Install manually:\n"
f" claude plugin marketplace add {LAPDOG_MARKETPLACE_SOURCE}\n"
f" claude plugin install {LAPDOG_PLUGIN_NAME}",
file=sys.stderr,
)
return
print("[lapdog] Plugin installed.", file=sys.stderr)
def _uninstall_lapdog_claude_code_plugin() -> None:
if not _lapdog_claude_code_plugin_installed():
return
claude_bin = shutil.which("claude")
if not claude_bin:
return
commands = [
[claude_bin, "plugin", "uninstall", LAPDOG_PLUGIN_NAME],
[claude_bin, "plugin", "marketplace", "remove", LAPDOG_MARKETPLACE_SOURCE],
]
for cmd in commands:
try:
subprocess.run(cmd, check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
detail = (e.stderr or e.stdout or "").strip()
print(
f"[lapdog] '{' '.join(cmd[1:])}' failed (rc={e.returncode}): {detail}",
file=sys.stderr,
)
print(
"[lapdog] Failed to uninstall 'lapdog' Claude Code plugin "
"Uninstall manually:\n"
f" claude plugin uninstall {LAPDOG_PLUGIN_NAME}",
file=sys.stderr,
)
return
print("[lapdog] Claude Code plugin uninstalled", file=sys.stderr)
def _resolved_port(cli_args: Optional[List[str]] = None) -> int:
"""Infer port the same way lapdog does: -p/--port in args, else PORT env, else 8126."""
if cli_args is not None:
i = 0
while i < len(cli_args):
arg = cli_args[i]
if arg in ("-p", "--port"):
if i + 1 < len(cli_args):
return int(cli_args[i + 1])
i += 1
elif arg.startswith("--port="):
return int(arg.split("=", 1)[1])
i += 1
return int(os.environ.get("PORT", "8126"))
def _pid_file_path() -> str:
return os.environ.get("LAPDOG_PID_FILE", PID_FILE)
def _log_file_path() -> str:
return os.environ.get("LAPDOG_LOG_FILE", LOG_FILE)
def _url_for_port(port: int) -> str:
return f"http://127.0.0.1:{port}/info"
def _http_get_status(url: str, timeout: float) -> int:
"""GET url and return the HTTP status code.
Uses an empty ProxyHandler so macOS _scproxy.get_proxy_settings is never
called. That call crashes inside a forked child on Python 3.13 / macOS
because the parent process has internal threads at fork time, leaving
CoreFoundation's logging lock state corrupt in the child.
"""
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url, timeout=timeout) as resp:
return int(resp.status)
def _lapdog_alive(timeout: float = 2.0) -> bool:
"""Check if the lapdog we started is running (pid file + process exists + /info responds)."""
pid, port = _read_pid_file()
if pid is None or port is None:
return False
if not _process_exists(pid):
return False
try:
return _http_get_status(_url_for_port(port), timeout=timeout) == 200
except Exception:
return False
def _read_pid_file(path: Optional[str] = None) -> Tuple[Optional[int], Optional[int]]:
path = path or _pid_file_path()
if not os.path.exists(path):
return None, None
try:
with open(path) as f:
lines = f.read().splitlines()
pid = int(lines[0].strip()) if lines else None
port = int(lines[1].strip()) if len(lines) > 1 else None
return pid, port
except (ValueError, OSError):
return None, None
def _process_exists(pid: int) -> bool:
try:
os.kill(pid, 0)
return True
except OSError:
return False
def _ensure_lapdog_running(forward_data: bool = False, detached: bool = False) -> Optional[int]:
"""Start lapdog in background if it is not already running. Exits if the port is taken."""
if _lapdog_alive():
_, port = _read_pid_file()
return port
port = _resolved_port()
if _port_in_use(port):
print(
f"[lapdog] Port {port} is already in use. Stop the existing lapdog instance first (e.g. 'lapdog stop').",
file=sys.stderr,
)
sys.exit(1)
if detached:
_start_lapdog_detached(port, forward_data=forward_data)
else:
_start_lapdog(port, forward_data=forward_data)
return port
def _write_pid_file(pid: int, port: int) -> None:
path = _pid_file_path()
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(f"{pid}\n{port}\n")
def _remove_pid_file() -> None:
path = _pid_file_path()
if os.path.exists(path):
try:
os.remove(path)
except OSError:
pass
def _start_lapdog(
port: int, extra_args: Optional[List[str]] = None, forward_data: bool = False
) -> Tuple[int, int, str]:
"""Start lapdog in background with logs to the log file; wait until ready or exit on timeout. Return (process, log_path)."""
log_path = _log_file_path()
os.makedirs(os.path.dirname(log_path), exist_ok=True)
args = [sys.executable, "-m", "ddapm_test_agent.agent", "--lapdog-mode"]
if not forward_data:
args.append("--disable-llmobs-data-forwarding")
if extra_args:
args += extra_args
popen_kwargs: Dict[str, Any] = {
"stdin": subprocess.DEVNULL,
"stderr": subprocess.STDOUT,
}
if sys.platform == "win32":
# On Windows, start_new_session is a no-op. Use creationflags to truly
# detach the child so it survives after the launcher process exits.
popen_kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["start_new_session"] = True
with open(log_path, "w") as log_file:
proc = subprocess.Popen(args, stdout=log_file, **popen_kwargs)
_write_pid_file(proc.pid, port)
_wait_for_lapdog(proc, log_path)
return proc.pid, port, log_path
def _port_in_use(port: Optional[int] = None) -> bool:
"""Return True if something is already serving /info on the given port. If port is None, use _resolved_port()."""
if port is None:
port = _resolved_port()
try:
return _http_get_status(_url_for_port(port), timeout=1) == 200
except Exception:
return False
def _wait_for_lapdog(proc: "subprocess.Popen[bytes]", log_path: Optional[str] = None) -> None:
"""Wait up to ~10s for lapdog to start, then exit(1) on timeout."""
for _ in range(50):
if _lapdog_alive():
return
time.sleep(0.2)
msg = "[lapdog] Lapdog failed to start in time."
if log_path:
msg += f" Check logs: {log_path}"
print(msg, file=sys.stderr)
_remove_pid_file()
try:
proc.kill()
except OSError:
pass
sys.exit(1)
def _run_claude(args: Optional[List[str]] = None) -> None:
"""Set BUN_OPTIONS with claude_intercept.mjs and exec the claude binary. Never returns."""
if args is None:
args = sys.argv[1:]
mjs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "claude_intercept.mjs")
# BUN_OPTIONS is re-parsed by Bun as a shell-like arg string, so backslashes
# in the path get treated as escape characters and stripped. Bun accepts
# forward slashes on Windows, which is the most reliable fix.
if sys.platform == "win32":
mjs_path = mjs_path.replace("\\", "/")
claude_bin = shutil.which("claude")
if not claude_bin:
print("[ddapm] 'claude' not found in PATH", file=sys.stderr)
sys.exit(1)
existing = os.environ.get("BUN_OPTIONS", "")
os.environ["BUN_OPTIONS"] = f"--preload {mjs_path} {existing}".strip()
os.execv(claude_bin, [claude_bin] + args)
def cmd_start(sub_cmd_args: List[str], forward_data: bool) -> None:
"""Start lapdog in background with Claude hooks enabled."""
if _lapdog_alive():
pid, port = _read_pid_file()
url = _url_for_port(port) if port else None
print(f"[lapdog] Lapdog already running at {url}" + (f" (PID {pid})" if pid else ""), file=sys.stderr)
return
port = _resolved_port(sys.argv[2:])
if _port_in_use(port):
print(
f"[lapdog] Port {port} is already in use (something is serving /info). "
"Stop it first (e.g. 'lapdog stop') or use a different port.",
file=sys.stderr,
)
sys.exit(1)
pid, port, log_path = _start_lapdog(port, sub_cmd_args, forward_data)
print(f"[lapdog] Lapdog running at {_url_for_port(port)} (pid={pid}, logs: {log_path})")
def cmd_stop(pid: Optional[int] = None) -> None:
"""Stop lapdog (started by 'lapdog start' or 'lapdog claude')."""
if pid is None:
pid, _ = _read_pid_file()
if pid is None:
print("[lapdog] No lapdog PID file found; lapdog may not be running.", file=sys.stderr)
sys.exit(1)
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
pass
except OSError as e:
print(f"[lapdog] Failed to stop lapdog (PID {pid}): {e}", file=sys.stderr)
sys.exit(1)
_remove_pid_file()
print("[lapdog] Lapdog stopped.")
def cmd_status() -> None:
"""Print lapdog status (from /info). Only works when lapdog was started by this CLI (pid file exists)."""
pid, port = _read_pid_file()
if port is None:
print("[lapdog] No lapdog running (start with 'lapdog start' or 'lapdog claude').", file=sys.stderr)
sys.exit(1)
url = _url_for_port(port)
try:
status = _http_get_status(url, timeout=2)
if status >= 400:
raise OSError(f"HTTP {status}")
print(f"[lapdog] Lapdog running at {url} (pid={pid}, logs: {_log_file_path()})", file=sys.stderr)
except Exception as e:
print(f"[lapdog] Lapdog not reachable at {url}: {e}", file=sys.stderr)
sys.exit(1)
def _start_lapdog_detached(port: int, forward_data: bool) -> None:
"""Start lapdog in a forked child so it is not a child of the calling process.
After os.execv replaces the current process with pi/claude, lapdog must not
be a child of that process. If it were, killing/restarting lapdog would
send SIGCHLD to the agent which can crash the runtime. By forking first
and starting lapdog in the child, the child exits immediately after lapdog
is ready and lapdog gets re-parented to init/launchd — fully independent of
the process that will become pi/claude.
On Windows there is no os.fork() and no SIGCHLD; the DETACHED_PROCESS /
CREATE_NEW_PROCESS_GROUP creation flags passed inside _start_lapdog already
detach the child from the launcher, so we just call it directly.
"""
if sys.platform == "win32":
_start_lapdog(port, forward_data=forward_data)
return
child_pid = os.fork()
if child_pid == 0:
# Child: start lapdog, wait for it to be ready, then exit.
try:
_start_lapdog(port, forward_data=forward_data)
except SystemExit:
# _start_lapdog may call sys.exit on failure
os._exit(1)
os._exit(0)
# Parent: wait for the intermediate child to finish.
_, status = os.waitpid(child_pid, 0)
if os.WIFEXITED(status) and os.WEXITSTATUS(status) != 0:
print("[lapdog] Failed to start lapdog in background.", file=sys.stderr)
sys.exit(1)
# The forked child's exit can briefly disrupt the listening socket. Wait
# from the final parent too so immediate follow-up work, such as --backfill
# preflight POSTs, does not race the re-parented server.
for _ in range(50):
if _lapdog_alive(timeout=0.5):
return
time.sleep(0.2)
print("[lapdog] Lapdog failed to become reachable after background start.", file=sys.stderr)
sys.exit(1)
def cmd_exec(app_cmd: List[str], forward_data: bool) -> None:
"""Auto-start lapdog if needed, inject tracer env vars, then exec the app command. Never returns."""
resolved = shutil.which(app_cmd[0])
if not resolved:
print(f"[lapdog] Command not found: {app_cmd[0]}", file=sys.stderr)
sys.exit(1)
_ensure_lapdog_running(forward_data)
print(build_running_banner(data_type="application"))
_, port = _read_pid_file()
if port is None:
print("[lapdog] Could not determine lapdog port.", file=sys.stderr)
sys.exit(1)
env = tracer_inject.build_instrumented_env(port=port)
os.execvpe(resolved, app_cmd, env)
def cmd_claude(
sub_cmd_args: List[str],
forward_data: bool,
install_plugin: bool,
backfill: bool = False,
) -> None:
"""Ensure lapdog is running in background, then launch Claude with intercept.
When ``backfill`` is True: ensure lapdog is running, replay historical
Claude Code transcripts from ``~/.claude/projects`` through
``/claude/hooks``, and exit without launching Claude. ``forward_data``
is forced off and plugin installation is skipped during backfill.
"""
if backfill:
port = _ensure_lapdog_running(forward_data=False, detached=True)
if port is None:
print("[lapdog] Could not determine lapdog port.", file=sys.stderr)
sys.exit(1)
backfill_claude.backfill(f"http://localhost:{port}")
return
if install_plugin:
_ensure_lapdog_claude_code_plugin_installed()
_ensure_lapdog_running(forward_data, detached=True)
print(build_running_banner(data_type="coding session", warning_lines=_PROXY_SESSION_WARNING_LINES))
_run_claude(sub_cmd_args)
# ---------------------------------------------------------------------------
# Pi extension management
# ---------------------------------------------------------------------------
_PI_GLOBAL_EXT_DIR = os.path.expanduser("~/.pi/agent/extensions")
_PI_EXT_DEST = os.path.join(_PI_GLOBAL_EXT_DIR, "lapdog.ts")
_PI_EXT_SOURCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pi_lapdog_extension.ts")
def _install_pi_extension() -> None:
"""Copy the bundled lapdog extension into pi's global extensions directory.
If the extension is already installed and identical, skip the copy.
LAPDOG_URL is injected at runtime via environment variable when pi is launched.
"""
if not os.path.isfile(_PI_EXT_SOURCE):
print(f"[lapdog] Extension source not found: {_PI_EXT_SOURCE}", file=sys.stderr)
sys.exit(1)
with open(_PI_EXT_SOURCE, "r") as f:
source = f.read()
# Check if already installed and up-to-date.
is_update = False
if os.path.isfile(_PI_EXT_DEST):
try:
with open(_PI_EXT_DEST, "r") as f:
existing = f.read()
if existing == source:
print(f"[lapdog] pi extension already installed at {_PI_EXT_DEST}")
return
is_update = True
except OSError:
pass
os.makedirs(_PI_GLOBAL_EXT_DIR, exist_ok=True)
with open(_PI_EXT_DEST, "w") as f:
f.write(source)
if is_update:
print(f"[lapdog] Updated pi extension → {_PI_EXT_DEST}")
else:
print(f"[lapdog] Installed pi extension → {_PI_EXT_DEST}")
def _run_pi(args: Optional[List[str]] = None, port: Optional[int] = 8126) -> None:
"""Exec the pi binary, forwarding arguments. Never returns."""
if args is None:
args = []
pi_bin = shutil.which("pi")
if not pi_bin:
print("[lapdog] 'pi' not found in PATH", file=sys.stderr)
sys.exit(1)
env = {**os.environ, "LAPDOG_URL": f"http://localhost:{port}"}
os.execve(pi_bin, [pi_bin] + args, env)
def cmd_pi(sub_cmd_args: List[str], forward_data: bool, backfill: bool = False) -> None:
"""Ensure lapdog is running, install the pi extension, then launch pi.
When ``backfill`` is True: ensure lapdog is running, replay historical
Pi/OMP sessions through ``/pi/hooks``, and exit without launching pi.
The extension is not installed during backfill (no live capture to wire
up); ``forward_data`` is forced off.
"""
if backfill:
port = _ensure_lapdog_running(forward_data=False, detached=True)
if port is None:
print("[lapdog] Could not determine lapdog port.", file=sys.stderr)
sys.exit(1)
backfill_pi.backfill(f"http://localhost:{port}")
return
port = _ensure_lapdog_running(forward_data, detached=True)
_install_pi_extension()
print(build_running_banner(data_type="coding session"))
_run_pi(args=sub_cmd_args, port=port)
def _codex_watcher_pid_file(log_dir: str, singleton_key: str) -> str:
return os.path.join(log_dir, f"codex-watcher-{singleton_key}.pid")
def _codex_watcher_command(pid: int) -> Optional[str]:
"""Return the command line for a live watcher candidate, if it can be verified."""
if os.name == "nt":
cmd = [
"powershell",
"-NoProfile",
"-Command",
f'(Get-CimInstance Win32_Process -Filter "ProcessId = {int(pid)}").CommandLine',
]
else:
cmd = ["ps", "-p", str(pid), "-o", "command="]
try:
result = subprocess.run(
cmd,
check=False,
capture_output=True,
text=True,
timeout=2,
)
except (OSError, subprocess.SubprocessError):
return None
command = result.stdout.strip()
if result.returncode != 0 or not command:
return None
return command
def _arg_value(parts: List[str], flag: str) -> Optional[str]:
try:
idx = parts.index(flag)
except ValueError:
return None
return parts[idx + 1] if idx + 1 < len(parts) else None
def _codex_watcher_matches(
pid: int,
parent_pid: Optional[int] = None,
lapdog_url: Optional[str] = None,
include_all_cwds: Optional[bool] = None,
) -> bool:
"""Return True when a live process matches the expected watcher metadata."""
if not _process_exists(pid):
return False
command = _codex_watcher_command(pid)
if not command:
return False
try:
parts = shlex.split(command)
except ValueError:
parts = command.split()
if "lapdog.codex_watcher" not in parts:
return False
if parent_pid is not None and _arg_value(parts, "--parent-pid") != str(parent_pid):
return False
if lapdog_url is not None and _arg_value(parts, "--lapdog-url") != lapdog_url:
return False
if include_all_cwds is not None and ("--include-all-cwds" in parts) is not include_all_cwds:
return False
return True
def _codex_watcher_reusable(
pid: int,
parent_pid: int,
lapdog_url: Optional[str] = None,
include_all_cwds: Optional[bool] = None,
) -> bool:
"""Return True only when a pid file points at the expected watcher process.
App watcher pid files can outlive the short `lapdog codex app` launcher, so
PID existence alone is not enough: a recycled PID could point at an
unrelated process. Validate the command line before reusing or terminating.
"""
return _codex_watcher_matches(
pid,
parent_pid=parent_pid,
lapdog_url=lapdog_url,
include_all_cwds=include_all_cwds,
)
def _terminate_codex_watcher(pid: int, pid_path: str, message: str) -> bool:
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
pass
except OSError as exc:
print(f"[lapdog] Failed to stop Codex watcher (PID {pid}): {exc}", file=sys.stderr)
return False
print(message, file=sys.stderr)
try:
os.remove(pid_path)
except OSError:
pass
return True
def _stop_codex_watcher_pid_file(
pid_path: str,
parent_pid: int,
lapdog_url: Optional[str] = None,
include_all_cwds: Optional[bool] = None,
) -> None:
"""Terminate a verified watcher from a pid file and remove stale pid files."""
existing_pid, _ = _read_pid_file(path=pid_path)
if not existing_pid:
return
if not _process_exists(existing_pid):
try:
os.remove(pid_path)
except OSError:
pass
return
if not _codex_watcher_reusable(
existing_pid,
parent_pid,
lapdog_url=lapdog_url,
include_all_cwds=include_all_cwds,
):
return
_terminate_codex_watcher(
existing_pid,
pid_path,
f"[lapdog] Replacing legacy Codex watcher for this app workspace (PID {existing_pid}).",
)
def _stop_codex_watcher_singleton(
singleton_key: str,
parent_pid: int,
lapdog_url: Optional[str] = None,
include_all_cwds: Optional[bool] = None,
) -> None:
"""Stop one legacy app watcher identified by its singleton key."""
log_dir = os.path.dirname(_log_file_path())
pid_path = _codex_watcher_pid_file(log_dir, singleton_key)
_stop_codex_watcher_pid_file(
pid_path,
parent_pid,
lapdog_url=lapdog_url,
include_all_cwds=include_all_cwds,
)
def _stop_all_codex_watchers() -> None:
"""Stop all running codex watcher processes found in the log directory."""
log_dir = os.path.dirname(_log_file_path())
try:
filenames = os.listdir(log_dir)
except OSError:
return
prefix = "codex-watcher-"
suffix = ".pid"
for filename in filenames:
if not filename.startswith(prefix) or not filename.endswith(suffix):
continue
pid_path = os.path.join(log_dir, filename)
existing_pid, _ = _read_pid_file(path=pid_path)
if not existing_pid:
continue
if not _codex_watcher_matches(existing_pid):
try:
os.remove(pid_path)
except OSError:
pass
continue
_terminate_codex_watcher(
existing_pid,
pid_path,
f"[lapdog] Stopped Codex watcher (PID {existing_pid}).",
)
def _stop_legacy_codex_app_watchers(port: int, parent_pid: int, keep_singleton_key: str) -> None:
"""Stop verified cwd-keyed app watchers after migrating to one all-cwd watcher."""
log_dir = os.path.dirname(_log_file_path())
try:
filenames = os.listdir(log_dir)
except OSError:
return
prefix = "codex-watcher-"
suffix = ".pid"
lapdog_url = f"http://localhost:{port}"
for filename in filenames:
if not filename.startswith(prefix) or not filename.endswith(suffix):
continue
singleton_key = filename[len(prefix) : -len(suffix)]
if singleton_key == keep_singleton_key:
continue
_stop_codex_watcher_singleton(
singleton_key,
parent_pid,
lapdog_url=lapdog_url,
include_all_cwds=False,
)
def _start_codex_watcher(
port: int,
proxy_session_key: Optional[str] = None,
cwd: Optional[str] = None,
parent_pid: Optional[int] = None,
singleton_key: Optional[str] = None,
include_all_cwds: bool = False,
) -> None:
"""Start the bundled Codex JSONL watcher for this working directory."""
watcher_cwd = os.path.abspath(cwd or os.getcwd())
watcher_parent_pid = parent_pid or os.getpid()
log_path = _log_file_path()
log_dir = os.path.dirname(log_path)
os.makedirs(log_dir, exist_ok=True)
lapdog_url = f"http://localhost:{port}"
if singleton_key:
pid_path = _codex_watcher_pid_file(log_dir, singleton_key)
existing_pid, _ = _read_pid_file(path=pid_path)
if existing_pid and _codex_watcher_reusable(
existing_pid,
watcher_parent_pid,
lapdog_url=lapdog_url,
include_all_cwds=include_all_cwds,
):
print(
f"[lapdog] Codex watcher already running for this app workspace (PID {existing_pid}).",
flush=True,
)
return
if existing_pid:
if _codex_watcher_matches(existing_pid, lapdog_url=lapdog_url, include_all_cwds=include_all_cwds):
_terminate_codex_watcher(
existing_pid,
pid_path,
f"[lapdog] Replacing stale Codex watcher for this app workspace (PID {existing_pid}).",
)
else:
print(
f"[lapdog] Replacing stale Codex watcher for this app workspace (PID {existing_pid}).",
file=sys.stderr,
)
else:
pid_path = None
ready_path = os.path.join(log_dir, f"codex-watcher-{os.getpid()}.ready")
try:
os.unlink(ready_path)
except OSError:
pass
args = [
sys.executable,
"-m",
"lapdog.codex_watcher",
"--lapdog-url",
f"http://localhost:{port}",
"--cwd",
watcher_cwd,
"--parent-pid",
str(watcher_parent_pid),
"--ready-file",
ready_path,
]
if proxy_session_key:
args += ["--proxy-session-key", proxy_session_key]
if include_all_cwds:
args += ["--include-all-cwds", "--cursor-path", CODEX_APP_CURSOR_FILE]
with open(log_path, "a") as log_file:
process = subprocess.Popen(
args,
stdin=subprocess.DEVNULL,
stdout=log_file,
stderr=subprocess.STDOUT,
start_new_session=True,
)
if pid_path:
with open(pid_path, "w") as f:
f.write(f"{process.pid}\n")
deadline = time.time() + 2
while time.time() < deadline:
if os.path.exists(ready_path):
return
if process.poll() is not None:
break
time.sleep(0.05)
print("[lapdog] Codex watcher did not confirm startup; continuing without startup confirmation.", file=sys.stderr)
def _run_codex(
args: Optional[List[str]] = None, port: Optional[int] = None, proxy_session_key: Optional[str] = None
) -> None:
"""Exec the codex binary, forwarding arguments. Never returns."""
if args is None:
args = []
codex_bin = shutil.which("codex")
if not codex_bin:
print("[lapdog] 'codex' not found in PATH", file=sys.stderr)
sys.exit(1)
env = os.environ.copy()
proxy_args: List[str] = []
if port is not None:
proxy_path = f"/codex/proxy/{proxy_session_key}/v1" if proxy_session_key else "/codex/proxy/v1"
base_url = f"http://localhost:{port}{proxy_path}"
env["OPENAI_BASE_URL"] = base_url
if env.get("OPENAI_API_KEY"):
proxy_args = [
"-c",
'model_provider="openai-lapdog"',
"-c",
(
'model_providers.openai-lapdog={name="OpenAI via Lapdog",'
f' base_url="{base_url}", env_key="OPENAI_API_KEY", wire_api="responses"' + "}"
),
]
else:
print(
"[lapdog] Codex proxy capture requires OPENAI_API_KEY; continuing with JSONL-only tracing.",
file=sys.stderr,
)
os.execve(codex_bin, [codex_bin] + proxy_args + args, env)
def cmd_codex(sub_cmd_args: List[str], forward_data: bool, backfill: bool = False) -> None:
"""Ensure lapdog is running, start the Codex JSONL watcher, then launch Codex.
When ``backfill`` is True: ensure lapdog is running, replay historical
rollouts from ``~/.codex/sessions`` through ``/codex/hooks``, and exit
without launching Codex. ``forward_data`` is ignored (forced off) so a
backfill never accidentally streams thousands of historical spans to
Datadog.
"""
if backfill:
port = _ensure_lapdog_running(forward_data=False, detached=True)
if port is None:
print("[lapdog] Could not determine lapdog port.", file=sys.stderr)
sys.exit(1)
backfill_codex.backfill(f"http://localhost:{port}", cwd=codex_args.resolve_cwd(sub_cmd_args))
return
port = _ensure_lapdog_running(forward_data, detached=True)
if port is None:
print("[lapdog] Could not determine lapdog port.", file=sys.stderr)
sys.exit(1)
app_mode = codex_args.is_app_command(sub_cmd_args)
proxy_session_key = None if app_mode else uuid.uuid4().hex
parent_pid = os.getpid()
if app_mode:
lapdog_pid, _ = _read_pid_file()
parent_pid = lapdog_pid or parent_pid
codex_cwd = codex_args.resolve_cwd(sub_cmd_args)
if app_mode:
_stop_legacy_codex_app_watchers(port, parent_pid, codex_args.app_watcher_key(port))
_start_codex_watcher(
port,
proxy_session_key=proxy_session_key,
cwd=codex_cwd,
parent_pid=parent_pid,
singleton_key=codex_args.app_watcher_key(port) if app_mode else None,
include_all_cwds=app_mode,
)
print(build_running_banner(data_type="coding session", warning_lines=_PROXY_SESSION_WARNING_LINES))
_run_codex(args=sub_cmd_args, port=port, proxy_session_key=proxy_session_key)
def cmd_uninstall() -> None:
"""Stop the lapdog server, removes ~/.lapdog directory, and uninstalls managed plugins"""
# stop lapdog server
pid, _ = _read_pid_file()
if pid is not None:
cmd_stop(pid=pid)
# remove ~/.lapdog dir
if os.path.isdir(LAPDOG_DIR):
shutil.rmtree(LAPDOG_DIR, ignore_errors=True)
print("[lapdog] Lapdog-related files under ~/.lapdog removed")
# remove claude code plugin
_uninstall_lapdog_claude_code_plugin()
# remove pi extension
if os.path.isfile(_PI_EXT_DEST):
try:
os.remove(_PI_EXT_DEST)
print(f"[lapdog] Removed {_PI_EXT_DEST}.")
except OSError as e:
print(f"[lapdog] Failed to remove {_PI_EXT_DEST}: {e}", file=sys.stderr)
# stop codex watcher(s)
_stop_all_codex_watchers()
print(
"[lapdog] Lapdog cleanup complete. Now uninstall the package:\n"
"[lapdog] brew uninstall lapdog\n"
"[lapdog] pipx uninstall ddapm-test-agent\n"
"[lapdog] pip uninstall ddapm-test-agent"
)
def _parse_command(cmd_args: List[str]) -> Tuple[List[str], List[str]]:
lapdog_args: List[str] = []
for arg_idx, arg in enumerate(cmd_args):
if not arg.startswith("--"):
return lapdog_args, cmd_args[arg_idx:]
lapdog_args.append(arg)
# no sub command found
print(LAPDOG_USAGE, file=sys.stderr)
sys.exit(1)
def _parse_lapdog_args(lapdog_args: List[str]) -> argparse.Namespace:
"""Parse lapdog-specific args"""
parser = argparse.ArgumentParser(
description="Lapdog CLI",
prog="lapdog",
)
parser.add_argument(
"--forward",
action="store_true",
default=False,
help="Enable data forwarding to Datadog.",
)
parser.add_argument(
"--no-plugin-install",
dest="install_plugin",
action="store_false",
default=True,
help=(
"Skip auto-installing the 'lapdog' Claude Code plugin when running "
f"'lapdog claude'. By default, lapdog runs 'claude plugin marketplace "
f"add {LAPDOG_MARKETPLACE_SOURCE}' and 'claude plugin install "
f"{LAPDOG_PLUGIN_NAME}' if the plugin is not already installed."
),
)
parser.add_argument(
"--backfill",
action="store_true",
default=False,
help=(
"Ingest historical sessions from disk by replaying them through the local "