-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcq
More file actions
executable file
·3193 lines (2793 loc) · 119 KB
/
cq
File metadata and controls
executable file
·3193 lines (2793 loc) · 119 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
#!/usr/bin/env python3
"""
cq (Code Quorum) - Unified AI Launcher
Split-pane collaboration between Claude and Codex using tmux or WezTerm.
"""
import sys
import os
import json
import time
import subprocess
import signal
import atexit
import argparse
import uuid
import getpass
import platform
import tempfile
import re
import shutil
import posixpath
import shlex
from pathlib import Path
script_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(script_dir / "lib"))
from terminal import TmuxBackend, WeztermBackend, detect_terminal
from compat import setup_windows_encoding
from cq_config import get_backend_env
from cq_start_config import DEFAULT_PROVIDERS, ensure_default_start_config, load_start_config
from session_utils import safe_write_session, check_session_writable, find_project_session_file
from session_scope import DEFAULT_SESSION, SESSION_ENV_VAR, normalize_session_name, project_session_dir, resolve_session_name
from session_registry import upsert_registry
from project_id import compute_cq_project_id
from process_lock import ProviderLock
from messages import t
setup_windows_encoding()
backend_env = get_backend_env()
if backend_env and not os.environ.get("CQ_BACKEND_ENV"):
os.environ["CQ_BACKEND_ENV"] = backend_env
VERSION = "5.1.3"
GIT_COMMIT = ""
GIT_DATE = ""
def _normalize_path_for_match(value: str) -> str:
"""
Normalize a path-like string for loose matching (macOS/Linux only).
This is used only for selecting a session for *current* cwd, so favor robustness.
"""
s = (value or "").strip()
if not s:
return ""
# Expand "~" early (common in shell-originated values). If expansion fails, keep original.
if s.startswith("~"):
try:
s = os.path.expanduser(s)
except Exception:
pass
try:
p = Path(s)
if not p.is_absolute():
s = str((Path.cwd() / p).absolute())
except Exception:
pass
s = s.replace("\\", "/")
# Collapse redundant separators and dot segments using POSIX semantics (we forced "/").
if s.startswith("//"):
prefix = "//"
rest = s[2:]
rest = posixpath.normpath(rest)
s = prefix + rest.lstrip("/")
else:
s = posixpath.normpath(s)
# Drop trailing slash (but keep "/").
if len(s) > 1 and s.endswith("/"):
s = s.rstrip("/")
return s
def _work_dir_match_keys(work_dir: Path) -> set[str]:
keys: set[str] = set()
candidates: list[str] = []
for raw in (os.environ.get("PWD"), str(work_dir)):
if raw:
candidates.append(raw)
try:
candidates.append(str(work_dir.resolve()))
except Exception:
pass
for candidate in candidates:
normalized = _normalize_path_for_match(candidate)
if normalized:
keys.add(normalized)
return keys
def _normpath_within(child_norm: str, parent_norm: str) -> bool:
"""
Return True if normalized path `child_norm` is equal to or inside `parent_norm`.
Both args must be normalized via `_normalize_path_for_match` (or equivalent).
"""
if not child_norm or not parent_norm:
return False
if child_norm == parent_norm:
return True
prefix = parent_norm if parent_norm.endswith("/") else (parent_norm + "/")
return child_norm.startswith(prefix)
def _extract_session_work_dir_norm(session_data: dict) -> str:
"""Extract a normalized work dir marker from a session file payload."""
if not isinstance(session_data, dict):
return ""
raw_norm = session_data.get("work_dir_norm")
if isinstance(raw_norm, str) and raw_norm.strip():
return _normalize_path_for_match(raw_norm)
raw = session_data.get("work_dir")
if isinstance(raw, str) and raw.strip():
return _normalize_path_for_match(raw)
return ""
def _get_git_info() -> str:
try:
result = subprocess.run(
["git", "-C", str(script_dir), "log", "-1", "--format=%h %ci"],
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=2
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return ""
def _build_keep_open_cmd(provider: str, start_cmd: str) -> str:
return (
f'{start_cmd}; '
f'code=$?; '
f'echo; echo "[{provider}] exited with code $code. Press Enter to close..."; '
f'read -r _; '
f'exit $code'
)
def _build_pane_title_cmd(marker: str) -> str:
return f"printf '\\033]0;{marker}\\007'; "
def _build_export_path_cmd(bin_dir: Path) -> str:
"""
Ensure CQ's `bin/` is available inside the started pane/session.
This allows running CQ's CLI helpers consistently across WezTerm/tmux.
"""
bin_s = str(bin_dir)
# Materialize PATH from the current CQ process instead of relying on the spawned shell's `$PATH`.
# This fixes macOS/Homebrew setups where `python3` exists in the interactive shell, but a spawned
# pane/session (tmux/Terminal.app) starts with a minimal PATH and `/usr/bin/env python3` fails.
current = os.environ.get("PATH") or ""
if current:
return f"export PATH={shlex.quote(bin_s)}{os.pathsep}{shlex.quote(current)}; "
return f"export PATH={shlex.quote(bin_s)}{os.pathsep}$PATH; "
def _build_cd_cmd(work_dir: Path) -> str:
return f"cd {shlex.quote(str(work_dir))}; "
def _env_bool(name: str, default: bool) -> bool:
raw = os.environ.get(name)
if raw is None or raw == "":
return default
v = raw.strip().lower()
if v in {"1", "true", "yes", "on"}:
return True
if v in {"0", "false", "no", "off"}:
return False
return default
def _env_float(name: str, default: float) -> float:
raw = os.environ.get(name)
if raw is None or raw == "":
return default
try:
return float(raw)
except Exception:
return default
def _cleanup_tmpclaude_artifacts() -> int:
"""
Best-effort cleanup for leftover Claude temp markers like `tmpclaude-xxxx-cwd`.
Deletion is conservative: only removes entries older than `CQ_TMPCLAUDE_MIN_AGE_S`.
Controls:
- `CQ_TMPCLAUDE_CLEAN` (default: true)
- `CQ_TMPCLAUDE_CLEAN_CWD` (default: true)
- `CQ_TMPCLAUDE_MIN_AGE_S` (default: 300)
- `CQ_TMPCLAUDE_DIRS` (extra dirs, split by `os.pathsep`)
- `CQ_TMPCLAUDE_PATTERNS` (comma-separated globs; default: tmpclaude-*-cwd)
"""
if not _env_bool("CQ_TMPCLAUDE_CLEAN", True):
return 0
patterns_raw = (os.environ.get("CQ_TMPCLAUDE_PATTERNS") or "").strip()
patterns = [p.strip() for p in patterns_raw.split(",") if p.strip()] if patterns_raw else ["tmpclaude-*-cwd"]
min_age_s = max(0.0, float(_env_float("CQ_TMPCLAUDE_MIN_AGE_S", 300.0)))
dirs: list[Path] = []
if _env_bool("CQ_TMPCLAUDE_CLEAN_CWD", True):
dirs.append(Path.cwd())
try:
dirs.append(Path(tempfile.gettempdir()))
except Exception:
pass
extra = (os.environ.get("CQ_TMPCLAUDE_DIRS") or "").strip()
if extra:
for part in extra.split(os.pathsep):
p = part.strip()
if not p:
continue
try:
dirs.append(Path(p).expanduser())
except Exception:
continue
seen_dirs: set[str] = set()
unique_dirs: list[Path] = []
for d in dirs:
key = str(d)
if key in seen_dirs:
continue
seen_dirs.add(key)
unique_dirs.append(d)
now = time.time()
removed = 0
for base in unique_dirs:
try:
if not base.exists() or not base.is_dir():
continue
except Exception:
continue
for pat in patterns:
try:
candidates = list(base.glob(pat))
except Exception:
candidates = []
for path in candidates:
try:
st = path.stat()
if min_age_s and (now - float(st.st_mtime)) < min_age_s:
continue
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
else:
path.unlink(missing_ok=True)
removed += 1
except Exception:
continue
return removed
def _is_pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(int(pid), 0)
return True
except Exception:
return False
def _runtime_base_dir() -> Path:
try:
base = Path(tempfile.gettempdir())
except Exception:
base = Path("/tmp")
return base / f"claude-ai-{getpass.getuser()}"
def _cleanup_stale_runtime_dirs(*, exclude: Path | None = None) -> int:
"""
Best-effort garbage collection for stale CQ runtime dirs under `$TMP/claude-ai-<user>/ai-*`.
Normal exits already remove the current `runtime_dir`. This targets leftovers from crashes
or hard kills (e.g. SIGKILL).
"""
if not _env_bool("CQ_RUNTIME_GC", True):
return 0
min_age_s = max(0.0, float(_env_float("CQ_RUNTIME_GC_MIN_AGE_S", 24 * 3600.0)))
base = _runtime_base_dir()
try:
if not base.exists() or not base.is_dir():
return 0
except Exception:
return 0
exclude_resolved: str | None = None
if exclude is not None:
try:
exclude_resolved = str(Path(exclude).resolve())
except Exception:
exclude_resolved = str(exclude)
now = time.time()
removed = 0
try:
candidates = sorted(base.glob("ai-*"), key=lambda p: p.stat().st_mtime if p.exists() else 0.0)
except Exception:
candidates = []
for session_dir in candidates:
try:
if not session_dir.is_dir():
continue
except Exception:
continue
try:
if exclude_resolved and str(session_dir.resolve()) == exclude_resolved:
continue
except Exception:
if exclude_resolved and str(session_dir) == exclude_resolved:
continue
try:
st = session_dir.stat()
if min_age_s and (now - float(st.st_mtime)) < min_age_s:
continue
except Exception:
continue
# If any recorded PID is alive, don't delete.
alive = False
try:
for pid_file in session_dir.glob("**/*.pid"):
try:
raw = pid_file.read_text(encoding="utf-8", errors="ignore").strip()
if raw.isdigit() and _is_pid_alive(int(raw)):
alive = True
break
except Exception:
continue
except Exception:
pass
if alive:
continue
try:
shutil.rmtree(session_dir, ignore_errors=True)
removed += 1
except Exception:
continue
return removed
class AILauncher:
def __init__(
self,
providers: list,
resume: bool = False,
auto: bool = False,
cmd_config: dict | None = None,
session_name: str = DEFAULT_SESSION,
):
self.providers = providers or ["codex"]
self.resume = resume
self.auto = auto
self.cmd_config = self._normalize_cmd_config(cmd_config)
self.script_dir = Path(__file__).resolve().parent
self.invocation_dir = Path.cwd()
self.cq_session_name = normalize_session_name(session_name)
# Project root is strictly the current working directory.
# Do NOT traverse upwards to infer a different root.
try:
self.project_root = self.invocation_dir.resolve()
except Exception:
self.project_root = self.invocation_dir.absolute()
self.session_id = f"ai-{int(time.time())}-{os.getpid()}"
self.cq_pid = os.getpid()
self.project_id = compute_cq_project_id(self.project_root)
project_hash = (self.project_id or "")[:16] or "unknown"
self.project_run_dir = (Path.home() / ".cache" / "cq" / "projects" / project_hash)
self.temp_base = Path(tempfile.gettempdir())
self.runtime_dir = self.temp_base / f"claude-ai-{getpass.getuser()}" / self.session_id
self.runtime_dir.mkdir(parents=True, exist_ok=True)
self._cleaned = False
self.terminal_type = self._detect_terminal_type()
self.tmux_sessions = {}
self.tmux_panes = {}
self.wezterm_panes = {}
self.extra_panes = {}
self.processes = {}
self.anchor_provider = None
self.anchor_pane_id = None
self._migrate_legacy_project_files()
os.environ["CQ_MANAGED"] = "1"
os.environ["CQ_PARENT_PID"] = str(self.cq_pid)
os.environ[SESSION_ENV_VAR] = self.cq_session_name
os.environ.setdefault("CQ_RUN_DIR", str(self.project_run_dir))
def _managed_env_overrides(self) -> dict:
env = {
"CQ_MANAGED": "1",
"CQ_PARENT_PID": str(self.cq_pid),
SESSION_ENV_VAR: self.cq_session_name,
}
if os.environ.get("CQ_RUN_DIR"):
env["CQ_RUN_DIR"] = os.environ["CQ_RUN_DIR"]
return env
def _project_config_dir(self) -> Path:
return self.project_root / ".cq_config"
def _project_session_dir(self) -> Path:
return project_session_dir(self.project_root, self.cq_session_name)
def _ensure_project_session_dir(self) -> bool:
session_dir = self._project_session_dir()
if session_dir.is_dir():
return True
try:
session_dir.mkdir(parents=True, exist_ok=True)
return True
except Exception as exc:
print(f"❌ Failed to create session directory: {session_dir}: {exc}", file=sys.stderr)
print(f"💡 Fix: mkdir -p {session_dir}", file=sys.stderr)
return False
def _project_session_file(self, filename: str) -> Path:
return self._project_session_dir() / filename
def _migrate_legacy_project_files(self) -> None:
"""
Move legacy project dotfiles from the project root into `.cq_config/`.
This keeps the project root clean while preserving backwards-compatible lookup
(see `lib/session_utils.py:find_project_session_file`).
"""
cfg = self._project_config_dir()
if not cfg.is_dir():
return
for name in (".codex-session", ".claude-session"):
legacy = self.project_root / name
if not legacy.exists():
continue
try:
target = cfg / name
if not target.exists():
legacy.replace(target)
continue
# Keep both, but move the legacy one under `.cq_config/` with a suffix.
suffix = time.strftime("%Y%m%d%H%M%S")
legacy.replace(cfg / f"{name}.legacy.{suffix}")
except Exception:
pass
def _normalize_cmd_config(self, raw: dict | None) -> dict:
if raw is None or raw is False:
return {"enabled": False}
if isinstance(raw, bool):
return {"enabled": bool(raw)}
if isinstance(raw, str):
return {"enabled": True, "start_cmd": raw.strip()}
if isinstance(raw, dict):
enabled = raw.get("enabled")
if enabled is None:
enabled = True
start_cmd = raw.get("start_cmd") or raw.get("command") or raw.get("cmd") or ""
title = raw.get("title") or raw.get("name") or "CQ-Cmd"
return {
"enabled": bool(enabled),
"start_cmd": str(start_cmd).strip(),
"title": str(title).strip() or "CQ-Cmd",
}
return {"enabled": False}
def _cmd_settings(self) -> dict:
cfg = self.cmd_config or {}
if not cfg or not cfg.get("enabled"):
return {"enabled": False}
title = (cfg.get("title") or "CQ-Cmd").strip() or "CQ-Cmd"
start_cmd = (cfg.get("start_cmd") or "").strip()
if not start_cmd:
start_cmd = self._default_cmd_start_cmd()
return {"enabled": True, "title": title, "start_cmd": start_cmd}
def _default_cmd_start_cmd(self) -> str:
shell = (os.environ.get("SHELL") or "bash").strip() or "bash"
if not shutil.which(shell):
shell = "bash"
return shell
def _with_bin_path_env(self, env: dict | None = None) -> dict:
base = dict(env or os.environ)
bin_path = str(self.script_dir / "bin")
current = base.get("PATH") or ""
parts = current.split(os.pathsep) if current else []
if bin_path not in parts:
base["PATH"] = bin_path + (os.pathsep + current if current else "")
return base
def _current_pane_id(self) -> str:
if self.terminal_type == "wezterm":
return (os.environ.get("WEZTERM_PANE") or "").strip()
try:
backend = TmuxBackend()
return backend.get_current_pane_id()
except Exception:
return (os.environ.get("TMUX_PANE") or "").strip()
def _build_env_prefix(self, env: dict) -> str:
if not env:
return ""
parts = []
for key, val in env.items():
if val is None:
continue
parts.append(f"export {key}={shlex.quote(str(val))}; ")
return "".join(parts)
def _provider_pane_id(self, provider: str) -> str:
prov = (provider or "").strip().lower()
anchor = (self.anchor_provider or "").strip().lower()
if prov and prov == anchor and self.anchor_pane_id:
return str(self.anchor_pane_id)
if self.terminal_type == "wezterm":
return str(self.wezterm_panes.get(prov, "") or "")
return str(self.tmux_panes.get(prov, "") or "")
def _short_run_id(self) -> str:
sid = str(self.session_id or "").strip()
parts = sid.split("-")
if len(parts) >= 3 and parts[0] == "ai":
ts = parts[1]
pid = parts[2]
if ts.isdigit() and pid.isdigit():
return f"{ts[-6:]}-{pid}"
return sid[-12:] if len(sid) > 12 else sid
def _pane_title_marker(self, provider: str) -> str:
prov = (provider or "").strip().lower()
prov_label = prov.capitalize() if prov else "Unknown"
session_label = str(self.cq_session_name or "").strip() or DEFAULT_SESSION
if session_label == DEFAULT_SESSION:
try:
project_name = str(getattr(self, "project_root", Path.cwd()).name or "").strip()
except Exception:
project_name = ""
if project_name:
session_label = project_name
# Keep titles readable and safe across terminals.
session_label = re.sub(r"[^A-Za-z0-9_.-]+", "-", session_label).strip("-") or DEFAULT_SESSION
return f"CQ-{session_label}-{prov_label}-{self._short_run_id()}"
def _set_current_pane_title_escape(self, title: str) -> None:
"""
Best-effort set the terminal title for the *current* pane (useful for WezTerm).
In tmux, prefer `set_pane_title` to avoid relying on terminal title escape behavior.
"""
try:
sys.stdout.write(f"\033]0;{title}\007")
sys.stdout.flush()
except Exception:
pass
def _set_current_pane_label(self, provider: str) -> None:
if self.terminal_type != "tmux":
return
if not os.environ.get("TMUX"):
return
try:
backend = TmuxBackend()
pane_id = backend.get_current_pane_id()
title = self._pane_title_marker(provider)
backend.set_pane_title(pane_id, title)
backend.set_pane_user_option(pane_id, "@cq_agent", provider.capitalize())
except Exception:
pass
def _run_shell_command(self, cmd: str, *, env: dict | None = None, cwd: str | None = None) -> int:
cmd = cmd or ""
env = self._with_bin_path_env(env)
shell = (os.environ.get("SHELL") or "bash").strip() or "bash"
if not shutil.which(shell):
shell = "bash"
return subprocess.run([shell, "-lc", cmd], env=env, cwd=cwd).returncode
def _detect_terminal_type(self):
# Forced by environment variable
forced = (os.environ.get("CQ_TERMINAL") or os.environ.get("CODEX_TERMINAL") or "").strip().lower()
if forced in {"wezterm", "tmux"}:
return forced
detected = detect_terminal()
if detected:
return detected
# Nothing found
return None
def _detect_launch_terminal(self):
"""Select terminal program for launching new windows (tmux mode only)"""
# WezTerm mode doesn't need external terminal program
if self.terminal_type == "wezterm":
return None
# tmux mode: select terminal
terminals = ["gnome-terminal", "konsole", "alacritty", "xterm"]
for term in terminals:
if shutil.which(term):
return term
return "tmux"
def _set_tmux_ui_active(self, active: bool) -> None:
"""
Enable/disable CQ tmux UI theming for the *current tmux session*.
This is session-scoped and reversible (saves/restores user options) via helper scripts
installed to `~/.local/bin/`.
"""
if self.terminal_type != "tmux":
return
if not os.environ.get("TMUX"):
return
candidates = ["cq-tmux-on.sh"] if active else ["cq-tmux-off.sh"]
script_path = None
for name in candidates:
found = shutil.which(name)
if found:
script_path = Path(found)
break
if not script_path or not script_path.exists():
return
try:
debug = (os.environ.get("CQ_DEBUG") or "").strip().lower() in ("1", "true", "yes")
cp = subprocess.run(
[str(script_path)],
check=False,
capture_output=debug,
text=True,
encoding="utf-8",
errors="replace",
)
if cp.returncode != 0 and debug:
out = (cp.stdout or "").strip()
err = (cp.stderr or "").strip()
detail = "\n".join([s for s in [out, err] if s])
if detail:
print(
f"⚠️ tmux ui script failed (rc={cp.returncode}):\n{detail}",
file=sys.stderr,
)
except Exception:
return
def _launch_script_in_macos_terminal(self, script_file: Path) -> bool:
"""macOS: Use Terminal.app to open new window for script (avoid tmux launcher nesting issues)"""
if platform.system() != "Darwin":
return False
if not shutil.which("osascript"):
return False
env = os.environ.copy()
env["CQ_WRAPPER_SCRIPT"] = str(script_file)
subprocess.Popen(
[
"osascript",
"-e",
'tell application "Terminal" to do script "/bin/bash " & quoted form of (system attribute "CQ_WRAPPER_SCRIPT")',
"-e",
'tell application "Terminal" to activate',
],
env=env,
)
return True
def _start_provider(self, provider: str, *, parent_pane: str | None = None, direction: str | None = None) -> str | None:
# Handle case when no terminal detected
if self.terminal_type is None:
print(f"❌ {t('no_terminal_backend')}")
print(f" {t('solutions')}")
print(f" - {t('install_wezterm')}")
print(f" - {t('or_install_tmux')}")
if shutil.which("tmux") and not (os.environ.get("TMUX") or os.environ.get("TMUX_PANE")):
print(f" - {t('tmux_installed_not_inside')}")
print(f" - {t('or_set_cq_terminal')}")
return None
# WezTerm mode: no tmux dependency
if self.terminal_type == "wezterm":
print(f"🚀 {t('starting_backend', provider=provider.capitalize(), terminal='wezterm')}")
return self._start_provider_wezterm(provider, parent_pane=parent_pane, direction=direction)
# tmux mode: check if tmux is available
if not shutil.which("tmux"):
# Try fallback to WezTerm
if detect_terminal() == "wezterm":
self.terminal_type = "wezterm"
print(f"🚀 {t('starting_backend', provider=provider.capitalize(), terminal='wezterm - tmux unavailable')}")
return self._start_provider_wezterm(provider, parent_pane=parent_pane, direction=direction)
else:
print(f"❌ {t('tmux_not_installed')}")
print(f" {t('install_wezterm_or_tmux')}")
return None
# Require an existing tmux client session (no auto-launch).
if not (os.environ.get("TMUX") or os.environ.get("TMUX_PANE")):
print(f"❌ {t('tmux_installed_not_inside')}", file=sys.stderr)
print(f"💡 Run: tmux", file=sys.stderr)
print(f" Then: {' '.join(['cq', *sys.argv[1:]])}", file=sys.stderr)
return None
print(f"🚀 {t('starting_backend', provider=provider.capitalize(), terminal='tmux')}")
if provider == "codex":
return self._start_codex_tmux(parent_pane=parent_pane, direction=direction)
else:
print(f"❌ {t('unknown_provider', provider=provider)}")
return None
def _start_provider_wezterm(
self,
provider: str,
*,
parent_pane: str | None = None,
direction: str | None = None,
) -> str | None:
if provider != "codex":
print(f"❌ {t('unknown_provider', provider=provider)}")
return None
runtime = self.runtime_dir / provider
runtime.mkdir(parents=True, exist_ok=True)
start_cmd = self._get_start_cmd(provider)
keep_open = os.environ.get("CODEX_WEZTERM_KEEP_OPEN", "1").lower() not in {"0", "false", "no", "off"}
if keep_open:
start_cmd = _build_keep_open_cmd(provider, start_cmd)
use_direction = (direction or ("right" if not self.wezterm_panes else "bottom")).strip() or "right"
use_parent = parent_pane
if not use_parent and use_direction == "bottom":
try:
use_parent = next(reversed(self.wezterm_panes.values()))
except StopIteration:
use_parent = None
pane_title_marker = self._pane_title_marker(provider)
title_cmd = _build_pane_title_cmd(pane_title_marker)
env_overrides = self._managed_env_overrides()
full_cmd = title_cmd + self._build_env_prefix(env_overrides) + _build_export_path_cmd(self.script_dir / "bin") + start_cmd
backend = WeztermBackend()
pane_id = backend.create_pane(full_cmd, str(Path.cwd()), direction=use_direction, percent=50, parent_pane=use_parent)
self.wezterm_panes[provider] = pane_id
self._write_codex_session(
runtime,
None,
pane_id=pane_id,
pane_title_marker=pane_title_marker,
codex_start_cmd=start_cmd,
)
print(f"✅ {t('started_backend', provider=provider.capitalize(), terminal='wezterm pane', pane_id=pane_id)}")
return pane_id
def _work_dir_strings(self, work_dir: Path) -> list[str]:
candidates: list[str] = []
env_pwd = os.environ.get("PWD")
if env_pwd:
candidates.append(env_pwd)
candidates.append(str(work_dir))
try:
candidates.append(str(work_dir.resolve()))
except Exception:
pass
# de-dup while preserving order
seen: set[str] = set()
result: list[str] = []
for candidate in candidates:
if candidate not in seen:
seen.add(candidate)
result.append(candidate)
return result
def _read_json_file(self, path: Path) -> dict:
try:
if not path.exists():
return {}
# Session files are written as UTF-8; always decode explicitly and tolerate UTF-8 BOM.
raw = path.read_text(encoding="utf-8-sig")
data = json.loads(raw)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _write_json_file(self, path: Path, data: dict) -> None:
try:
if not path.parent.is_dir():
raise FileNotFoundError(str(path.parent))
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
except Exception:
pass
def _require_project_config_dir(self) -> bool:
cfg = self._project_config_dir()
if cfg.is_dir():
return True
print("❌ Missing required project config directory: .cq_config", file=sys.stderr)
print(f" project_root: {self.project_root}", file=sys.stderr)
print(f" cwd: {Path.cwd()}", file=sys.stderr)
print(f"💡 Fix: mkdir -p {cfg}", file=sys.stderr)
return False
def _clear_codex_log_binding(self, data: dict) -> dict:
try:
if not isinstance(data, dict):
return {}
cleared = dict(data)
for key in ("codex_session_path", "codex_session_id", "codex_start_cmd"):
if key in cleared:
cleared.pop(key, None)
if cleared.get("active") is False:
cleared["active"] = True
return cleared
except Exception as exc:
print(f"⚠️ codex_session_clear_failed: {exc}", file=sys.stderr)
return data if isinstance(data, dict) else {}
def _claude_session_file(self) -> Path:
return self._project_session_file(".claude-session")
def _read_local_claude_session_id(self) -> str | None:
data = self._read_json_file(self._claude_session_file())
sid = data.get("claude_session_id")
if not sid:
legacy = data.get("session_id")
if isinstance(legacy, str) and legacy.strip():
try:
uuid.UUID(legacy)
sid = legacy
except Exception:
sid = None
if isinstance(sid, str) and sid.strip():
# Guard against path-format mismatch (Windows case/slash differences, MSYS paths, etc.).
recorded_norm = _extract_session_work_dir_norm(data)
if not recorded_norm:
# Old/foreign session file without a recorded work dir: refuse to resume to avoid cross-project reuse.
return None
current_keys = _work_dir_match_keys(Path.cwd())
if current_keys and recorded_norm not in current_keys:
return None
return sid.strip()
return None
def _write_local_claude_session(
self,
session_id: str | None = None,
*,
active: bool = True,
pane_id: str | None = None,
pane_title_marker: str | None = None,
terminal: str | None = None,
) -> None:
if not self._ensure_project_session_dir():
return
path = self._claude_session_file()
writable, reason, fix = check_session_writable(path)
if not writable:
print(f"❌ Cannot write {path.name}: {reason}", file=sys.stderr)
print(f"💡 Fix: {fix}", file=sys.stderr)
return
data = self._read_json_file(path) if path.exists() else {}
work_dir = self.project_root
now = time.strftime("%Y-%m-%d %H:%M:%S")
if session_id:
data["claude_session_id"] = session_id
data["session_id"] = self.session_id
try:
data["cq_project_id"] = compute_cq_project_id(work_dir)
except Exception:
data["cq_project_id"] = data.get("cq_project_id")
data["work_dir"] = str(work_dir)
data["work_dir_norm"] = _normalize_path_for_match(str(work_dir))
data["start_dir"] = str(self.invocation_dir)
data["terminal"] = terminal or self.terminal_type
data["active"] = bool(active)
data["started_at"] = data.get("started_at") or now
data["updated_at"] = now
if pane_id:
data["pane_id"] = pane_id
if pane_title_marker:
data["pane_title_marker"] = pane_title_marker
payload = json.dumps(data, ensure_ascii=False, indent=2)
ok, err = safe_write_session(path, payload)
if not ok:
print(err, file=sys.stderr)
return
if pane_id:
try:
upsert_registry(
{
"cq_session_id": self.session_id,
"cq_session_name": self.cq_session_name,
"cq_project_id": compute_cq_project_id(self.project_root),
"work_dir": str(self.project_root),
"terminal": terminal or self.terminal_type,
"providers": {
"claude": {
"pane_id": pane_id,
"pane_title_marker": pane_title_marker,
"session_file": str(path),
"claude_session_id": data.get("claude_session_id"),
"claude_session_path": data.get("claude_session_path"),
}
},
}
)
except Exception:
pass
def _get_latest_codex_session_id(self) -> tuple[str | None, bool]:
"""
Returns (session_id, has_any_history_for_cwd).
Session id is Codex CLI's UUID used by `codex resume <id>`.
Always scans session logs to find the latest session for current cwd,
then updates local .codex-session file.
"""
# Always scan logs to find the latest session - don't use cached session file
# as it may be stale (user may have started new sessions since last run).
project_session = self._project_session_file(".codex-session")
# Always scan Codex session logs for the latest session bound to this cwd.
# This ensures we get the latest session even if user did /clear during run.
root = Path(os.environ.get("CODEX_SESSION_ROOT") or (Path.home() / ".codex" / "sessions")).expanduser()
if not root.exists():
return None, False
root_norm = _normalize_path_for_match(str(self.project_root))
if not root_norm:
return None, False
try:
logs = sorted(
(p for p in root.glob("**/*.jsonl") if p.is_file()),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
except Exception:
logs = []
scan_limit = 400
raw_limit = (os.environ.get("CQ_CODEX_SCAN_LIMIT") or "").strip()
if raw_limit:
try:
scan_limit = max(100, min(20000, int(raw_limit)))
except Exception:
scan_limit = 400
for log_path in logs[:scan_limit]:
try:
with log_path.open("r", encoding="utf-8", errors="ignore") as handle:
head = [handle.readline().strip() for _ in range(30)]
except OSError:
continue
for line in head:
if not line:
continue
try:
entry = json.loads(line)
except Exception:
continue
if not isinstance(entry, dict) or entry.get("type") != "session_meta":
continue
payload = entry.get("payload") if isinstance(entry.get("payload"), dict) else {}
cwd = payload.get("cwd")
if not isinstance(cwd, str) or not cwd.strip():
continue
cwd_norm = _normalize_path_for_match(cwd)
# Accept sessions launched from any directory under the same project root.