forked from bfly123/claude_code_bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccb
More file actions
executable file
·4897 lines (4312 loc) · 189 KB
/
ccb
File metadata and controls
executable file
·4897 lines (4312 loc) · 189 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
"""
ccb (Claude Code Bridge) - Unified AI Launcher
Supports Claude + Codex / Claude + Gemini / all three simultaneously
Supports tmux and 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
import threading
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, is_wsl, get_shell_type, get_backend_for_session
from compat import setup_windows_encoding
from ccb_config import get_backend_env
from ccb_start_config import DEFAULT_PROVIDERS, ensure_default_start_config, load_start_config
from session_utils import (
check_session_writable,
find_project_session_file,
legacy_project_config_dir,
project_config_dir,
resolve_project_config_dir,
safe_write_session,
)
from pane_registry import upsert_registry, load_registry_by_project_id
from project_id import compute_ccb_project_id
from providers import CASK_CLIENT_SPEC, GASK_CLIENT_SPEC, OASK_CLIENT_SPEC, LASK_CLIENT_SPEC, DASK_CLIENT_SPEC
from process_lock import ProviderLock
from askd_rpc import shutdown_daemon, read_state
from askd_runtime import state_file_path
from i18n import t
setup_windows_encoding()
backend_env = get_backend_env()
if backend_env and not os.environ.get("CCB_BACKEND_ENV"):
os.environ["CCB_BACKEND_ENV"] = backend_env
VERSION = "5.2.8"
GIT_COMMIT = "c539e79"
GIT_DATE = "2026-02-25"
_WIN_DRIVE_RE = re.compile(r"^[A-Za-z]:([/\\\\]|$)")
_MNT_DRIVE_RE = re.compile(r"^/mnt/([A-Za-z])/(.*)$")
_MSYS_DRIVE_RE = re.compile(r"^/([A-Za-z])/(.*)$")
def _looks_like_windows_path(value: str) -> bool:
s = value.strip()
if not s:
return False
if _WIN_DRIVE_RE.match(s):
return True
if s.startswith("\\\\") or s.startswith("//"):
return True
return False
def _normalize_path_for_match(value: str) -> str:
"""
Normalize a path-like string for loose matching across Windows/WSL/MSYS variations.
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
# If the path is relative, absolutize it against current cwd for matching purposes only.
# This reduces false negatives when upstream tools record a relative cwd.
# NOTE: treat Windows-like absolute paths as absolute even on non-Windows hosts.
try:
preview = s.replace("\\", "/")
is_abs = (
preview.startswith("/")
or preview.startswith("//")
or bool(_WIN_DRIVE_RE.match(preview))
or preview.startswith("\\\\")
)
if not is_abs:
s = str((Path.cwd() / Path(s)).absolute())
except Exception:
pass
s = s.replace("\\", "/")
# Map WSL drive mount to Windows-style drive path for comparison.
m = _MNT_DRIVE_RE.match(s)
if m:
drive = m.group(1).lower()
rest = m.group(2)
s = f"{drive}:/{rest}"
else:
# Map MSYS /c/... to c:/... (Git-Bash/MSYS2 environments on Windows).
m = _MSYS_DRIVE_RE.match(s)
if m and ("MSYSTEM" in os.environ or os.name == "nt"):
drive = m.group(1).lower()
rest = m.group(2)
s = f"{drive}:/{rest}"
# Collapse redundant separators and dot segments using POSIX semantics (we forced "/").
# Preserve UNC double-slash prefix.
if s.startswith("//"):
prefix = "//"
rest = s[2:]
rest = posixpath.normpath(rest)
s = prefix + rest.lstrip("/")
else:
s = posixpath.normpath(s)
# Normalize Windows drive letter casing (c:/..., not C:/...).
if _WIN_DRIVE_RE.match(s):
s = s[0].lower() + s[1:]
# Drop trailing slash (but keep "/" and "c:/").
if len(s) > 1 and s.endswith("/"):
s = s.rstrip("/")
if _WIN_DRIVE_RE.match(s) and not s.endswith("/"):
# Ensure drive root keeps trailing slash form "c:/".
if len(s) == 2:
s = s + "/"
# On Windows-like paths, compare case-insensitively to avoid drive letter/case issues.
if _looks_like_windows_path(s):
s = s.casefold()
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:
if get_shell_type() == "powershell":
return (
f'{start_cmd}; '
f'$code = $LASTEXITCODE; '
f'Write-Host "`n[{provider}] exited with code $code. Press Enter to close..."; '
f'Read-Host; '
f'exit $code'
)
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:
if get_shell_type() == "powershell":
safe_sq = marker.replace("'", "''")
safe_dq = marker.replace('"', '`"')
return (
"$esc=[char]27; "
f"[Console]::Write(\"$esc]0;{safe_dq}`a\"); "
f"$Host.UI.RawUI.WindowTitle = '{safe_sq}'; "
)
return f"printf '\\033]0;{marker}\\007'; "
def _build_export_path_cmd(bin_dir: Path) -> str:
"""
Ensure CCB's `bin/` is available inside the started pane/session.
This allows running `oask`/`gask` from within Codex/Gemini/OpenCode environments consistently
across WezTerm/tmux (and PowerShell shells on Windows).
"""
bin_s = str(bin_dir)
if get_shell_type() == "powershell":
safe = bin_s.replace("'", "''")
# Prefer a fully materialized PATH to avoid cases where the spawned shell inherits a stale
# PATH (e.g. tmux server started before Homebrew paths were available).
current = (os.environ.get("PATH") or "").replace("'", "''")
if current:
return f"$env:Path = '{safe};{current}'; "
return f"$env:Path = '{safe};' + $env:Path; "
# Materialize PATH from the current CCB 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:
if get_shell_type() == "powershell":
safe = str(work_dir).replace("'", "''")
return f"Set-Location -Path '{safe}'; "
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 `CCB_TMPCLAUDE_MIN_AGE_S`.
Controls:
- `CCB_TMPCLAUDE_CLEAN` (default: true)
- `CCB_TMPCLAUDE_CLEAN_CWD` (default: true)
- `CCB_TMPCLAUDE_MIN_AGE_S` (default: 300)
- `CCB_TMPCLAUDE_DIRS` (extra dirs, split by `os.pathsep`)
- `CCB_TMPCLAUDE_PATTERNS` (comma-separated globs; default: tmpclaude-*-cwd)
"""
if not _env_bool("CCB_TMPCLAUDE_CLEAN", True):
return 0
patterns_raw = (os.environ.get("CCB_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("CCB_TMPCLAUDE_MIN_AGE_S", 300.0)))
dirs: list[Path] = []
if _env_bool("CCB_TMPCLAUDE_CLEAN_CWD", True):
dirs.append(Path.cwd())
try:
dirs.append(Path(tempfile.gettempdir()))
except Exception:
pass
extra = (os.environ.get("CCB_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
if os.name == "nt":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
SYNCHRONIZE = 0x00100000
handle = kernel32.OpenProcess(SYNCHRONIZE, False, int(pid))
if handle:
kernel32.CloseHandle(handle)
return True
return False
except Exception:
return True
try:
os.kill(int(pid), 0)
return True
except ProcessLookupError:
# Process doesn't exist
return False
except PermissionError:
# Process exists but no permission to check
return True
except Exception:
# Other errors - assume dead for safety
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 CCB 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("CCB_RUNTIME_GC", True):
return 0
min_age_s = max(0.0, float(_env_float("CCB_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
def _shrink_ccb_logs() -> int:
"""
Best-effort log slimming for daemon logs to avoid disk bloat.
- Current daemons log under `~/.cache/ccb` (or `$XDG_CACHE_HOME/ccb`).
- Older installs may have left logs under `~/.ccb/run`.
"""
if not _env_bool("CCB_LOG_SHRINK", True):
return 0
try:
max_bytes = max(0, int(_env_float("CCB_LOG_MAX_BYTES", 2 * 1024 * 1024)))
except Exception:
max_bytes = 2 * 1024 * 1024
if max_bytes <= 0:
return 0
# Cache directory (matches lib/askd_runtime.py defaults)
cache_dir: Path | None = None
xdg_cache = (os.environ.get("XDG_CACHE_HOME") or "").strip()
if xdg_cache:
cache_dir = Path(xdg_cache) / "ccb"
else:
cache_dir = Path.home() / ".cache" / "ccb"
legacy_dir = Path.home() / ".ccb" / "run"
def _shrink_file(path: Path) -> bool:
try:
if not path.exists() or not path.is_file():
return False
size = path.stat().st_size
if size <= max_bytes:
return False
with path.open("rb") as handle:
handle.seek(-max_bytes, os.SEEK_END)
tail = handle.read()
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_bytes(tail)
os.replace(tmp, path)
return True
except Exception:
try:
tmp = path.with_suffix(path.suffix + ".tmp")
if tmp.exists():
tmp.unlink()
except Exception:
pass
return False
removed = 0
for base in (cache_dir, legacy_dir):
try:
if not base.exists() or not base.is_dir():
continue
except Exception:
continue
try:
for log_file in base.glob("*.log"):
if _shrink_file(log_file):
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,
):
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()
# 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.ccb_pid = os.getpid()
self.project_id = compute_ccb_project_id(self.project_root)
project_hash = (self.project_id or "")[:16] or "unknown"
self.project_run_dir = (Path.home() / ".cache" / "ccb" / "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._askd_checked = False
self._watchdog_thread = None
self._watchdog_stop_event = None
self._daemon_proc = None # Track daemon Popen object for reaping
self._daemon_proc_lock = threading.Lock() # Protect daemon_proc access
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["CCB_MANAGED"] = "1"
os.environ["CCB_PARENT_PID"] = str(self.ccb_pid)
os.environ.setdefault("CCB_RUN_DIR", str(self.project_run_dir))
def _managed_env_overrides(self) -> dict:
env = {
"CCB_MANAGED": "1",
"CCB_PARENT_PID": str(self.ccb_pid),
}
if os.environ.get("CCB_RUN_DIR"):
env["CCB_RUN_DIR"] = os.environ["CCB_RUN_DIR"]
return env
def _provider_env_overrides(self, provider: str) -> dict:
"""Managed env + explicit caller marker for the pane/provider process."""
env = self._managed_env_overrides()
prov = (provider or "").strip().lower()
if prov in {"claude", "codex", "gemini", "opencode", "droid", "email", "manual"}:
env["CCB_CALLER"] = prov
return env
def _project_config_dir(self) -> Path:
return resolve_project_config_dir(self.project_root)
def _project_session_file(self, filename: str) -> Path:
cfg = self._project_config_dir()
return cfg / filename
def _migrate_legacy_project_files(self) -> None:
"""
Move legacy project dotfiles from the project root into the project config dir
(`.ccb/` or legacy `.ccb_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", ".gemini-session", ".opencode-session", ".claude-session", ".droid-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 `.ccb/` 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 "CCB-Cmd"
return {
"enabled": bool(enabled),
"start_cmd": str(start_cmd).strip(),
"title": str(title).strip() or "CCB-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 "CCB-Cmd").strip() or "CCB-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:
if get_shell_type() == "powershell":
return "pwsh" if shutil.which("pwsh") else "powershell"
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 ""
if get_shell_type() == "powershell":
parts: list[str] = []
for key, val in env.items():
if val is None:
continue
safe = str(val).replace("'", "''")
parts.append(f"$env:{key} = '{safe}'; ")
return "".join(parts)
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 _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 = f"CCB-{provider.capitalize()}"
backend.set_pane_title(pane_id, title)
backend.set_pane_user_option(pane_id, "@ccb_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)
if get_shell_type() == "powershell":
shell = "pwsh" if shutil.which("pwsh") else "powershell"
return subprocess.run([shell, "-Command", cmd], env=env, cwd=cwd).returncode
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 _maybe_start_caskd(self) -> None:
self._maybe_start_provider_daemon("codex")
def _maybe_start_unified_askd(self, *, quiet: bool = False) -> None:
"""Start unified askd daemon (provider-agnostic)."""
# Try to start for any enabled provider that uses askd (including claude)
for provider in ["codex", "gemini", "opencode", "droid", "claude"]:
if provider in [p.lower() for p in self.providers]:
# Try to start and check if successful
self._maybe_start_provider_daemon(provider, quiet=quiet)
# Verify daemon actually started by pinging
try:
from askd_runtime import state_file_path
from askd.daemon import ping_daemon
state_file = state_file_path("askd.json")
if ping_daemon(timeout_s=0.5, state_file=state_file):
return # Successfully started
except Exception:
pass
# If not successful, continue to next provider
def _maybe_start_provider_daemon(self, provider: str, *, quiet: bool = False) -> None:
def _bool_from_env(name: str):
raw = os.environ.get(name)
if raw is None or raw == "":
return None
v = raw.strip().lower()
if v in {"0", "false", "no", "off"}:
return False
if v in {"1", "true", "yes", "on"}:
return True
return None
def _emit(msg: str, *, err: bool = False) -> None:
if quiet and not _env_bool("CCB_DEBUG", False):
return
print(msg, file=sys.stderr if err else sys.stdout)
provider = (provider or "").strip().lower()
specs = {
"codex": CASK_CLIENT_SPEC,
"gemini": GASK_CLIENT_SPEC,
"opencode": OASK_CLIENT_SPEC,
"claude": LASK_CLIENT_SPEC,
"droid": DASK_CLIENT_SPEC,
}
spec = specs.get(provider)
if not spec:
return
if provider not in [p.lower() for p in self.providers]:
return
autostart = _bool_from_env(spec.autostart_env_primary)
if autostart is None:
autostart = _bool_from_env(spec.autostart_env_legacy)
if autostart is False:
return
if _bool_from_env(spec.enabled_env) is False:
return
try:
from importlib import import_module
daemon_module = import_module(spec.daemon_module)
ping_daemon = getattr(daemon_module, "ping_daemon")
read_state = getattr(daemon_module, "read_state", None)
shutdown_daemon_fn = getattr(daemon_module, "shutdown_daemon", None)
except Exception as exc:
_emit(f"⚠️ Failed to import {spec.daemon_module}: {exc}")
return
def _owned_by_ccb(state: dict | None) -> bool:
if not isinstance(state, dict):
return False
try:
parent_pid = int(state.get("parent_pid") or 0)
except Exception:
parent_pid = 0
managed = bool(state.get("managed"))
return managed and parent_pid == self.ccb_pid
state_file = None
raw_state_file = (os.environ.get(spec.state_file_env) or "").strip()
if raw_state_file:
try:
state_file = Path(raw_state_file).expanduser()
except Exception:
state_file = None
if ping_daemon(state_file=state_file):
st = read_state(state_file=state_file) or {} if callable(read_state) else {}
if spec.daemon_bin_name == "askd" and not self._askd_checked:
self._askd_checked = True
if not _owned_by_ccb(st):
# Check if forced rebind is enabled (case-insensitive)
force_rebind = _env_bool("CCB_FORCE_REBIND", False)
# Check if foreign parent is still alive before forcing rebind
# Safely normalize parent_pid to int (handle None, non-int, etc.)
try:
foreign_parent_pid = int((st or {}).get("parent_pid") or 0)
except Exception:
foreign_parent_pid = 0
foreign_parent_alive = False
if not force_rebind and foreign_parent_pid > 0:
try:
foreign_parent_alive = _is_pid_alive(foreign_parent_pid)
except Exception:
foreign_parent_alive = False
if force_rebind or not foreign_parent_alive:
# Safe to rebind: either forced or foreign parent is dead/stale
if force_rebind:
_emit(f"⚠️ CCB_FORCE_REBIND=1 set, forcing askd rebind despite live parent (PID {foreign_parent_pid})...")
else:
_emit(f"⚠️ askd owned by dead parent (PID {foreign_parent_pid}), restarting to bind lifecycle...")
if callable(shutdown_daemon_fn):
try:
shutdown_daemon_fn(timeout_s=1.0, state_file=state_file)
except Exception:
pass
else:
# Foreign parent is still alive, don't force rebind
_emit(f"⚠️ askd owned by live parent (PID {foreign_parent_pid}), skipping rebind to avoid disruption")
_emit(f" Set CCB_FORCE_REBIND=1 to override this safety check")
host = st.get("host") if isinstance(st, dict) else None
port = st.get("port") if isinstance(st, dict) else None
if host and port:
_emit(f"✅ {spec.daemon_bin_name} already running at {host}:{port}")
else:
_emit(f"✅ {spec.daemon_bin_name} already running")
return
deadline = time.time() + 2.0
while time.time() < deadline:
if not ping_daemon(timeout_s=0.2, state_file=state_file):
break
time.sleep(0.1)
if ping_daemon(timeout_s=0.2, state_file=state_file):
_emit("⚠️ askd restart skipped: existing daemon still running")
host = st.get("host") if isinstance(st, dict) else None
port = st.get("port") if isinstance(st, dict) else None
if host and port:
_emit(f"✅ {spec.daemon_bin_name} already running at {host}:{port}")
else:
_emit(f"✅ {spec.daemon_bin_name} already running")
return
else:
host = st.get("host") if isinstance(st, dict) else None
port = st.get("port") if isinstance(st, dict) else None
if host and port:
_emit(f"✅ {spec.daemon_bin_name} already running at {host}:{port}")
else:
_emit(f"✅ {spec.daemon_bin_name} already running")
return
else:
host = st.get("host") if isinstance(st, dict) else None
port = st.get("port") if isinstance(st, dict) else None
if host and port:
_emit(f"✅ {spec.daemon_bin_name} already running at {host}:{port}")
else:
_emit(f"✅ {spec.daemon_bin_name} already running")
return
daemon_script = self.script_dir / "bin" / spec.daemon_bin_name
if not daemon_script.exists():
_emit(f"⚠️ {spec.daemon_bin_name} not found (bin/{spec.daemon_bin_name}). Reinstall or update your checkout.")
return
kwargs = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
"close_fds": True,
}
if os.name == "nt":
kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) | getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
else:
kwargs["start_new_session"] = True
try:
env = os.environ.copy()
env["CCB_PARENT_PID"] = str(os.getpid())
proc = subprocess.Popen([sys.executable, str(daemon_script)], env=env, **kwargs)
# Track daemon process for reaping (thread-safe)
if spec.daemon_bin_name == "askd":
with self._daemon_proc_lock:
self._daemon_proc = proc
except Exception as exc:
_emit(f"⚠️ Failed to start {spec.daemon_bin_name}: {exc}")
return
deadline = time.time() + 2.0
while time.time() < deadline:
if ping_daemon(timeout_s=0.2, state_file=state_file):
st = read_state(state_file=state_file) or {} if callable(read_state) else {}
host = st.get("host") if isinstance(st, dict) else None
port = st.get("port") if isinstance(st, dict) else None
if host and port:
_emit(f"✅ {spec.daemon_bin_name} started at {host}:{port}")
else:
_emit(f"✅ {spec.daemon_bin_name} started")
return
time.sleep(0.1)
_emit(f"⚠️ {spec.daemon_bin_name} start requested, but daemon not reachable yet")
def _start_daemon_watchdog(self) -> None:
"""Start watchdog thread to monitor askd daemon health."""
import threading
# Restart if thread exists but is dead
if self._watchdog_thread is not None:
if not self._watchdog_thread.is_alive():
self._watchdog_thread = None
self._watchdog_stop_event = None
else:
return # Already running
self._watchdog_stop_event = threading.Event()
self._watchdog_thread = threading.Thread(
target=self._daemon_watchdog_loop,
daemon=True,
name="askd-watchdog"
)
self._watchdog_thread.start()
def _daemon_watchdog_loop(self) -> None:
"""Watchdog loop to monitor and restart askd daemon if needed."""
from askd_runtime import state_file_path
from askd.daemon import ping_daemon, read_state
verbose_watchdog = _env_bool("CCB_WATCHDOG_VERBOSE", False) or _env_bool("CCB_DEBUG", False)
def _wd_log(msg: str) -> None:
if verbose_watchdog:
print(msg, file=sys.stderr)
# Validate and clamp check interval
try:
check_interval = float(os.environ.get("CCB_WATCHDOG_INTERVAL_S", "10"))
check_interval = max(1.0, min(check_interval, 300.0)) # Clamp to 1-300 seconds
except (ValueError, TypeError):
check_interval = 10.0
consecutive_failures = 0