code-context-control 2.158.5__py3-none-any.whl → 2.159.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli/_hook_utils.py +7 -4
- cli/c3.py +6 -1
- cli/hook_dispatch.py +71 -16
- cli/hook_edit_ledger.py +62 -33
- cli/hub_server.py +41 -17
- cli/mcp_server.py +5 -0
- cli/tools/delegate.py +67 -4
- cli/tools/shell.py +4 -3
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/METADATA +1 -1
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/RECORD +28 -25
- core/blas_threads.py +33 -0
- oracle/mcp_oracle.py +27 -1
- oracle/services/mobile_api.py +63 -6
- services/access_guard.py +132 -18
- services/activity_log.py +57 -43
- services/atomic_json.py +8 -4
- services/builtin_leases.py +4 -3
- services/edit_ledger.py +183 -50
- services/file_memo.py +50 -0
- services/file_memory.py +70 -9
- services/keyring_read.py +222 -0
- services/retention.py +15 -1
- services/task_store.py +13 -6
- services/validation_cache.py +10 -7
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/WHEEL +0 -0
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/entry_points.txt +0 -0
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/licenses/LICENSE +0 -0
- {code_context_control-2.158.5.dist-info → code_context_control-2.159.1.dist-info}/top_level.txt +0 -0
cli/_hook_utils.py
CHANGED
|
@@ -10,7 +10,6 @@ import os
|
|
|
10
10
|
import re
|
|
11
11
|
import shlex
|
|
12
12
|
import sys
|
|
13
|
-
import traceback
|
|
14
13
|
from datetime import datetime, timezone
|
|
15
14
|
from pathlib import Path
|
|
16
15
|
|
|
@@ -96,6 +95,7 @@ def log_hook_error(hook_name: str, exc: BaseException) -> None:
|
|
|
96
95
|
except Exception:
|
|
97
96
|
pass
|
|
98
97
|
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
98
|
+
import traceback # noqa: PLC0415 — ~7 ms; only a failing hook pays it
|
|
99
99
|
tb = traceback.format_exc().strip()
|
|
100
100
|
line = f"[{ts}] [{hook_name}] {type(exc).__name__}: {exc}\n{tb}\n---\n"
|
|
101
101
|
with open(log_file, "a", encoding="utf-8") as f:
|
|
@@ -411,9 +411,12 @@ def detect_host(data: dict, explicit_host: str | None = None) -> str:
|
|
|
411
411
|
return aliases[named]
|
|
412
412
|
if not isinstance(data, dict):
|
|
413
413
|
return HOST_CLAUDE
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
414
|
+
# Grok's envelope is the only one with camelCase hookEventName; checking
|
|
415
|
+
# for it first spares every other host the ~5 ms import of `core`.
|
|
416
|
+
if "hookEventName" in data:
|
|
417
|
+
from core.grok_payload import is_grok_payload
|
|
418
|
+
if is_grok_payload(data):
|
|
419
|
+
return HOST_GROK
|
|
417
420
|
if data.get("turn_id"):
|
|
418
421
|
return HOST_CODEX
|
|
419
422
|
response = data.get("tool_response")
|
cli/c3.py
CHANGED
|
@@ -45,6 +45,11 @@ from pathlib import Path
|
|
|
45
45
|
# Add parent to path for imports
|
|
46
46
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
47
47
|
|
|
48
|
+
# Before anything can import numpy: `c3 ui` builds a full runtime.
|
|
49
|
+
from core import blas_threads # noqa: E402
|
|
50
|
+
|
|
51
|
+
blas_threads.limit()
|
|
52
|
+
|
|
48
53
|
from cli.commands.common import CommandDeps
|
|
49
54
|
from cli.commands.common import cmd_claudemd as common_cmd_claudemd
|
|
50
55
|
from cli.commands.common import cmd_compress as common_cmd_compress
|
|
@@ -91,7 +96,7 @@ console = Console() if HAS_RICH else None
|
|
|
91
96
|
# Config
|
|
92
97
|
CONFIG_DIR = ".c3"
|
|
93
98
|
CONFIG_FILE = ".c3/config.json"
|
|
94
|
-
__version__ = "2.
|
|
99
|
+
__version__ = "2.159.1"
|
|
95
100
|
|
|
96
101
|
# The PreToolUse matcher for native subagent calls (installer and hub migration).
|
|
97
102
|
AGENT_MATCHER = "Agent|Task"
|
cli/hook_dispatch.py
CHANGED
|
@@ -36,7 +36,6 @@ emit a short "[c3:hook-error] ..." additionalContext warning so enforcement
|
|
|
36
36
|
cannot silently stop enforcing.
|
|
37
37
|
"""
|
|
38
38
|
import importlib
|
|
39
|
-
import inspect
|
|
40
39
|
import json
|
|
41
40
|
import sys
|
|
42
41
|
from pathlib import Path
|
|
@@ -239,15 +238,31 @@ def _call_run(run_fn, module_name: str, event: str, payload: dict,
|
|
|
239
238
|
two-argument lambdas, and a legacy single-file hook must keep working.
|
|
240
239
|
"""
|
|
241
240
|
if event == "pretool" and module_name in _DEFER_CONSUME:
|
|
242
|
-
|
|
243
|
-
accepts = "defer_consume" in inspect.signature(run_fn).parameters
|
|
244
|
-
except (TypeError, ValueError):
|
|
245
|
-
accepts = False
|
|
246
|
-
if accepts:
|
|
241
|
+
if _takes_param(run_fn, "defer_consume"):
|
|
247
242
|
return run_fn(payload, project_path, defer_consume=True)
|
|
248
243
|
return run_fn(payload, project_path)
|
|
249
244
|
|
|
250
245
|
|
|
246
|
+
def _takes_param(fn, name: str) -> bool:
|
|
247
|
+
"""True when *fn* declares a parameter called *name*.
|
|
248
|
+
|
|
249
|
+
A plain function answers from its code object. ``inspect`` costs every
|
|
250
|
+
hook process about 7 ms to import, and this check runs on every
|
|
251
|
+
PreToolUse, so it is only imported for other callables (partials,
|
|
252
|
+
callable objects, and decorated functions, whose wrapper's code would
|
|
253
|
+
hide the signature ``inspect`` follows ``__wrapped__`` to).
|
|
254
|
+
"""
|
|
255
|
+
code = getattr(fn, "__code__", None)
|
|
256
|
+
if code is not None and not hasattr(fn, "__wrapped__"):
|
|
257
|
+
n_params = code.co_argcount + code.co_kwonlyargcount
|
|
258
|
+
return name in code.co_varnames[:n_params]
|
|
259
|
+
import inspect # noqa: PLC0415 — rare path, see above
|
|
260
|
+
try:
|
|
261
|
+
return name in inspect.signature(fn).parameters
|
|
262
|
+
except (TypeError, ValueError):
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
|
|
251
266
|
def _grant_lost_deny() -> dict:
|
|
252
267
|
return {
|
|
253
268
|
"hookSpecificOutput": {
|
|
@@ -561,17 +576,57 @@ def dispatch(event: str, payload: dict, project_path: Path | None = None) -> dic
|
|
|
561
576
|
return merge_outputs(outputs, warnings, event=event, host=host)
|
|
562
577
|
|
|
563
578
|
|
|
579
|
+
_HOSTS = ("codex", "claude", "claude-code", "gemini", "grok")
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _parse_args(argv: list) -> tuple:
|
|
583
|
+
"""``(event, host, project)`` as main()'s argparse parser reads *argv*.
|
|
584
|
+
|
|
585
|
+
Hook commands are written as an event plus ``--host NAME`` or
|
|
586
|
+
``--project PATH`` (either also as ``--opt=value``), and those shapes are
|
|
587
|
+
read here: argparse costs every hook process about 18 ms on Python 3.14,
|
|
588
|
+
because each add_argument builds a help formatter, which imports shutil
|
|
589
|
+
and _colorize. Anything else (help, an abbreviation, an unknown or
|
|
590
|
+
invalid argument) goes to argparse, which answers or exits as before.
|
|
591
|
+
"""
|
|
592
|
+
event, opts = None, {"--host": None, "--project": None}
|
|
593
|
+
i = 0
|
|
594
|
+
while i < len(argv):
|
|
595
|
+
tok = argv[i]
|
|
596
|
+
name, eq, value = tok.partition("=")
|
|
597
|
+
if name in opts:
|
|
598
|
+
if not eq:
|
|
599
|
+
if i + 1 >= len(argv) or argv[i + 1].startswith("-"):
|
|
600
|
+
return _parse_args_slow(argv)
|
|
601
|
+
i += 1
|
|
602
|
+
value = argv[i]
|
|
603
|
+
opts[name] = value
|
|
604
|
+
elif event is None and not tok.startswith("-"):
|
|
605
|
+
event = tok
|
|
606
|
+
else:
|
|
607
|
+
return _parse_args_slow(argv)
|
|
608
|
+
i += 1
|
|
609
|
+
if opts["--host"] is not None and opts["--host"] not in _HOSTS:
|
|
610
|
+
return _parse_args_slow(argv)
|
|
611
|
+
return event or "", opts["--host"], opts["--project"]
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _parse_args_slow(argv: list) -> tuple:
|
|
615
|
+
import argparse # noqa: PLC0415 — see _parse_args
|
|
616
|
+
parser = argparse.ArgumentParser()
|
|
617
|
+
parser.add_argument("event", nargs="?", default="")
|
|
618
|
+
parser.add_argument("--host", choices=list(_HOSTS))
|
|
619
|
+
parser.add_argument("--project")
|
|
620
|
+
args = parser.parse_args(argv)
|
|
621
|
+
return args.event, args.host, args.project
|
|
622
|
+
|
|
623
|
+
|
|
564
624
|
def main() -> None:
|
|
565
625
|
# Windows hook subprocesses get cp1252 pipes; sub-hook _text may carry
|
|
566
626
|
# box-drawing chars / emoji, so print(text) below would UnicodeEncodeError.
|
|
567
627
|
_hook_utils.ensure_utf8_stdio()
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
parser.add_argument("event", nargs="?", default="")
|
|
571
|
-
parser.add_argument("--host", choices=["codex", "claude", "claude-code", "gemini", "grok"])
|
|
572
|
-
parser.add_argument("--project")
|
|
573
|
-
args = parser.parse_args()
|
|
574
|
-
event = args.event.strip().lower()
|
|
628
|
+
event, host, project = _parse_args(sys.argv[1:])
|
|
629
|
+
event = event.strip().lower()
|
|
575
630
|
if event not in (*VALID_EVENTS, "start", "compact", "end"):
|
|
576
631
|
log_hook_error(
|
|
577
632
|
"hook_dispatch",
|
|
@@ -592,9 +647,9 @@ def main() -> None:
|
|
|
592
647
|
return
|
|
593
648
|
|
|
594
649
|
try:
|
|
595
|
-
if
|
|
596
|
-
payload["_c3_host"] =
|
|
597
|
-
output = dispatch(event, payload, Path(
|
|
650
|
+
if host:
|
|
651
|
+
payload["_c3_host"] = host
|
|
652
|
+
output = dispatch(event, payload, Path(project).resolve() if project else None)
|
|
598
653
|
except Exception as exc:
|
|
599
654
|
# The dispatcher itself failing is critical — say so. Route the notice
|
|
600
655
|
# through merge_outputs so even the panic path speaks the host's
|
cli/hook_edit_ledger.py
CHANGED
|
@@ -36,57 +36,86 @@ EDITABLE_EXTS = {
|
|
|
36
36
|
|
|
37
37
|
# How many tail lines to scan for version/seq (avoids full-file parse)
|
|
38
38
|
_TAIL_SCAN = 50
|
|
39
|
+
# Bytes read per step when walking the ledger backwards from its end
|
|
40
|
+
_TAIL_CHUNK = 64 * 1024
|
|
39
41
|
|
|
40
42
|
|
|
41
43
|
def _tail_lines(ledger_file: Path, n: int = _TAIL_SCAN) -> list[str]:
|
|
42
|
-
"""
|
|
44
|
+
"""The last n non-empty lines of the ledger, oldest first.
|
|
45
|
+
|
|
46
|
+
Reads backwards from the end, so the cost follows n rather than the
|
|
47
|
+
ledger's size (it runs twice per edit, and ledgers reach megabytes).
|
|
48
|
+
"""
|
|
49
|
+
lines = []
|
|
43
50
|
try:
|
|
44
|
-
|
|
45
|
-
|
|
51
|
+
with open(ledger_file, "rb") as f:
|
|
52
|
+
pos = f.seek(0, 2)
|
|
53
|
+
partial = b""
|
|
54
|
+
while pos > 0 and len(lines) < n:
|
|
55
|
+
step = min(_TAIL_CHUNK, pos)
|
|
56
|
+
pos -= step
|
|
57
|
+
f.seek(pos)
|
|
58
|
+
parts = (f.read(step) + partial).split(b"\n")
|
|
59
|
+
# Unless the read reached the start, parts[0] may begin mid-line.
|
|
60
|
+
partial = parts.pop(0) if pos > 0 else b""
|
|
61
|
+
for raw in reversed(parts):
|
|
62
|
+
if raw.strip():
|
|
63
|
+
lines.append(raw.decode("utf-8", errors="replace"))
|
|
64
|
+
if len(lines) == n:
|
|
65
|
+
break
|
|
66
|
+
except OSError:
|
|
46
67
|
return []
|
|
47
|
-
lines = []
|
|
48
|
-
pos = len(raw)
|
|
49
|
-
while pos > 0 and len(lines) < n:
|
|
50
|
-
nl = raw.rfind(b"\n", 0, pos - 1)
|
|
51
|
-
chunk = raw[nl + 1:pos]
|
|
52
|
-
if chunk.strip():
|
|
53
|
-
lines.append(chunk.decode("utf-8", errors="replace"))
|
|
54
|
-
pos = nl if nl >= 0 else 0
|
|
55
68
|
return list(reversed(lines))
|
|
56
69
|
|
|
57
70
|
|
|
58
|
-
def
|
|
59
|
-
"""
|
|
71
|
+
def _lines_naming(ledger_file: Path, rel_path: str) -> list[str]:
|
|
72
|
+
"""Every ledger line that contains rel_path as a JSON string, in file order.
|
|
73
|
+
|
|
74
|
+
A byte search finds the candidates, so only they get JSON-parsed. The
|
|
75
|
+
raw-UTF-8 form is searched too, for a writer that skipped ASCII escaping.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
raw = ledger_file.read_bytes()
|
|
79
|
+
except OSError:
|
|
80
|
+
return []
|
|
81
|
+
found = {}
|
|
82
|
+
for needle in {json.dumps(rel_path).encode("utf-8"),
|
|
83
|
+
json.dumps(rel_path, ensure_ascii=False).encode("utf-8")}:
|
|
84
|
+
pos = raw.find(needle)
|
|
85
|
+
while pos >= 0:
|
|
86
|
+
start = raw.rfind(b"\n", 0, pos) + 1
|
|
87
|
+
end = raw.find(b"\n", pos)
|
|
88
|
+
if end < 0:
|
|
89
|
+
end = len(raw)
|
|
90
|
+
found[start] = raw[start:end]
|
|
91
|
+
pos = raw.find(needle, end)
|
|
92
|
+
return [found[k].decode("utf-8", errors="replace") for k in sorted(found)]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _max_version(lines: list[str], rel_path: str) -> int:
|
|
96
|
+
"""Highest version number among the lines' entries for rel_path (0 if none)."""
|
|
60
97
|
max_v = 0
|
|
61
|
-
for line in
|
|
98
|
+
for line in lines:
|
|
62
99
|
try:
|
|
63
100
|
entry = json.loads(line)
|
|
64
101
|
except (json.JSONDecodeError, ValueError):
|
|
65
102
|
continue
|
|
66
|
-
if entry.get("file") == rel_path:
|
|
103
|
+
if isinstance(entry, dict) and entry.get("file") == rel_path:
|
|
67
104
|
v_str = entry.get("version", "v0")
|
|
68
105
|
try:
|
|
69
106
|
max_v = max(max_v, int(v_str.lstrip("v")))
|
|
70
107
|
except (ValueError, AttributeError):
|
|
71
108
|
pass
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if entry.get("file") == rel_path:
|
|
83
|
-
v_str = entry.get("version", "v0")
|
|
84
|
-
try:
|
|
85
|
-
max_v = max(max_v, int(v_str.lstrip("v")))
|
|
86
|
-
except (ValueError, AttributeError):
|
|
87
|
-
pass
|
|
88
|
-
except Exception:
|
|
89
|
-
pass
|
|
109
|
+
return max_v
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _next_version(ledger_file: Path, rel_path: str) -> str:
|
|
113
|
+
"""Get next version for a file by scanning only the tail of the ledger."""
|
|
114
|
+
max_v = _max_version(_tail_lines(ledger_file, _TAIL_SCAN), rel_path)
|
|
115
|
+
# If nothing found in tail, file might have older entries (or a rotation
|
|
116
|
+
# tombstone at the head). Parse only the lines that name it.
|
|
117
|
+
if max_v == 0:
|
|
118
|
+
max_v = _max_version(_lines_naming(ledger_file, rel_path), rel_path)
|
|
90
119
|
return f"v{max_v + 1}"
|
|
91
120
|
|
|
92
121
|
|
cli/hub_server.py
CHANGED
|
@@ -34,6 +34,7 @@ from core.ide import PROFILES, detect_ide, get_profile, load_ide_config, normali
|
|
|
34
34
|
from services import access_guard, fleet_overview
|
|
35
35
|
from services.activity_log import ActivityLog
|
|
36
36
|
from services.atomic_json import write_json_atomic
|
|
37
|
+
from services.file_memo import FileMemo
|
|
37
38
|
from services.project_manager import ProjectManager
|
|
38
39
|
from services.tool_classifier import CATEGORIES
|
|
39
40
|
|
|
@@ -531,27 +532,33 @@ def api_hub_config_set():
|
|
|
531
532
|
|
|
532
533
|
# ─── Routes: projects ────────────────────────────────────────────────────────
|
|
533
534
|
|
|
534
|
-
def
|
|
535
|
-
"""Count unacknowledged notifications for a project by reading its .c3/notifications.jsonl."""
|
|
536
|
-
nf = Path(project_path) / ".c3" / "notifications.jsonl"
|
|
537
|
-
if not nf.exists():
|
|
538
|
-
return 0
|
|
535
|
+
def _count_unacknowledged(nf) -> int:
|
|
539
536
|
count = 0
|
|
540
537
|
try:
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
538
|
+
with open(nf, encoding="utf-8", errors="replace") as fh:
|
|
539
|
+
for line in fh:
|
|
540
|
+
if not line.strip():
|
|
541
|
+
continue
|
|
542
|
+
try:
|
|
543
|
+
entry = json.loads(line)
|
|
544
|
+
if not entry.get("acknowledged"):
|
|
545
|
+
count += 1
|
|
546
|
+
except (json.JSONDecodeError, AttributeError):
|
|
547
|
+
continue
|
|
550
548
|
except OSError:
|
|
551
549
|
pass
|
|
552
550
|
return count
|
|
553
551
|
|
|
554
552
|
|
|
553
|
+
# /api/projects asks for every registered project on every poll.
|
|
554
|
+
_notification_counts = FileMemo(_count_unacknowledged)
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _notification_count(project_path: str) -> int:
|
|
558
|
+
"""Count unacknowledged notifications for a project by reading its .c3/notifications.jsonl."""
|
|
559
|
+
return _notification_counts.get(Path(project_path) / ".c3" / "notifications.jsonl")
|
|
560
|
+
|
|
561
|
+
|
|
555
562
|
_sub_links_cache = {"fp": None, "ts": 0.0, "data": None, "computing": False}
|
|
556
563
|
_sub_links_lock = threading.Lock()
|
|
557
564
|
_SUB_LINKS_TTL = 15.0
|
|
@@ -578,14 +585,31 @@ def _sub_federation_errors(sub):
|
|
|
578
585
|
return ""
|
|
579
586
|
|
|
580
587
|
|
|
588
|
+
_REALPATH_TTL_S = 30.0
|
|
589
|
+
_realpath_cache: dict = {}
|
|
590
|
+
|
|
591
|
+
|
|
581
592
|
def _norm_realpath(s):
|
|
582
593
|
"""resolve()+normcase, matching services.subprojects._norm — plain
|
|
583
594
|
normcase alone would flag symlinked/8.3/trailing-slash registry rows
|
|
584
|
-
as false orphans that Reconcile then denies.
|
|
595
|
+
as false orphans that Reconcile then denies.
|
|
596
|
+
|
|
597
|
+
Kept for _REALPATH_TTL_S: every /api/projects poll resolves each row's
|
|
598
|
+
path several times, and a resolve() costs a filesystem round trip.
|
|
599
|
+
"""
|
|
600
|
+
key = str(s or "")
|
|
601
|
+
now = time.monotonic()
|
|
602
|
+
hit = _realpath_cache.get(key)
|
|
603
|
+
if hit is not None and now < hit[0]:
|
|
604
|
+
return hit[1]
|
|
585
605
|
try:
|
|
586
|
-
|
|
606
|
+
value = os.path.normcase(str(Path(s).resolve()))
|
|
587
607
|
except Exception:
|
|
588
|
-
|
|
608
|
+
value = os.path.normcase(key)
|
|
609
|
+
if len(_realpath_cache) >= 1024:
|
|
610
|
+
_realpath_cache.clear()
|
|
611
|
+
_realpath_cache[key] = (now + _REALPATH_TTL_S, value)
|
|
612
|
+
return value
|
|
589
613
|
|
|
590
614
|
|
|
591
615
|
def _compute_subproject_links(projects):
|
cli/mcp_server.py
CHANGED
|
@@ -21,6 +21,11 @@ from typing import Any
|
|
|
21
21
|
# Add parent to path for imports
|
|
22
22
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
23
23
|
|
|
24
|
+
# Before anything can import numpy (lifespan imports it before the threads).
|
|
25
|
+
from core import blas_threads # noqa: E402
|
|
26
|
+
|
|
27
|
+
blas_threads.limit()
|
|
28
|
+
|
|
24
29
|
try:
|
|
25
30
|
from fastmcp import Context, FastMCP
|
|
26
31
|
except Exception:
|
cli/tools/delegate.py
CHANGED
|
@@ -177,6 +177,69 @@ def _probe_cli_version(exe: str, timeout: int = 10, args: list[str] | None = Non
|
|
|
177
177
|
pass
|
|
178
178
|
|
|
179
179
|
|
|
180
|
+
# Successful `<cli> --version` answers, kept per machine for a day and keyed by
|
|
181
|
+
# the executable's path, size and mtime, so an upgraded CLI is probed again.
|
|
182
|
+
# Every MCP server start runs check_gemini() and check_codex() in its prewarm
|
|
183
|
+
# thread, and `gemini --version` starts Node to answer: 1.1 s each time.
|
|
184
|
+
_VERSION_CACHE_TTL_S = 24 * 3600
|
|
185
|
+
_VERSION_CACHE_MAX = 32
|
|
186
|
+
_version_cache_lock = threading.Lock()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _version_cache_file() -> Path:
|
|
190
|
+
home = os.environ.get("C3_HOME") or os.path.expanduser("~")
|
|
191
|
+
return Path(home) / ".c3" / "cache" / "cli_versions.json"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _version_cache_fresh(hit, now: float) -> bool:
|
|
195
|
+
try:
|
|
196
|
+
return isinstance(hit.get("out"), str) and 0 <= now - float(hit["at"]) < _VERSION_CACHE_TTL_S
|
|
197
|
+
except (AttributeError, KeyError, TypeError, ValueError):
|
|
198
|
+
return False
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _read_version_cache(path: Path) -> dict:
|
|
202
|
+
try:
|
|
203
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
204
|
+
except (OSError, ValueError):
|
|
205
|
+
return {}
|
|
206
|
+
return data if isinstance(data, dict) else {}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _probe_cli_version_cached(exe: str, timeout: int = 10):
|
|
210
|
+
"""``_probe_cli_version(exe, timeout)``, answered from the cache when fresh.
|
|
211
|
+
|
|
212
|
+
Only exit-0 answers are stored, so a failure or a timeout is probed again
|
|
213
|
+
on the next call. An executable that cannot be stat'ed is never cached.
|
|
214
|
+
"""
|
|
215
|
+
try:
|
|
216
|
+
st = os.stat(exe)
|
|
217
|
+
key = f"{os.path.normcase(os.path.abspath(exe))}|{st.st_size}|{st.st_mtime_ns}"
|
|
218
|
+
except (OSError, TypeError, ValueError):
|
|
219
|
+
key = None
|
|
220
|
+
path = _version_cache_file()
|
|
221
|
+
if key:
|
|
222
|
+
hit = _read_version_cache(path).get(key)
|
|
223
|
+
if _version_cache_fresh(hit, time.time()):
|
|
224
|
+
return hit["out"], str(hit.get("err") or ""), 0
|
|
225
|
+
probed = _probe_cli_version(exe, timeout=timeout)
|
|
226
|
+
if key and probed is not None and probed[2] == 0:
|
|
227
|
+
with _version_cache_lock:
|
|
228
|
+
now = time.time()
|
|
229
|
+
data = {k: v for k, v in _read_version_cache(path).items()
|
|
230
|
+
if _version_cache_fresh(v, now)}
|
|
231
|
+
data[key] = {"out": probed[0], "err": probed[1], "at": now}
|
|
232
|
+
if len(data) > _VERSION_CACHE_MAX:
|
|
233
|
+
keep = sorted(data, key=lambda k: data[k]["at"])[-_VERSION_CACHE_MAX:]
|
|
234
|
+
data = {k: data[k] for k in keep}
|
|
235
|
+
try:
|
|
236
|
+
from services.atomic_json import write_json_atomic
|
|
237
|
+
write_json_atomic(path, data, fsync=False)
|
|
238
|
+
except Exception:
|
|
239
|
+
pass
|
|
240
|
+
return probed
|
|
241
|
+
|
|
242
|
+
|
|
180
243
|
# ---------------------------------------------------------------------------
|
|
181
244
|
# Codex CLI backend
|
|
182
245
|
# ---------------------------------------------------------------------------
|
|
@@ -263,7 +326,7 @@ def check_claude() -> dict:
|
|
|
263
326
|
_claude_available = False
|
|
264
327
|
return {"status": "not_installed", "detail": "claude CLI not found on PATH"}
|
|
265
328
|
try:
|
|
266
|
-
probed =
|
|
329
|
+
probed = _probe_cli_version_cached(exe, timeout=10)
|
|
267
330
|
if probed is None:
|
|
268
331
|
_claude_available = False
|
|
269
332
|
return {"status": "timeout", "detail": "claude --version timed out (10s)"}
|
|
@@ -1046,7 +1109,7 @@ def check_gemini() -> dict:
|
|
|
1046
1109
|
_gemini_available = False
|
|
1047
1110
|
return {"status": "not_installed", "detail": "gemini CLI not found on PATH"}
|
|
1048
1111
|
try:
|
|
1049
|
-
probed =
|
|
1112
|
+
probed = _probe_cli_version_cached(exe, timeout=10)
|
|
1050
1113
|
if probed is None:
|
|
1051
1114
|
_gemini_available = False
|
|
1052
1115
|
return {"status": "timeout", "detail": "gemini --version timed out (10s)"}
|
|
@@ -1301,7 +1364,7 @@ def check_codex() -> dict:
|
|
|
1301
1364
|
_codex_available = False
|
|
1302
1365
|
return {"status": "not_installed", "detail": "codex CLI not found on PATH"}
|
|
1303
1366
|
try:
|
|
1304
|
-
probed =
|
|
1367
|
+
probed = _probe_cli_version_cached(exe, timeout=10)
|
|
1305
1368
|
if probed is None:
|
|
1306
1369
|
_codex_available = False
|
|
1307
1370
|
return {"status": "timeout", "detail": "codex --version timed out (10s)"}
|
|
@@ -1508,7 +1571,7 @@ def check_grok() -> dict:
|
|
|
1508
1571
|
_grok_available = False
|
|
1509
1572
|
return {"status": "not_installed", "detail": "grok CLI not found on PATH"}
|
|
1510
1573
|
try:
|
|
1511
|
-
probed =
|
|
1574
|
+
probed = _probe_cli_version_cached(exe, timeout=10)
|
|
1512
1575
|
if probed is None:
|
|
1513
1576
|
_grok_available = False
|
|
1514
1577
|
return {"status": "timeout", "detail": "grok --version timed out (10s)"}
|
cli/tools/shell.py
CHANGED
|
@@ -49,7 +49,7 @@ from cli.tools.shell_render import (
|
|
|
49
49
|
split_lines,
|
|
50
50
|
split_preview,
|
|
51
51
|
)
|
|
52
|
-
from core import count_tokens
|
|
52
|
+
from core import blas_threads, count_tokens
|
|
53
53
|
from services import access_guard
|
|
54
54
|
from services.shell_output import (
|
|
55
55
|
TEXT_MAX_BYTES,
|
|
@@ -196,8 +196,9 @@ def _select_bash() -> str | None:
|
|
|
196
196
|
def _popen_kwargs(extra_env: dict | None = None) -> dict:
|
|
197
197
|
# Force UTF-8 in child processes so Unicode output (→, box-drawing, emoji)
|
|
198
198
|
# doesn't crash on Windows' legacy cp1252 console encoding. setdefault so an
|
|
199
|
-
# intentional caller-set encoding still wins.
|
|
200
|
-
|
|
199
|
+
# intentional caller-set encoding still wins. The user's command also gets
|
|
200
|
+
# the user's own OpenBLAS thread count, not the one C3 pins for itself.
|
|
201
|
+
env = blas_threads.user_env(dict(os.environ))
|
|
201
202
|
env.setdefault("PYTHONUTF8", "1")
|
|
202
203
|
env.setdefault("PYTHONIOENCODING", "utf-8")
|
|
203
204
|
if extra_env:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: code-context-control
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.159.1
|
|
4
4
|
Summary: Local MCP code-intelligence for AI coding tools: surgical search/read/edit, agent-config version history, path-level access + masking guards, and a multi-project hub.
|
|
5
5
|
Author-email: Dimitri Tselenchuk <dtselenc@gmail.com>
|
|
6
6
|
License-Expression: Apache-2.0
|