-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathclaw_adapter.py
More file actions
1708 lines (1439 loc) · 64.8 KB
/
Copy pathclaw_adapter.py
File metadata and controls
1708 lines (1439 loc) · 64.8 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
# Adapted from MetaClaw
"""
Claw adapter: auto-configures the active CLI agent to use the SkillClaw proxy.
Supported agents:
openclaw — runs `openclaw config set …` + `openclaw gateway restart`
opencode — patches ~/.config/opencode/opencode.json to register SkillClaw provider
hermes — patches ~/.hermes/config.yaml to point model traffic at SkillClaw
codex — patches ~/.codex/config.toml to register an opt-in SkillClaw profile
claude — patches ~/.claude/settings.json to route Anthropic traffic via SkillClaw
qwenpaw — patches QwenPaw model config, selects SkillClaw as active model
ironclaw — patches ~/.ironclaw/.env, runs `ironclaw service restart`
picoclaw — patches ~/.picoclaw/config.json model_list, runs `picoclaw gateway restart`
zeroclaw — patches ~/.zeroclaw/config.toml, runs `zeroclaw service restart`
nanoclaw — patches nanoclaw's .env (ANTHROPIC_BASE_URL), restarts via launchd/systemd
nemoclaw — registers skillclaw provider in OpenShell, sets inference route
none — skip auto-configuration entirely
Add more claws by implementing a `_configure_<name>` function and registering
it in ``_ADAPTERS``.
"""
from __future__ import annotations
import datetime
import json
import logging
import os
import platform
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Callable
import yaml
if TYPE_CHECKING:
from .config import SkillClawConfig
logger = logging.getLogger(__name__)
_LEGACY_SKILLCLAW_SKILLS_DIR = Path.home() / ".skillclaw" / "skills"
_HERMES_HOME = Path.home() / ".hermes"
_HERMES_SKILLS_DIR = _HERMES_HOME / "skills"
_HERMES_BACKUP_DIR = Path.home() / ".skillclaw" / "backups" / "hermes"
_CODEX_HOME = Path.home() / ".codex"
_CODEX_CONFIG_PATH = _CODEX_HOME / "config.toml"
_CODEX_PROFILE_CONFIG_PATH = _CODEX_HOME / "skillclaw.config.toml"
_CODEX_SKILLS_DIR = _CODEX_HOME / "skills"
_CODEX_BACKUP_DIR = Path.home() / ".skillclaw" / "backups" / "codex"
_CLAUDE_HOME = Path.home() / ".claude"
_CLAUDE_SETTINGS_PATH = _CLAUDE_HOME / "settings.json"
_CLAUDE_SKILLS_DIR = _CLAUDE_HOME / "skills"
_CLAUDE_BACKUP_DIR = Path.home() / ".skillclaw" / "backups" / "claude"
_OPENCODE_CONFIG_DIR = Path.home() / ".config" / "opencode"
_OPENCODE_CONFIG_PATH = _OPENCODE_CONFIG_DIR / "opencode.json"
_OPENCODE_SKILLS_DIR = _OPENCODE_CONFIG_DIR / "skills"
_OPENCODE_BACKUP_DIR = Path.home() / ".skillclaw" / "backups" / "opencode"
# ------------------------------------------------------------------ #
# Dispatcher #
# ------------------------------------------------------------------ #
def configure_claw(cfg: "SkillClawConfig") -> None:
"""Dispatch to the appropriate claw adapter based on cfg.claw_type."""
claw = getattr(cfg, "claw_type", "openclaw")
# Backward-compat: configure_openclaw=False → treat as "none"
configure_flag = getattr(cfg, "configure_openclaw", True)
if not configure_flag:
claw = "none"
adapter = _ADAPTERS.get(claw)
if adapter is None:
logger.warning("[ClawAdapter] Unknown claw_type=%r — skipping auto-configuration", claw)
return
adapter(cfg)
# ------------------------------------------------------------------ #
# OpenClaw adapter #
# ------------------------------------------------------------------ #
def _configure_openclaw(cfg: "SkillClawConfig") -> None:
"""Auto-configure OpenClaw to use the SkillClaw proxy."""
model_id = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
provider_json = json.dumps(
{
"api": "openai-completions",
"baseUrl": f"http://127.0.0.1:{cfg.proxy_port}/v1",
"apiKey": cfg.proxy_api_key or "skillclaw",
"models": [
{
"id": model_id,
"name": model_id,
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 32768,
"maxTokens": 8192,
}
],
}
)
commands = [
["openclaw", "config", "set", "models.providers.skillclaw", "--json", provider_json],
["openclaw", "config", "set", "agents.defaults.model.primary", f"skillclaw/{model_id}"],
["openclaw", "config", "set", "agents.defaults.sandbox.mode", "off"],
["openclaw", "gateway", "restart"],
]
_run_commands("openclaw", commands)
# ------------------------------------------------------------------ #
# Hermes adapter #
# ------------------------------------------------------------------ #
def _load_yaml_mapping(path: Path, label: str) -> dict:
"""Load a YAML mapping, falling back to an empty mapping."""
if not path.exists():
return {}
try:
loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except Exception as e:
logger.warning("[ClawAdapter] Failed to read %s config %s: %s", label, path, e)
return {}
if isinstance(loaded, dict):
return loaded
logger.warning(
"[ClawAdapter] %s config %s is not a mapping; replacing it",
label,
path,
)
return {}
def _load_json_mapping(path: Path, label: str) -> dict:
"""Load a JSON mapping, falling back to an empty mapping."""
if not path.exists():
return {}
try:
loaded = json.loads(path.read_text(encoding="utf-8")) or {}
except Exception as e:
logger.warning("[ClawAdapter] Failed to read %s config %s: %s", label, path, e)
return {}
if isinstance(loaded, dict):
return loaded
logger.warning(
"[ClawAdapter] %s config %s is not a mapping; replacing it",
label,
path,
)
return {}
def _write_yaml_mapping_atomic(path: Path, data: dict, label: str) -> None:
"""Atomically write a YAML mapping to disk."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_path = Path(handle.name)
handle.write(_yaml_mapping_to_text(data))
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
logger.info("[ClawAdapter] %s config updated: %s", label, path)
except Exception as e:
logger.error("[ClawAdapter] Failed to write %s config %s: %s", label, path, e)
finally:
if tmp_path is not None:
tmp_path.unlink(missing_ok=True)
def _yaml_mapping_to_text(data: dict) -> str:
return yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
def _write_text_atomic(path: Path, text: str, label: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_path = Path(handle.name)
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
logger.info("[ClawAdapter] %s updated: %s", label, path)
except Exception as e:
logger.error("[ClawAdapter] Failed to write %s %s: %s", label, path, e)
finally:
if tmp_path is not None:
tmp_path.unlink(missing_ok=True)
def _backup_text_file_if_changed(
path: Path,
new_text: str,
*,
backup_dir: Path,
backup_stem: str,
backup_suffix: str,
label: str,
) -> Path | None:
"""Save a timestamped backup before overwriting a text file."""
if not path.exists():
return None
try:
current_text = path.read_text(encoding="utf-8")
except Exception as e:
logger.warning("[ClawAdapter] Failed to read %s for backup: %s", path, e)
return None
if current_text == new_text:
return None
backup_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
backup_path = backup_dir / f"{backup_stem}.{timestamp}.{backup_suffix}"
latest_path = backup_dir / f"{backup_stem}.latest.{backup_suffix}"
try:
backup_path.write_text(current_text, encoding="utf-8")
latest_path.write_text(current_text, encoding="utf-8")
logger.info("[ClawAdapter] %s backup saved: %s", label, backup_path)
return backup_path
except Exception as e:
logger.warning("[ClawAdapter] Failed to save %s backup: %s", label, e)
return None
def _latest_backup_path(backup_dir: Path, backup_stem: str, backup_suffix: str) -> Path | None:
latest_path = backup_dir / f"{backup_stem}.latest.{backup_suffix}"
if latest_path.exists():
return latest_path
if not backup_dir.is_dir():
return None
backups = sorted(backup_dir.glob(f"{backup_stem}.*.{backup_suffix}"))
return backups[-1] if backups else None
def _format_toml_value(value: object) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, int):
return str(value)
if isinstance(value, float):
return repr(value)
return json.dumps(str(value), ensure_ascii=False)
def _parse_toml_value(raw: str) -> object:
value = raw.strip()
if len(value) >= 2 and value.startswith('"') and value.endswith('"'):
try:
return json.loads(value)
except Exception:
return value[1:-1]
if value == "true":
return True
if value == "false":
return False
return value
def _upsert_top_level_toml_keys(text: str, updates: dict[str, object]) -> str:
"""Update simple top-level TOML assignments before the first table."""
lines = text.splitlines()
first_table_index = len(lines)
for idx, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
first_table_index = idx
break
preamble = lines[:first_table_index]
remainder = lines[first_table_index:]
seen: set[str] = set()
updated_preamble: list[str] = []
for line in preamble:
stripped = line.strip()
if stripped.startswith("#") or "=" not in stripped:
updated_preamble.append(line)
continue
key = stripped.split("=", 1)[0].strip()
if key in updates:
updated_preamble.append(f"{key} = {_format_toml_value(updates[key])}")
seen.add(key)
continue
updated_preamble.append(line)
missing_keys = [key for key in updates if key not in seen]
if missing_keys:
if updated_preamble and updated_preamble[-1].strip():
updated_preamble.append("")
for key in missing_keys:
updated_preamble.append(f"{key} = {_format_toml_value(updates[key])}")
if remainder:
updated_preamble.append("")
merged = updated_preamble + remainder
return "\n".join(merged).rstrip() + "\n"
def _remove_top_level_toml_keys(text: str, keys: set[str]) -> str:
"""Remove selected top-level assignments before the first TOML table."""
lines = text.splitlines()
first_table_index = len(lines)
for idx, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
first_table_index = idx
break
preamble = lines[:first_table_index]
remainder = lines[first_table_index:]
kept: list[str] = []
for line in preamble:
stripped = line.strip()
if stripped.startswith("#") or "=" not in stripped:
kept.append(line)
continue
key = stripped.split("=", 1)[0].strip()
if key not in keys:
kept.append(line)
return "\n".join(kept + remainder).rstrip() + "\n"
def _remove_toml_table(text: str, table_name: str) -> str:
"""Remove a TOML table and its body, if present."""
lines = text.splitlines()
kept: list[str] = []
skipping = False
target_header = f"[{table_name}]"
for line in lines:
stripped = line.strip()
is_header = stripped.startswith("[") and stripped.endswith("]")
if is_header:
if skipping:
skipping = False
if stripped == target_header:
skipping = True
continue
if skipping:
continue
kept.append(line)
return "\n".join(kept).rstrip() + "\n"
def _extract_toml_table(text: str, table_name: str) -> dict[str, object]:
"""Extract simple key/value pairs from a TOML table."""
result: dict[str, object] = {}
lines = text.splitlines()
target_header = f"[{table_name}]"
inside = False
for line in lines:
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
if inside:
break
inside = stripped == target_header
continue
if not inside or stripped.startswith("#") or "=" not in stripped:
continue
key, raw_value = stripped.split("=", 1)
result[key.strip()] = _parse_toml_value(raw_value)
return result
def _extract_top_level_toml_value(text: str, key: str) -> object | None:
"""Read a simple top-level TOML assignment before the first table."""
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
break
if stripped.startswith("#") or "=" not in stripped:
continue
current_key, raw_value = stripped.split("=", 1)
if current_key.strip() == key:
return _parse_toml_value(raw_value)
return None
def _prepare_external_skills_dir(target_dir: Path, label: str) -> None:
"""Prepare an agent-native skill directory without overwriting existing skills."""
target_dir.mkdir(parents=True, exist_ok=True)
if not _LEGACY_SKILLCLAW_SKILLS_DIR.is_dir():
return
migrated = _copy_missing_skill_dirs(_LEGACY_SKILLCLAW_SKILLS_DIR, target_dir)
if migrated > 0:
logger.info(
"[ClawAdapter] migrated %d legacy SkillClaw skill(s) into %s skills dir",
migrated,
label,
)
def _backup_hermes_config_if_changed(config_path: Path, new_text: str) -> Path | None:
"""Save the current Hermes config before overwriting it, if it changed."""
return _backup_text_file_if_changed(
config_path,
new_text,
backup_dir=_HERMES_BACKUP_DIR,
backup_stem="config",
backup_suffix="yaml",
label="Hermes config",
)
def _latest_hermes_backup_path() -> Path | None:
return _latest_backup_path(_HERMES_BACKUP_DIR, "config", "yaml")
def _write_json_mapping_atomic(path: Path, data: dict, label: str) -> None:
"""Atomically write a JSON mapping to disk."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_path = Path(handle.name)
json.dump(data, handle, indent=2, ensure_ascii=False)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
logger.info("[ClawAdapter] %s config updated: %s", label, path)
except Exception as e:
logger.error("[ClawAdapter] Failed to write %s config %s: %s", label, path, e)
finally:
if tmp_path is not None:
tmp_path.unlink(missing_ok=True)
def _configure_hermes(cfg: "SkillClawConfig") -> None:
"""Auto-configure Hermes to route model traffic through SkillClaw."""
config_path = _HERMES_HOME / "config.yaml"
model_id = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
api_key = cfg.proxy_api_key or "skillclaw"
base_url = f"http://127.0.0.1:{cfg.proxy_port}/v1"
_prepare_hermes_skills_dir(cfg)
data = _load_yaml_mapping(config_path, "Hermes")
model = data.get("model")
if not isinstance(model, dict):
model = {"default": model} if isinstance(model, str) and model.strip() else {}
model["provider"] = "custom"
model["base_url"] = base_url
model["default"] = model_id
model["api_key"] = api_key
# Clear stale provider-specific mode so Hermes auto-detects from the proxy URL.
model["api_mode"] = ""
data["model"] = model
_backup_hermes_config_if_changed(config_path, _yaml_mapping_to_text(data))
_write_yaml_mapping_atomic(config_path, data, "Hermes")
def inspect_hermes_config(cfg: "SkillClawConfig") -> dict[str, object]:
"""Return a diagnostic snapshot of the local Hermes integration state."""
config_path = _HERMES_HOME / "config.yaml"
expected_model = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
expected_base_url = f"http://127.0.0.1:{cfg.proxy_port}/v1"
expected_api_key = cfg.proxy_api_key or "skillclaw"
expected_skills_dir = Path(str(getattr(cfg, "skills_dir", "") or _HERMES_SKILLS_DIR)).expanduser()
data = _load_yaml_mapping(config_path, "Hermes")
model = data.get("model") if isinstance(data, dict) else {}
if not isinstance(model, dict):
model = {"default": model} if isinstance(model, str) and model else {}
configured_provider = str(model.get("provider", "") or "")
configured_base_url = str(model.get("base_url", "") or "")
configured_default = str(model.get("default", "") or "")
configured_api_key = str(model.get("api_key", "") or "")
backup_path = _latest_hermes_backup_path()
proxy_match = (
configured_provider == "custom"
and configured_base_url == expected_base_url
and configured_default == expected_model
and configured_api_key == expected_api_key
)
legacy_present = _LEGACY_SKILLCLAW_SKILLS_DIR.is_dir()
uses_default_skills_dir = expected_skills_dir == _HERMES_SKILLS_DIR
issues: list[str] = []
notes: list[str] = [
"This integration only rewrites Hermes-local config and does not touch other claw adapters.",
"Hermes session capture still relies on explicit session headers when"
" available, with proxy-side heuristics as the fallback.",
]
next_steps: list[str] = []
if not config_path.exists():
issues.append("Hermes config is missing: ~/.hermes/config.yaml")
if not proxy_match:
issues.append("Hermes model routing is not pointing at the local SkillClaw proxy.")
next_steps.append("Start SkillClaw once so it can rewrite ~/.hermes/config.yaml.")
if not expected_skills_dir.is_dir():
issues.append(f"Hermes skills directory is missing: {expected_skills_dir}")
next_steps.append(f"Create or prepare the Hermes skills directory: {expected_skills_dir}")
if legacy_present:
notes.append(
f"Legacy SkillClaw skills were found at {_LEGACY_SKILLCLAW_SKILLS_DIR};"
" missing skills are copied into the Hermes library on startup."
)
if not backup_path:
next_steps.append(
"Run SkillClaw once before relying on `skillclaw restore hermes`, so a backup can be created."
)
return {
"status": "ok" if not issues else "warning",
"config_path": str(config_path),
"config_exists": config_path.exists(),
"integration_scope": "hermes-only",
"expected_model": expected_model,
"expected_base_url": expected_base_url,
"configured_provider": configured_provider or "(unset)",
"configured_base_url": configured_base_url or "(unset)",
"configured_model": configured_default or "(unset)",
"proxy_match": proxy_match,
"expected_skills_dir": str(expected_skills_dir),
"skills_dir_exists": expected_skills_dir.is_dir(),
"skills_dir_mode": "hermes-default" if uses_default_skills_dir else "custom",
"legacy_skillclaw_skills_dir": str(_LEGACY_SKILLCLAW_SKILLS_DIR),
"legacy_skillclaw_skills_present": legacy_present,
"latest_backup": str(backup_path) if backup_path else "(none)",
"session_boundary_mode": "explicit headers if provided, proxy heuristics otherwise",
"issues": issues,
"notes": notes,
"next_steps": next_steps,
}
def restore_hermes_config(backup_path: Path | None = None) -> dict[str, str]:
"""Restore ~/.hermes/config.yaml from the latest or a specified backup."""
source = Path(backup_path).expanduser() if backup_path is not None else _latest_hermes_backup_path()
if source is None or not source.exists():
raise FileNotFoundError("No Hermes backup found")
text = source.read_text(encoding="utf-8")
target = _HERMES_HOME / "config.yaml"
_write_text_atomic(target, text, "Hermes config restore")
return {"source": str(source), "target": str(target)}
def _prepare_hermes_skills_dir(cfg: "SkillClawConfig") -> None:
"""Prepare the Hermes-local skill directory without touching other agents."""
target_dir = Path(str(getattr(cfg, "skills_dir", "") or _HERMES_SKILLS_DIR)).expanduser()
target_dir.mkdir(parents=True, exist_ok=True)
if target_dir != _HERMES_SKILLS_DIR:
logger.info(
"[ClawAdapter] Hermes uses custom skills dir: %s",
target_dir,
)
return
if not _LEGACY_SKILLCLAW_SKILLS_DIR.is_dir():
return
migrated = _copy_missing_skill_dirs(_LEGACY_SKILLCLAW_SKILLS_DIR, target_dir)
if migrated > 0:
logger.info(
"[ClawAdapter] migrated %d legacy SkillClaw skill(s) into Hermes skills dir",
migrated,
)
def _copy_missing_skill_dirs(src_root: Path, dst_root: Path) -> int:
"""Copy only skill folders that do not already exist in the destination."""
copied = 0
for entry in sorted(src_root.iterdir()):
if not entry.is_dir():
continue
src_skill_md = entry / "SKILL.md"
if not src_skill_md.is_file():
continue
dst_dir = dst_root / entry.name
dst_skill_md = dst_dir / "SKILL.md"
if dst_skill_md.exists():
continue
shutil.copytree(entry, dst_dir)
copied += 1
return copied
# ------------------------------------------------------------------ #
# Codex adapter #
# ------------------------------------------------------------------ #
def _backup_codex_config_if_changed(config_path: Path, new_text: str) -> Path | None:
return _backup_text_file_if_changed(
config_path,
new_text,
backup_dir=_CODEX_BACKUP_DIR,
backup_stem="config",
backup_suffix="toml",
label="Codex config",
)
def _latest_codex_backup_path() -> Path | None:
return _latest_backup_path(_CODEX_BACKUP_DIR, "config", "toml")
def _build_codex_provider_block(base_url: str, api_key: str) -> str:
lines = [
"[model_providers.skillclaw]",
'name = "SkillClaw"',
f"base_url = {_format_toml_value(base_url)}",
'wire_api = "responses"',
f"experimental_bearer_token = {_format_toml_value(api_key)}",
]
return "\n".join(lines) + "\n"
def _build_codex_profile_block(model_id: str) -> str:
lines = [
f"model = {_format_toml_value(model_id)}",
'model_provider = "skillclaw"',
]
return "\n".join(lines) + "\n"
def _configure_codex(cfg: "SkillClawConfig") -> None:
"""Register SkillClaw as an opt-in Codex profile.
Do not change Codex's global ``model`` / ``model_provider`` defaults.
Users opt in explicitly with ``codex --profile skillclaw``.
"""
model_id = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
api_key = cfg.proxy_api_key or "skillclaw"
base_url = f"http://127.0.0.1:{cfg.proxy_port}/v1"
config_path = _CODEX_CONFIG_PATH
profile_config_path = _CODEX_PROFILE_CONFIG_PATH
_prepare_external_skills_dir(_CODEX_SKILLS_DIR, "Codex")
existing_text = ""
if config_path.exists():
try:
existing_text = config_path.read_text(encoding="utf-8")
except Exception as e:
logger.warning("[ClawAdapter] Failed to read Codex config %s: %s", config_path, e)
updated = existing_text
if str(_extract_top_level_toml_value(updated, "model_provider") or "") == "skillclaw":
updated = _remove_top_level_toml_keys(updated, {"model", "model_provider"})
updated = _remove_toml_table(updated, "model_providers.skillclaw").rstrip() + "\n\n"
updated = _remove_toml_table(updated, "profiles.skillclaw").rstrip() + "\n\n"
profile_text = _build_codex_profile_block(model_id) + "\n" + _build_codex_provider_block(base_url, api_key)
_backup_codex_config_if_changed(config_path, updated)
_write_text_atomic(config_path, updated, "Codex config")
_write_text_atomic(profile_config_path, profile_text, "Codex SkillClaw profile config")
def inspect_codex_config(cfg: "SkillClawConfig") -> dict[str, object]:
"""Return a diagnostic snapshot of the local Codex integration state."""
config_path = _CODEX_CONFIG_PATH
profile_config_path = _CODEX_PROFILE_CONFIG_PATH
expected_model = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
expected_base_url = f"http://127.0.0.1:{cfg.proxy_port}/v1"
expected_api_key = cfg.proxy_api_key or "skillclaw"
expected_skills_dir = _CODEX_SKILLS_DIR
configured_skillclaw_skills_dir = Path(
str(getattr(cfg, "skills_dir", "") or expected_skills_dir),
).expanduser()
text = ""
if config_path.exists():
try:
text = config_path.read_text(encoding="utf-8")
except Exception as e:
logger.warning("[ClawAdapter] Failed to read Codex config %s: %s", config_path, e)
profile_text = ""
if profile_config_path.exists():
try:
profile_text = profile_config_path.read_text(encoding="utf-8")
except Exception as e:
logger.warning("[ClawAdapter] Failed to read Codex profile config %s: %s", profile_config_path, e)
configured_model = str(_extract_top_level_toml_value(text, "model") or "")
configured_provider = str(_extract_top_level_toml_value(text, "model_provider") or "")
provider_cfg = _extract_toml_table(profile_text, "model_providers.skillclaw")
configured_base_url = str(provider_cfg.get("base_url") or "")
configured_wire_api = str(provider_cfg.get("wire_api") or "")
configured_token = str(provider_cfg.get("experimental_bearer_token") or "")
configured_profile_model = str(_extract_top_level_toml_value(profile_text, "model") or "")
configured_profile_provider = str(_extract_top_level_toml_value(profile_text, "model_provider") or "")
proxy_match = (
configured_profile_model == expected_model
and configured_profile_provider == "skillclaw"
and configured_base_url == expected_base_url
and configured_wire_api == "responses"
and configured_token == expected_api_key
)
backup_path = _latest_codex_backup_path()
skills_dir_match = configured_skillclaw_skills_dir == expected_skills_dir
issues: list[str] = []
notes: list[str] = [
"Codex can opt into SkillClaw with `codex --profile skillclaw`.",
"SkillClaw registers a Codex profile and does not change Codex's global model defaults.",
"Codex session boundaries fall back to proxy-side heuristics because"
" Codex does not send SkillClaw session headers.",
]
next_steps: list[str] = []
if not config_path.exists():
issues.append("Codex config is missing: ~/.codex/config.toml")
if not profile_config_path.exists():
issues.append("Codex SkillClaw profile config is missing: ~/.codex/skillclaw.config.toml")
if not proxy_match:
issues.append("Codex SkillClaw profile is missing or not pointing at the local SkillClaw proxy.")
next_steps.append(
"Start SkillClaw once with `claw_type=codex` so it can register ~/.codex/skillclaw.config.toml."
)
if configured_provider == "skillclaw":
issues.append("Codex global model_provider still points at SkillClaw; normal Codex runs may be intercepted.")
next_steps.append('Remove top-level `model_provider = "skillclaw"` or run `skillclaw restore codex`.')
if not expected_skills_dir.is_dir():
issues.append(f"Codex skills directory is missing: {expected_skills_dir}")
next_steps.append(f"Create or prepare the Codex skills directory: {expected_skills_dir}")
if not skills_dir_match:
issues.append(
f"SkillClaw is configured to evolve skills in {configured_skillclaw_skills_dir}, "
f"but Codex reads skills from {expected_skills_dir}."
)
next_steps.append(f"Set `skills.dir` to {expected_skills_dir} when using the Codex integration.")
if not backup_path:
next_steps.append("Run SkillClaw once before relying on `skillclaw restore codex`, so a backup can be created.")
return {
"status": "ok" if not issues else "warning",
"config_path": str(config_path),
"config_exists": config_path.exists(),
"integration_scope": "codex-profile-only",
"expected_model": expected_model,
"configured_model": configured_model or "(unset)",
"expected_profile": "skillclaw",
"configured_profile_model": configured_profile_model or "(unset)",
"configured_profile_provider": configured_profile_provider or "(unset)",
"expected_base_url": expected_base_url,
"configured_base_url": configured_base_url or "(unset)",
"configured_provider": configured_provider or "(unset)",
"proxy_match": proxy_match,
"expected_skills_dir": str(expected_skills_dir),
"skills_dir_exists": expected_skills_dir.is_dir(),
"skills_dir_mode": "codex-default" if skills_dir_match else "custom",
"configured_skillclaw_skills_dir": str(configured_skillclaw_skills_dir),
"configured_wire_api": configured_wire_api or "(unset)",
"latest_backup": str(backup_path) if backup_path else "(none)",
"session_boundary_mode": "proxy heuristics",
"issues": issues,
"notes": notes,
"next_steps": next_steps,
}
def restore_codex_config(backup_path: Path | None = None) -> dict[str, str]:
"""Restore ~/.codex/config.toml from the latest or a specified backup."""
source = Path(backup_path).expanduser() if backup_path is not None else _latest_codex_backup_path()
if source is None or not source.exists():
raise FileNotFoundError("No Codex backup found")
text = source.read_text(encoding="utf-8")
target = _CODEX_CONFIG_PATH
_write_text_atomic(target, text, "Codex config restore")
profile_target = _CODEX_PROFILE_CONFIG_PATH
removed_profile = False
if profile_target.exists():
profile_target.unlink()
removed_profile = True
return {"source": str(source), "target": str(target), "removed_profile": str(removed_profile)}
# ------------------------------------------------------------------ #
# Claude Code adapter #
# ------------------------------------------------------------------ #
def _backup_claude_settings_if_changed(settings_path: Path, new_text: str) -> Path | None:
return _backup_text_file_if_changed(
settings_path,
new_text,
backup_dir=_CLAUDE_BACKUP_DIR,
backup_stem="settings",
backup_suffix="json",
label="Claude Code settings",
)
def _latest_claude_backup_path() -> Path | None:
return _latest_backup_path(_CLAUDE_BACKUP_DIR, "settings", "json")
def _configure_claude(cfg: "SkillClawConfig") -> None:
"""Auto-configure Claude Code to use the SkillClaw proxy."""
settings_path = _CLAUDE_SETTINGS_PATH
api_key = cfg.proxy_api_key or "skillclaw"
base_url = f"http://127.0.0.1:{cfg.proxy_port}"
_prepare_external_skills_dir(_CLAUDE_SKILLS_DIR, "Claude Code")
data = _load_json_mapping(settings_path, "Claude Code")
env = data.get("env")
if not isinstance(env, dict):
env = {}
env["ANTHROPIC_BASE_URL"] = base_url
env["ANTHROPIC_AUTH_TOKEN"] = api_key
data["env"] = env
new_text = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_backup_claude_settings_if_changed(settings_path, new_text)
_write_text_atomic(settings_path, new_text, "Claude Code settings")
def inspect_claude_config(cfg: "SkillClawConfig") -> dict[str, object]:
"""Return a diagnostic snapshot of the local Claude Code integration state."""
settings_path = _CLAUDE_SETTINGS_PATH
expected_base_url = f"http://127.0.0.1:{cfg.proxy_port}"
expected_api_key = cfg.proxy_api_key or "skillclaw"
expected_skills_dir = _CLAUDE_SKILLS_DIR
configured_skillclaw_skills_dir = Path(
str(getattr(cfg, "skills_dir", "") or expected_skills_dir),
).expanduser()
data = _load_json_mapping(settings_path, "Claude Code")
env = data.get("env") if isinstance(data.get("env"), dict) else {}
configured_base_url = str(env.get("ANTHROPIC_BASE_URL", "") or "")
configured_token = str(env.get("ANTHROPIC_AUTH_TOKEN", "") or "")
configured_model = str(data.get("model", "") or "")
proxy_match = configured_base_url == expected_base_url and configured_token == expected_api_key
backup_path = _latest_claude_backup_path()
skills_dir_match = configured_skillclaw_skills_dir == expected_skills_dir
issues: list[str] = []
notes: list[str] = [
"Claude Code uses SkillClaw through `ANTHROPIC_BASE_URL` and"
" `ANTHROPIC_AUTH_TOKEN` in ~/.claude/settings.json.",
"Claude Code session boundaries fall back to proxy-side heuristics"
" because Claude Code does not send SkillClaw session headers.",
]
next_steps: list[str] = []
if not settings_path.exists():
issues.append("Claude Code settings are missing: ~/.claude/settings.json")
if not proxy_match:
issues.append("Claude Code is not pointing at the local SkillClaw proxy.")
next_steps.append("Start SkillClaw once with `claw_type=claude` so it can rewrite ~/.claude/settings.json.")
if not expected_skills_dir.is_dir():
issues.append(f"Claude Code skills directory is missing: {expected_skills_dir}")
next_steps.append(f"Create or prepare the Claude Code skills directory: {expected_skills_dir}")
if not skills_dir_match:
issues.append(
f"SkillClaw is configured to evolve skills in {configured_skillclaw_skills_dir}, "
f"but Claude Code reads skills from {expected_skills_dir}."
)
next_steps.append(f"Set `skills.dir` to {expected_skills_dir} when using the Claude Code integration.")
if not backup_path:
next_steps.append(
"Run SkillClaw once before relying on `skillclaw restore claude`, so a backup can be created."
)
return {
"status": "ok" if not issues else "warning",
"config_path": str(settings_path),
"config_exists": settings_path.exists(),
"integration_scope": "claude-only",
"configured_model": configured_model or "(unset)",
"expected_base_url": expected_base_url,
"configured_base_url": configured_base_url or "(unset)",
"configured_provider": "anthropic-env",
"proxy_match": proxy_match,
"expected_skills_dir": str(expected_skills_dir),
"skills_dir_exists": expected_skills_dir.is_dir(),
"skills_dir_mode": "claude-default" if skills_dir_match else "custom",
"configured_skillclaw_skills_dir": str(configured_skillclaw_skills_dir),
"latest_backup": str(backup_path) if backup_path else "(none)",
"session_boundary_mode": "proxy heuristics",
"issues": issues,
"notes": notes,
"next_steps": next_steps,
}
def restore_claude_config(backup_path: Path | None = None) -> dict[str, str]:
"""Restore ~/.claude/settings.json from the latest or a specified backup."""
source = Path(backup_path).expanduser() if backup_path is not None else _latest_claude_backup_path()
if source is None or not source.exists():
raise FileNotFoundError("No Claude Code backup found")
text = source.read_text(encoding="utf-8")
target = _CLAUDE_SETTINGS_PATH
_write_text_atomic(target, text, "Claude Code settings restore")
return {"source": str(source), "target": str(target)}
# ------------------------------------------------------------------ #
# OpenCode adapter #
# ------------------------------------------------------------------ #
def _backup_opencode_config_if_changed(config_path: Path, new_text: str) -> Path | None:
return _backup_text_file_if_changed(
config_path,
new_text,
backup_dir=_OPENCODE_BACKUP_DIR,
backup_stem="opencode",
backup_suffix="json",
label="OpenCode config",
)
def _latest_opencode_backup_path() -> Path | None:
return _latest_backup_path(_OPENCODE_BACKUP_DIR, "opencode", "json")
def _prepare_opencode_skills_dir(cfg: "SkillClawConfig") -> None:
target_dir = Path(str(getattr(cfg, "skills_dir", "") or _OPENCODE_SKILLS_DIR)).expanduser()
_prepare_external_skills_dir(target_dir, "OpenCode")
def _configure_opencode(cfg: "SkillClawConfig") -> None:
"""Auto-configure OpenCode to use the SkillClaw proxy."""
config_path = _OPENCODE_CONFIG_PATH
model_id = cfg.served_model_name or cfg.llm_model_id or "skillclaw-model"
api_key = cfg.proxy_api_key or "skillclaw"
base_url = f"http://127.0.0.1:{cfg.proxy_port}/v1"
_prepare_opencode_skills_dir(cfg)
data = _load_json_mapping(config_path, "OpenCode")
provider_block = data.get("provider")
if not isinstance(provider_block, dict):
provider_block = {}
data["provider"] = provider_block
provider_block["skillclaw"] = {
"api": "openai-completions",
"name": "SkillClaw",
"options": {
"apiKey": api_key,
"baseURL": base_url,
},
"models": {
model_id: {
"id": model_id,
"name": model_id,
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 32768,
"maxTokens": 8192,
}
},
}
data["model"] = f"skillclaw/{model_id}"