-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3482 lines (3000 loc) · 133 KB
/
server.py
File metadata and controls
3482 lines (3000 loc) · 133 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
from __future__ import annotations
import base64
import fnmatch
import hashlib
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
import urllib.request
import zipfile
from copy import deepcopy
from pathlib import Path, PurePosixPath
from urllib.parse import unquote, urlparse
from typing import Any, Callable, Optional, Tuple, Union
from toolmodules import get_extension_tooling
from toolmodules.extensions.common import install_package_with_pip
SERVER_NAME = "CodexTools"
SERVER_VERSION = "0.8.1"
DEFAULT_PROTOCOL_VERSION = "2024-11-05"
BASE_DIR = Path(__file__).resolve().parent
CAPABILITY_DIR = BASE_DIR / "capabilities"
CAPABILITY_INDEX_PATH = CAPABILITY_DIR / "INDEX.md"
CAPABILITY_DECLARATION_PATH = CAPABILITY_DIR / "declaration.json"
CAPABILITY_RESOURCE_PREFIX = "codextools://capabilities"
DEFAULT_TEXT_READ_MAX_CHARS = 4000
DEFAULT_TEXTS_READ_MAX_CHARS_PER_FILE = 3000
DEFAULT_TEXTS_READ_MAX_CHARS_TOTAL = 12000
DEFAULT_SEARCH_MAX_MATCHES = 80
DEFAULT_SEARCH_MAX_MATCHES_PER_FILE = 8
DEFAULT_SEARCH_MAX_SKIPPED_FILES = 20
DEFAULT_SEARCH_COMMON_EXCLUDED_DIRS = frozenset(
{
".git",
".hg",
".svn",
".venv",
"venv",
"node_modules",
"__pycache__",
".mypy_cache",
".pytest_cache",
".ruff_cache",
".tox",
".idea",
".vscode",
"dist",
"build",
"local_cache",
}
)
DEFAULT_PROC_STDOUT_MAX_CHARS = 4000
DEFAULT_PROC_STDERR_MAX_CHARS = 4000
def _log(msg: str) -> None:
print(msg, file=sys.stderr, flush=True)
def _ok(payload: Any) -> dict[str, Any]:
text = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False, indent=2)
return {"content": [{"type": "text", "text": text}]}
def _tool_error(message: str) -> dict[str, Any]:
return {"content": [{"type": "text", "text": message}], "isError": True}
def _require_str(args: dict[str, Any], key: str) -> str:
value = args.get(key)
if not isinstance(value, str) or not value.strip():
raise ValueError(f"`{key}` must be a non-empty string")
return value
def _require_str_list(args: dict[str, Any], key: str) -> list[str]:
value = args.get(key)
if not isinstance(value, list) or not value:
raise ValueError(f"`{key}` must be a non-empty string array")
result: list[str] = []
for index, item in enumerate(value):
if not isinstance(item, str) or not item.strip():
raise ValueError(f"`{key}[{index}]` must be a non-empty string")
result.append(item)
return result
def _as_int(
value: Any,
default: int,
minimum: Optional[int] = None,
maximum: Optional[int] = None,
) -> int:
if value is None:
result = default
elif isinstance(value, bool):
raise ValueError("bool is not valid for integer field")
else:
result = int(value)
if minimum is not None and result < minimum:
raise ValueError(f"value must be >= {minimum}")
if maximum is not None and result > maximum:
raise ValueError(f"value must be <= {maximum}")
return result
def _as_bool(value: Any, default: bool) -> bool:
if value is None:
return default
return bool(value)
def _path(path_text: str) -> Path:
return Path(path_text).expanduser().resolve()
def _resolve_workspace_root() -> Path:
env_override = os.environ.get("CODEXTOOLS_WORKSPACE_ROOT", "").strip()
if env_override:
return _path(env_override)
probe = Path.cwd().resolve()
if shutil.which("git"):
try:
completed = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
cwd=str(probe),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
repo_root = completed.stdout.strip()
if completed.returncode == 0 and repo_root:
return Path(repo_root).resolve()
except Exception:
pass
return probe
def _workspace_state_key(workspace_root: Path) -> str:
normalized = str(workspace_root).strip()
if os.name == "nt":
normalized = normalized.lower()
digest = hashlib.sha1(normalized.encode("utf-8", errors="replace")).hexdigest()
return f"ws-{digest[:12]}"
def _paths_equal(left: Path, right: Path) -> bool:
if os.name == "nt":
return str(left).lower() == str(right).lower()
return str(left) == str(right)
PROJECT_ROOT = Path(__file__).resolve().parent
PROJECT_NAME = PROJECT_ROOT.name
WORKSPACE_ROOT = _resolve_workspace_root()
WORKSPACE_STATE_KEY = _workspace_state_key(WORKSPACE_ROOT)
STATE_ROOT = PROJECT_ROOT / ".agent" / "state" / WORKSPACE_STATE_KEY
CONTROL_STATE_PATH = STATE_ROOT / "codextools_control_state.json"
def _runtime_project_name() -> str:
try:
workspace_root = _resolve_runtime_workspace_root()
except Exception:
workspace_root = WORKSPACE_ROOT
candidate = workspace_root.name.strip()
return candidate if candidate else PROJECT_NAME
PROC_RUN_DENY_PRIMARY_COMMANDS = {
"cat",
"type",
"echo",
"sed",
"awk",
"perl",
"get-content",
"set-content",
"out-file",
"copy",
"cp",
"move",
"mv",
"rm",
"del",
"erase",
"mkdir",
"md",
"rmdir",
"rd",
"touch",
"new-item",
"ni",
}
PROC_RUN_REDIRECTION_PATTERN = re.compile(r"(?:^|\s)(?:\|>|>>|<|<<|1>|2>|1>>|2>>)(?:\s|$)")
MODEL_LINE_PATTERN = re.compile(r"(?m)^\s*model\s*=\s*[\"']([^\"']+)[\"']\s*$")
AUTO_AGENT_RULES_VERSION = 2
AUTO_AGENT_BLOCK_NAMESPACE = "codextools:auto-agent-rules"
AUTO_AGENT_BLOCK_START = f"<!-- {AUTO_AGENT_BLOCK_NAMESPACE}:v{AUTO_AGENT_RULES_VERSION}:start -->"
AUTO_AGENT_BLOCK_END = f"<!-- {AUTO_AGENT_BLOCK_NAMESPACE}:v{AUTO_AGENT_RULES_VERSION}:end -->"
AUTO_AGENT_BLOCK_PATTERN = re.compile(
rf"(?s)(?P<block><!--\s*{re.escape(AUTO_AGENT_BLOCK_NAMESPACE)}(?:\:v(?P<start_version>\d+))?\:start\s*-->.*?<!--\s*{re.escape(AUTO_AGENT_BLOCK_NAMESPACE)}(?:\:v(?P<end_version>\d+))?\:end\s*-->)"
)
FALLBACK_AGENT_RULES_TEXT = "# Agent Rules\n\n- Follow project instructions for this workspace.\n"
_RUNTIME_MODEL_HINT = ""
_RUNTIME_WORKSPACE_ROOT_HINT = ""
def _utc_now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _ensure_control_paths() -> None:
STATE_ROOT.mkdir(parents=True, exist_ok=True)
def _default_guard_policy_state() -> dict[str, Any]:
return {
"enforce_proc_run_policy": True,
"audit": [],
}
def _normalize_guard_policy_state(raw: Any) -> dict[str, Any]:
guard = _default_guard_policy_state()
if not isinstance(raw, dict):
return guard
guard["enforce_proc_run_policy"] = bool(raw.get("enforce_proc_run_policy", True))
audit_raw = raw.get("audit")
if isinstance(audit_raw, list):
audit: list[dict[str, Any]] = []
for item in audit_raw:
if not isinstance(item, dict):
continue
entry_time = item.get("time")
entry_event = item.get("event")
entry_message = item.get("message")
if not isinstance(entry_time, str) or not entry_time.strip():
continue
if not isinstance(entry_event, str) or not entry_event.strip():
continue
if not isinstance(entry_message, str) or not entry_message.strip():
continue
entry: dict[str, Any] = {
"time": entry_time.strip(),
"event": entry_event.strip(),
"message": entry_message.strip(),
}
entry_tool = item.get("tool")
if isinstance(entry_tool, str) and entry_tool.strip():
entry["tool"] = entry_tool.strip()
extra = item.get("extra")
if isinstance(extra, dict) and extra:
entry["extra"] = extra
audit.append(entry)
guard["audit"] = audit[-200:]
return guard
def _ensure_guard_policy_state(state: dict[str, Any]) -> dict[str, Any]:
guard = _normalize_guard_policy_state(state.get("guard_policy"))
state["guard_policy"] = guard
return guard
def _append_guard_audit(
state: dict[str, Any],
*,
event: str,
message: str,
tool: Optional[str] = None,
extra: Optional[dict[str, Any]] = None,
) -> None:
guard = _ensure_guard_policy_state(state)
audit_raw = guard.get("audit")
audit = audit_raw if isinstance(audit_raw, list) else []
entry: dict[str, Any] = {
"time": _utc_now(),
"event": event,
"message": message,
}
if isinstance(tool, str) and tool.strip():
entry["tool"] = tool.strip()
if isinstance(extra, dict) and extra:
entry["extra"] = extra
audit.append(entry)
guard["audit"] = audit[-200:]
def _default_control_state() -> dict[str, Any]:
return {
"version": 1,
"workspace_root": str(WORKSPACE_ROOT),
"workspace_state_key": WORKSPACE_STATE_KEY,
"guard_policy": _default_guard_policy_state(),
}
def _load_control_state() -> dict[str, Any]:
_ensure_control_paths()
if not CONTROL_STATE_PATH.exists():
return _default_control_state()
try:
loaded = json.loads(CONTROL_STATE_PATH.read_text(encoding="utf-8", errors="replace"))
if not isinstance(loaded, dict):
raise ValueError("state root must be object")
except Exception as e:
_log(f"state load failed, using defaults: {e}")
return _default_control_state()
state = _default_control_state()
for key in state.keys():
if key in loaded:
state[key] = loaded[key]
state["workspace_root"] = str(WORKSPACE_ROOT)
state["workspace_state_key"] = WORKSPACE_STATE_KEY
_ensure_guard_policy_state(state)
return state
def _save_control_state(state: dict[str, Any]) -> None:
_ensure_control_paths()
CONTROL_STATE_PATH.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8", newline="")
def _next_identifier(state: dict[str, Any], seq_key: str, prefix: str) -> str:
raw = state.get(seq_key, 1)
try:
seq = int(raw)
except Exception:
seq = 1
if seq < 1:
seq = 1
state[seq_key] = seq + 1
return f"{prefix}-{seq:04d}"
def _coerce_plan_status(value: Any) -> str:
status = str(value).strip().lower()
return status if status in PLAN_STEP_STATUSES else "pending"
def _compute_plan_progress(steps: list[dict[str, Any]]) -> tuple[int, int, int, dict[str, int]]:
counts = {status: 0 for status in PLAN_STEP_STATUSES}
for step in steps:
status = _coerce_plan_status(step.get("status", "pending"))
counts[status] += 1
total_steps = len(steps)
completed = counts["completed"]
progress_percent = int((completed * 100) / total_steps) if total_steps > 0 else 0
return total_steps, completed, progress_percent, counts
def _compact_text(value: Any, fallback: str = "") -> str:
if value is None:
return fallback
text = value if isinstance(value, str) else str(value)
compact = " ".join(part for part in text.splitlines() if part.strip())
return compact.strip() or fallback
def _normalize_newlines(text: str) -> str:
return text.replace("\r\n", "\n").replace("\r", "\n")
def _strip_auto_agent_blocks(text: str) -> str:
normalized = _normalize_newlines(text)
stripped = AUTO_AGENT_BLOCK_PATTERN.sub("", normalized)
return re.sub(r"\n{3,}", "\n\n", stripped).strip()
def _get_auto_agent_block_match(text: str) -> Optional[re.Match[str]]:
return AUTO_AGENT_BLOCK_PATTERN.search(_normalize_newlines(text))
def _get_auto_agent_block_version(match: re.Match[str]) -> Optional[int]:
versions: list[int] = []
for group_name in ("start_version", "end_version"):
raw_value = match.group(group_name)
if raw_value is None:
continue
try:
versions.append(int(raw_value))
except ValueError:
return None
if not versions:
return None
return min(versions)
def _build_auto_agent_block(template_text: str) -> str:
normalized_template = _strip_auto_agent_blocks(template_text)
if not normalized_template:
normalized_template = _strip_auto_agent_blocks(FALLBACK_AGENT_RULES_TEXT)
return f"{AUTO_AGENT_BLOCK_START}\n{normalized_template}\n{AUTO_AGENT_BLOCK_END}\n"
def _path_from_workspace_uri(uri_text: str) -> Optional[Path]:
compact = _compact_text(uri_text, "")
if not compact:
return None
parsed = urlparse(compact)
if parsed.scheme and parsed.scheme.lower() != "file":
return None
if parsed.scheme.lower() == "file":
raw_path = unquote(parsed.path or "")
if os.name == "nt" and re.fullmatch(r"/[A-Za-z]:.*", raw_path):
raw_path = raw_path[1:]
if parsed.netloc and os.name == "nt":
host = parsed.netloc.strip()
if host and host.lower() not in {"", "localhost"}:
raw_path = f"//{host}{raw_path}"
else:
raw_path = compact
try:
return Path(raw_path).expanduser().resolve()
except Exception:
return None
def _capture_runtime_workspace_hint(params: dict[str, Any]) -> None:
global _RUNTIME_WORKSPACE_ROOT_HINT
candidates: list[str] = []
def _add_candidate(value: Any) -> None:
if isinstance(value, str) and value.strip():
candidates.append(value.strip())
_add_candidate(params.get("rootPath"))
_add_candidate(params.get("rootUri"))
workspace_folders = params.get("workspaceFolders")
if isinstance(workspace_folders, list):
for item in workspace_folders:
if not isinstance(item, dict):
continue
_add_candidate(item.get("uri"))
_add_candidate(item.get("path"))
for meta_key in ("meta", "_meta"):
meta_obj = params.get(meta_key)
if not isinstance(meta_obj, dict):
continue
_add_candidate(meta_obj.get("rootPath"))
_add_candidate(meta_obj.get("rootUri"))
for candidate in candidates:
parsed = _path_from_workspace_uri(candidate)
if parsed is None:
continue
_RUNTIME_WORKSPACE_ROOT_HINT = str(parsed)
return
def _resolve_runtime_workspace_root() -> Path:
env_override = os.environ.get("CODEXTOOLS_WORKSPACE_ROOT", "").strip()
if env_override:
return _path(env_override)
hint = _compact_text(_RUNTIME_WORKSPACE_ROOT_HINT, "")
if hint:
try:
return _path(hint)
except Exception:
pass
return WORKSPACE_ROOT
def _capture_runtime_model_hint(params: dict[str, Any]) -> None:
global _RUNTIME_MODEL_HINT
hints: list[str] = []
def _add_hint(value: Any) -> None:
if not isinstance(value, str):
return
compact = _compact_text(value, "")
if compact:
hints.append(compact)
for key in ("model", "model_name", "modelName", "assistant_model", "assistantModel"):
_add_hint(params.get(key))
client_info = params.get("clientInfo")
if isinstance(client_info, dict):
for key in ("name", "title", "version", "model"):
_add_hint(client_info.get(key))
for meta_key in ("meta", "_meta"):
meta_obj = params.get(meta_key)
if not isinstance(meta_obj, dict):
continue
for key in ("model", "model_name", "modelName", "assistant_model", "assistantModel"):
_add_hint(meta_obj.get(key))
if hints:
_RUNTIME_MODEL_HINT = " ".join(dict.fromkeys(hints))
def _load_model_hint_from_local_config() -> str:
workspace_root = _resolve_runtime_workspace_root()
config_candidates = (
workspace_root / "codex.config.codextools.toml",
workspace_root / "codex.config.toml",
PROJECT_ROOT / "codex.config.codextools.toml",
PROJECT_ROOT / "codex.config.toml",
)
for config_path in config_candidates:
if not config_path.exists():
continue
try:
config_text = config_path.read_text(encoding="utf-8", errors="replace")
except Exception:
continue
match = MODEL_LINE_PATTERN.search(config_text)
if not match:
continue
candidate = _compact_text(match.group(1), "")
if candidate:
return candidate
return ""
def _resolve_agent_target_filename() -> str:
hints: list[str] = []
runtime_hint = _compact_text(_RUNTIME_MODEL_HINT, "")
if runtime_hint:
hints.append(runtime_hint)
config_hint = _load_model_hint_from_local_config()
if config_hint:
hints.append(config_hint)
for env_key in ("CODEX_MODEL", "MODEL", "OPENAI_MODEL", "ANTHROPIC_MODEL", "LLM_MODEL"):
env_value = os.environ.get(env_key)
if isinstance(env_value, str) and env_value.strip():
hints.append(env_value.strip())
merged_hint = " ".join(hints).lower()
if "claude" in merged_hint:
return "CLAUDE.MD"
if "codex" in merged_hint:
return "AGENTS.MD"
return "AGENTS.MD"
def _load_agent_template_text(target_filename: str, workspace_root: Path) -> str:
target_path = workspace_root / target_filename
candidates: list[Path] = [
workspace_root / "AGENTS.MD",
workspace_root / "AGENTS.md",
PROJECT_ROOT / "AGENTS.MD",
PROJECT_ROOT / "AGENTS.md",
]
if target_filename.upper() == "AGENTS.MD":
candidates.extend(
[
workspace_root / "CLAUDE.MD",
workspace_root / "CLAUDE.md",
PROJECT_ROOT / "CLAUDE.MD",
PROJECT_ROOT / "CLAUDE.md",
]
)
seen: set[str] = set()
target_key = str(target_path).lower()
for candidate in candidates:
key = str(candidate).lower()
if key == target_key or key in seen:
continue
seen.add(key)
if not candidate.exists():
continue
try:
text = candidate.read_text(encoding="utf-8", errors="replace")
except Exception:
continue
normalized = _strip_auto_agent_blocks(text)
if normalized:
return normalized + "\n"
return FALLBACK_AGENT_RULES_TEXT
def _ensure_runtime_agent_file_ready() -> dict[str, Any]:
workspace_root = _resolve_runtime_workspace_root()
target_filename = _resolve_agent_target_filename()
target_path = workspace_root / target_filename
template_text = _load_agent_template_text(target_filename, workspace_root)
normalized_template = _strip_auto_agent_blocks(template_text)
if not normalized_template:
normalized_template = _strip_auto_agent_blocks(FALLBACK_AGENT_RULES_TEXT)
managed_block = _build_auto_agent_block(normalized_template)
workspace_root.mkdir(parents=True, exist_ok=True)
existed = target_path.exists()
existing_text = ""
if existed:
existing_text = target_path.read_text(encoding="utf-8", errors="replace")
normalized_existing = _normalize_newlines(existing_text)
stripped_existing = normalized_existing.strip()
block_match = _get_auto_agent_block_match(normalized_existing)
if block_match is not None:
block_version = _get_auto_agent_block_version(block_match)
existing_block = _normalize_newlines(block_match.group("block")).strip()
desired_block = managed_block.strip()
if block_version is not None and block_version > AUTO_AGENT_RULES_VERSION:
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "already_newer",
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": block_version,
}
if block_version == AUTO_AGENT_RULES_VERSION and existing_block == desired_block:
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "already_current",
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": block_version,
}
updated_text = (
normalized_existing[: block_match.start("block")]
+ managed_block
+ normalized_existing[block_match.end("block") :]
)
if updated_text and not updated_text.endswith("\n"):
updated_text += "\n"
target_path.write_text(updated_text, encoding="utf-8", newline="")
update_reason = "version_missing"
if block_version is not None:
update_reason = "version_outdated" if block_version < AUTO_AGENT_RULES_VERSION else "content_changed"
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "updated",
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": block_version,
"update_reason": update_reason,
}
if stripped_existing == normalized_template:
target_path.write_text(managed_block, encoding="utf-8", newline="")
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "versioned",
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": None,
}
if normalized_template and normalized_template in normalized_existing:
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "already_present",
"current_version": AUTO_AGENT_RULES_VERSION,
}
if stripped_existing:
base_text = existing_text
if base_text and not base_text.endswith(("\n", "\r")):
base_text += "\n"
if base_text and not base_text.endswith("\n\n"):
base_text += "\n"
target_path.write_text(base_text + managed_block, encoding="utf-8", newline="")
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": "appended",
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": None,
}
target_path.write_text(managed_block, encoding="utf-8", newline="")
action = "created" if not existed else "initialized"
return {
"path": str(target_path),
"filename": target_filename,
"workspace_root": str(workspace_root),
"action": action,
"current_version": AUTO_AGENT_RULES_VERSION,
"existing_version": None,
}
def _enforce_agent_file_gate(tool_name: str) -> None:
try:
result = _ensure_runtime_agent_file_ready()
except Exception as e:
raise PermissionError(
f"Tool call blocked: failed to prepare AGENTS/CLAUDE file before `{tool_name}`: {e}"
) from e
action = _compact_text(result.get("action"), "") if isinstance(result, dict) else ""
if action in {"created", "initialized", "appended", "updated", "versioned"}:
state = _load_control_state()
_append_guard_audit(
state,
event="agent_file_prepared",
message=f"prepared {result.get('filename', 'AGENTS/CLAUDE')} in workspace.",
tool=tool_name,
extra={
"action": action,
"path": result.get("path"),
"workspace_root": result.get("workspace_root"),
},
)
_save_control_state(state)
def _tokenize_proc_run_command(command: Any, shell_mode: bool) -> list[str]:
if isinstance(command, list):
if not all(isinstance(item, str) for item in command):
raise ValueError("`command` list must contain only strings")
return [item for item in command if item]
if isinstance(command, str):
if shell_mode:
return [command]
parsed = shlex.split(command, posix=False if os.name == "nt" else True)
return parsed if parsed else [command]
raise ValueError("`command` must be a string or string array")
def _primary_command_name(tokens: list[str]) -> str:
if not tokens:
return ""
head = tokens[0].strip().strip('"').strip("'")
if not head:
return ""
return Path(head).name.lower()
def _normalize_proc_run_batch_item(item: Any, index: int, default_reason: str) -> dict[str, Any]:
if not isinstance(item, dict):
raise ValueError(f"`commands[{index}]` must be an object")
if "command" not in item:
raise ValueError(f"`commands[{index}].command` is required")
normalized: dict[str, Any] = {
"command": item["command"],
"reason": default_reason,
}
for key in ("cwd", "timeout_sec", "shell", "env"):
if key in item:
normalized[key] = item[key]
return normalized
def _enforce_proc_run_policy(args: dict[str, Any]) -> None:
state = _load_control_state()
guard = _ensure_guard_policy_state(state)
if not bool(guard.get("enforce_proc_run_policy", True)):
return
reason = args.get("reason")
if not isinstance(reason, str) or not reason.strip():
message = (
"proc_run blocked by policy: provide `reason` and explain why CodexTools fs tools are insufficient."
)
_append_guard_audit(state, event="proc_blocked_missing_reason", message=message, tool="proc_run")
_save_control_state(state)
raise PermissionError(message)
shell_mode = _as_bool(args.get("shell"), False)
command = args.get("command")
tokens = _tokenize_proc_run_command(command, shell_mode)
command_text = command if isinstance(command, str) else " ".join(tokens)
if shell_mode:
message = "proc_run blocked by policy: `shell=true` is disabled. Use shell=false and CodexTools fs tools."
_append_guard_audit(
state,
event="proc_blocked_shell_mode",
message=message,
tool="proc_run",
extra={"command": command_text},
)
_save_control_state(state)
raise PermissionError(message)
if isinstance(command_text, str) and PROC_RUN_REDIRECTION_PATTERN.search(command_text):
message = "proc_run blocked by policy: shell redirection or pipeline detected. Use CodexTools fs tools for file/text work."
_append_guard_audit(
state,
event="proc_blocked_redirection",
message=message,
tool="proc_run",
extra={"command": command_text},
)
_save_control_state(state)
raise PermissionError(message)
primary = _primary_command_name(tokens)
if primary in PROC_RUN_DENY_PRIMARY_COMMANDS:
message = (
f"proc_run blocked by policy: `{primary}` is reserved for file/text operations. "
"Use CodexTools fs tools instead."
)
_append_guard_audit(
state,
event="proc_blocked_file_text_command",
message=message,
tool="proc_run",
extra={"command": command_text, "primary": primary},
)
_save_control_state(state)
raise PermissionError(message)
def _enforce_proc_run_batch_policy(args: dict[str, Any]) -> None:
reason = args.get("reason")
raw_commands = args.get("commands")
if not isinstance(raw_commands, list) or not raw_commands:
raise ValueError("`commands` must be a non-empty array")
default_reason = reason if isinstance(reason, str) else ""
for index, item in enumerate(raw_commands):
_enforce_proc_run_policy(_normalize_proc_run_batch_item(item, index, default_reason))
def _enforce_tool_policy(name: str, args: dict[str, Any]) -> None:
_enforce_agent_file_gate(name)
if name in {"proc_run", "debug_run", "perf_benchmark"}:
_enforce_proc_run_policy(args)
elif name == "proc_run_batch":
_enforce_proc_run_batch_policy(args)
_JAR_TEXT_FILE_SUFFIXES: tuple[str, ...] = (
".java",
".kt",
".kts",
".groovy",
".scala",
".xml",
".properties",
".mf",
".txt",
".md",
".json",
".yaml",
".yml",
".csv",
".sql",
)
def _normalize_jar_entry_name(entry_text: str) -> str:
entry_name = entry_text.strip().replace("\\", "/").lstrip("/")
if not entry_name:
raise ValueError("jar entry path must be a non-empty string")
return entry_name
def _split_jar_path_and_entry(path_text: str) -> tuple[Path, Optional[str]]:
raw = path_text.strip()
for marker in ("!/", "!\\"):
if marker in raw:
jar_text, entry_text = raw.split(marker, 1)
jar_path = _path(jar_text)
if jar_path.suffix.lower() != ".jar":
raise ValueError("archive entry syntax requires a `.jar` path before `!/`")
return jar_path, _normalize_jar_entry_name(entry_text)
return _path(raw), None
def _apply_text_read_limits(
content: str,
start_line: Any,
end_line: Any,
max_lines: Any,
max_chars: Any,
) -> dict[str, Any]:
all_lines = content.splitlines(keepends=True)
lines = all_lines
if start_line is not None or end_line is not None:
start = _as_int(start_line, 1, minimum=1)
end = _as_int(end_line, len(all_lines), minimum=1)
if end < start:
raise ValueError("`end_line` must be >= `start_line`")
lines = all_lines[start - 1 : end]
selected_line_count = len(lines)
truncated_by_lines = False
if max_lines is not None:
line_limit = _as_int(max_lines, 1, minimum=1)
if len(lines) > line_limit:
lines = lines[:line_limit]
truncated_by_lines = True
limited_content = "".join(lines)
truncated_by_chars = False
if max_chars is not None:
limit = _as_int(max_chars, 0, minimum=0)
if limit and len(limited_content) > limit:
limited_content = limited_content[:limit]
truncated_by_chars = True
return {
"line_count": len(all_lines),
"selected_line_count": selected_line_count,
"returned_line_count": len(lines),
"truncated": truncated_by_lines or truncated_by_chars,
"truncated_by_lines": truncated_by_lines,
"truncated_by_chars": truncated_by_chars,
"content": limited_content,
}
def _truncate_result_text(value: str, limit: int) -> tuple[str, bool]:
if limit <= 0:
return "", bool(value)
if len(value) <= limit:
return value, False
if limit <= 3:
return value[:limit], True
return value[: limit - 3] + "...", True
def _is_probably_text_jar_entry(entry_name: str) -> bool:
lower_name = entry_name.lower()
return lower_name.endswith(_JAR_TEXT_FILE_SUFFIXES)
def _encode_binary_payload(data: bytes, binary_encoding: str) -> str:
if binary_encoding == "hex":
return data.hex()
return base64.b64encode(data).decode("ascii")
_CLASS_METHOD_ACCESS_FLAGS: tuple[tuple[int, str], ...] = (
(0x0001, "public"),
(0x0002, "private"),
(0x0004, "protected"),
(0x0008, "static"),
(0x0010, "final"),
(0x0020, "synchronized"),
(0x0040, "bridge"),
(0x0080, "varargs"),
(0x0100, "native"),
(0x0400, "abstract"),
(0x0800, "strict"),
(0x1000, "synthetic"),
)
_CLASS_PRIMITIVE_TYPES: dict[str, str] = {
"V": "void",
"Z": "boolean",