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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
"""

Tool Loader

Part of SOVEREIGN PYTHON LLM ENGINE



Auto-registers all available tools into the registry.

"""

from pathlib import Path
from .registry import ToolRegistry, ToolDefinition, RiskClass, ApprovalPolicy


# ==========================================
# FILESYSTEM TOOLS
# ==========================================

def register_filesystem_tools(registry: ToolRegistry) -> None:

    async def read_file(params: dict) -> dict:
        path = Path(params["path"])
        if not path.exists():
            return {"error": f"File not found: {path}"}
        try:
            content = path.read_text(encoding='utf-8')
            return {"content": content, "path": str(path), "size": len(content)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.read",
        version="1.0.0",
        title="Read File",
        description="Read contents of a file",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=5000,
        handler=read_file,
        tags=["filesystem", "read"]
    ))

    async def write_file(params: dict) -> dict:
        path = Path(params["path"])
        content = params["content"]
        try:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(content, encoding='utf-8')
            return {"success": True, "path": str(path), "bytes_written": len(content)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.write",
        version="1.0.0",
        title="Write File",
        description="Write content to a file",
        input_schema={
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "content": {"type": "string"}
            },
            "required": ["path", "content"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=10000,
        handler=write_file,
        tags=["filesystem", "write"]
    ))

    async def list_directory(params: dict) -> dict:
        path = Path(params["path"])
        if not path.exists():
            return {"error": f"Path not found: {path}"}
        if not path.is_dir():
            return {"error": f"Not a directory: {path}"}
        try:
            files = []
            for item in path.iterdir():
                files.append({
                    "name": item.name,
                    "path": str(item),
                    "is_dir": item.is_dir(),
                    "is_file": item.is_file(),
                    "size": item.stat().st_size if item.is_file() else 0
                })
            return {"files": files, "count": len(files), "path": str(path)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.list",
        version="1.0.0",
        title="List Directory",
        description="List files in a directory",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=5000,
        handler=list_directory,
        tags=["filesystem", "read"]
    ))

    async def delete_file(params: dict) -> dict:
        path = Path(params["path"])
        if not path.exists():
            return {"error": f"File not found: {path}"}
        try:
            path.unlink()
            return {"success": True, "path": str(path)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.delete",
        version="1.0.0",
        title="Delete File",
        description="Delete a file (irreversible)",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.DESTRUCTIVE_LOCAL,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=5000,
        handler=delete_file,
        tags=["filesystem", "delete"]
    ))

    async def move_file(params: dict) -> dict:
        import shutil
        src = Path(params["source"])
        dst = Path(params["destination"])
        if not src.exists():
            return {"error": f"Source not found: {src}"}
        try:
            dst.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(src), str(dst))
            return {"success": True, "source": str(src), "destination": str(dst)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.move",
        version="1.0.0",
        title="Move File",
        description="Move or rename a file",
        input_schema={
            "type": "object",
            "properties": {
                "source": {"type": "string"},
                "destination": {"type": "string"}
            },
            "required": ["source", "destination"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=5000,
        handler=move_file,
        tags=["filesystem", "write"]
    ))

    async def search_files(params: dict) -> dict:
        import fnmatch
        root = Path(params["path"])
        pattern = params["pattern"]
        recursive = params.get("recursive", True)

        if not root.exists():
            return {"error": f"Path not found: {root}"}

        try:
            matches = []
            glob_pattern = f"**/{pattern}" if recursive else pattern
            for match in root.glob(glob_pattern):
                matches.append({
                    "path": str(match),
                    "name": match.name,
                    "size": match.stat().st_size if match.is_file() else 0
                })
            return {"matches": matches, "count": len(matches)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="filesystem.search",
        version="1.0.0",
        title="Search Files",
        description="Search for files by pattern (e.g. '*.py', '*.json')",
        input_schema={
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "pattern": {"type": "string"},
                "recursive": {"type": "boolean", "default": True}
            },
            "required": ["path", "pattern"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=search_files,
        tags=["filesystem", "search"]
    ))


# ==========================================
# CODE TOOLS
# ==========================================

def register_code_tools(registry: ToolRegistry) -> None:

    async def execute_python(params: dict) -> dict:
        code = params["code"]
        try:
            import subprocess
            result = subprocess.run(
                ["python", "-c", code],
                capture_output=True,
                text=True,
                timeout=30
            )
            return {
                "stdout": result.stdout,
                "stderr": result.stderr,
                "returncode": result.returncode,
                "success": result.returncode == 0
            }
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="code.execute_python",
        version="1.0.0",
        title="Execute Python",
        description="Execute Python code in subprocess",
        input_schema={
            "type": "object",
            "properties": {"code": {"type": "string"}},
            "required": ["code"]
        },
        output_schema=None,
        risk_class=RiskClass.DESTRUCTIVE_LOCAL,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=True,
        timeout_ms=30000,
        handler=execute_python,
        tags=["code", "execution"]
    ))

    async def run_shell(params: dict) -> dict:
        import subprocess
        command = params["command"]
        cwd = params.get("cwd", None)
        try:
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                timeout=60,
                cwd=cwd
            )
            return {
                "stdout": result.stdout,
                "stderr": result.stderr,
                "returncode": result.returncode,
                "success": result.returncode == 0
            }
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="code.shell",
        version="1.0.0",
        title="Run Shell Command",
        description="Run a shell command",
        input_schema={
            "type": "object",
            "properties": {
                "command": {"type": "string"},
                "cwd": {"type": "string"}
            },
            "required": ["command"]
        },
        output_schema=None,
        risk_class=RiskClass.DESTRUCTIVE_LOCAL,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=True,
        timeout_ms=60000,
        handler=run_shell,
        tags=["code", "shell", "execution"]
    ))


# ==========================================
# GIT TOOLS
# ==========================================

def register_git_tools(registry: ToolRegistry) -> None:
    from .git.operations import (
        git_status_tool, git_commit_tool,
        git_push_tool, git_log_tool
    )
    from .git.operations import GitOperations

    async def git_status(params: dict) -> dict:
        try:
            return await git_status_tool(params["repo_path"])
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.status",
        version="1.0.0",
        title="Git Status",
        description="Get git repository status (branch, modified, untracked files)",
        input_schema={
            "type": "object",
            "properties": {"repo_path": {"type": "string"}},
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_status,
        tags=["git", "read"]
    ))

    async def git_diff(params: dict) -> dict:
        try:
            git = GitOperations(Path(params["repo_path"]))
            diff = await git.diff(params.get("file_path"))
            return {"diff": diff}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.diff",
        version="1.0.0",
        title="Git Diff",
        description="Show changes in working directory",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "file_path": {"type": "string"}
            },
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_diff,
        tags=["git", "read"]
    ))

    async def git_log(params: dict) -> dict:
        try:
            return await git_log_tool(params["repo_path"], params.get("max_count", 10))
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.log",
        version="1.0.0",
        title="Git Log",
        description="Get commit history",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "max_count": {"type": "integer", "default": 10}
            },
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_log,
        tags=["git", "read"]
    ))

    async def git_commit(params: dict) -> dict:
        try:
            return await git_commit_tool(
                params["repo_path"],
                params["message"],
                params.get("files")
            )
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.commit",
        version="1.0.0",
        title="Git Commit",
        description="Stage files and create a commit",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "message": {"type": "string"},
                "files": {"type": "array", "items": {"type": "string"}}
            },
            "required": ["repo_path", "message"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=15000,
        handler=git_commit,
        tags=["git", "write"]
    ))

    async def git_push(params: dict) -> dict:
        try:
            return await git_push_tool(params["repo_path"], params.get("remote", "origin"))
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.push",
        version="1.0.0",
        title="Git Push",
        description="Push commits to remote repository",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "remote": {"type": "string", "default": "origin"}
            },
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_REMOTE_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=30000,
        handler=git_push,
        tags=["git", "write", "remote"]
    ))

    async def git_pull(params: dict) -> dict:
        try:
            git = GitOperations(Path(params["repo_path"]))
            await git.pull(params.get("remote", "origin"), params.get("branch"))
            return {"success": True}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.pull",
        version="1.0.0",
        title="Git Pull",
        description="Pull commits from remote repository",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "remote": {"type": "string", "default": "origin"},
                "branch": {"type": "string"}
            },
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=30000,
        handler=git_pull,
        tags=["git", "write", "remote"]
    ))

    async def git_branch_list(params: dict) -> dict:
        try:
            git = GitOperations(Path(params["repo_path"]))
            branches = await git.branch_list()
            return {"branches": branches}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.branch_list",
        version="1.0.0",
        title="List Git Branches",
        description="List all branches in repository",
        input_schema={
            "type": "object",
            "properties": {"repo_path": {"type": "string"}},
            "required": ["repo_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_branch_list,
        tags=["git", "read"]
    ))

    async def git_branch_create(params: dict) -> dict:
        try:
            git = GitOperations(Path(params["repo_path"]))
            await git.branch_create(params["name"], params.get("checkout", False))
            return {"success": True, "branch": params["name"]}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.branch_create",
        version="1.0.0",
        title="Create Git Branch",
        description="Create a new branch",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "name": {"type": "string"},
                "checkout": {"type": "boolean", "default": False}
            },
            "required": ["repo_path", "name"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_branch_create,
        tags=["git", "write"]
    ))

    async def git_checkout(params: dict) -> dict:
        try:
            git = GitOperations(Path(params["repo_path"]))
            await git.checkout(params["branch"])
            return {"success": True, "branch": params["branch"]}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.checkout",
        version="1.0.0",
        title="Git Checkout",
        description="Checkout a branch",
        input_schema={
            "type": "object",
            "properties": {
                "repo_path": {"type": "string"},
                "branch": {"type": "string"}
            },
            "required": ["repo_path", "branch"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=10000,
        handler=git_checkout,
        tags=["git", "write"]
    ))

    async def git_clone(params: dict) -> dict:
        try:
            from git import Repo
            import asyncio
            target = Path(params["target_path"])
            target.mkdir(parents=True, exist_ok=True)

            def _clone():
                Repo.clone_from(params["url"], target)

            await asyncio.to_thread(_clone)
            return {"success": True, "path": str(target)}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="git.clone",
        version="1.0.0",
        title="Git Clone",
        description="Clone a remote repository",
        input_schema={
            "type": "object",
            "properties": {
                "url": {"type": "string"},
                "target_path": {"type": "string"}
            },
            "required": ["url", "target_path"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=60000,
        handler=git_clone,
        tags=["git", "write", "remote"]
    ))


# ==========================================
# DATABASE TOOLS
# ==========================================

def register_database_tools(registry: ToolRegistry) -> None:
    from .database.sqlite import sqlite_query_tool, sqlite_execute_tool

    async def sqlite_query(params: dict) -> dict:
        try:
            return await sqlite_query_tool(
                params["db_path"],
                params["sql"],
                params.get("params")
            )
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="database.sqlite_query",
        version="1.0.0",
        title="SQLite Query",
        description="Execute a SELECT query on a SQLite database",
        input_schema={
            "type": "object",
            "properties": {
                "db_path": {"type": "string"},
                "sql": {"type": "string"},
                "params": {"type": "array"}
            },
            "required": ["db_path", "sql"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=15000,
        handler=sqlite_query,
        tags=["database", "sqlite", "read"]
    ))

    async def sqlite_execute(params: dict) -> dict:
        try:
            return await sqlite_execute_tool(
                params["db_path"],
                params["sql"],
                params.get("params")
            )
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="database.sqlite_execute",
        version="1.0.0",
        title="SQLite Execute",
        description="Execute an INSERT/UPDATE/DELETE on a SQLite database",
        input_schema={
            "type": "object",
            "properties": {
                "db_path": {"type": "string"},
                "sql": {"type": "string"},
                "params": {"type": "array"}
            },
            "required": ["db_path", "sql"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_LOCAL_WRITE,
        approval_policy=ApprovalPolicy.USER_CONFIRMATION,
        sandbox_required=False,
        timeout_ms=15000,
        handler=sqlite_execute,
        tags=["database", "sqlite", "write"]
    ))

    async def sqlite_list_tables(params: dict) -> dict:
        try:
            from .database.sqlite import SQLiteOperations
            ops = SQLiteOperations(Path(params["db_path"]))
            tables = await ops.list_tables()
            return {"tables": tables}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="database.sqlite_list_tables",
        version="1.0.0",
        title="SQLite List Tables",
        description="List all tables in a SQLite database",
        input_schema={
            "type": "object",
            "properties": {"db_path": {"type": "string"}},
            "required": ["db_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=5000,
        handler=sqlite_list_tables,
        tags=["database", "sqlite", "read"]
    ))


# ==========================================
# DOCUMENT TOOLS
# ==========================================

def register_document_tools(registry: ToolRegistry) -> None:

    async def parse_pdf(params: dict) -> dict:
        try:
            from .documents.pdf import PDFParser
            parser = PDFParser()
            doc = await parser.parse(Path(params["path"]))
            return {
                "text": doc.text,
                "pages": doc.pages,
                "metadata": doc.metadata
            }
        except ImportError:
            return {"error": "pypdf not installed. Run: pip install pypdf"}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="documents.parse_pdf",
        version="1.0.0",
        title="Parse PDF",
        description="Extract text and metadata from a PDF file",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=30000,
        handler=parse_pdf,
        tags=["documents", "pdf", "read"]
    ))

    async def parse_docx(params: dict) -> dict:
        try:
            from .documents.docx import DOCXParser
            parser = DOCXParser()
            doc = await parser.parse(Path(params["path"]))
            return {
                "text": doc.text,
                "paragraphs": doc.paragraphs,
                "metadata": doc.metadata
            }
        except ImportError:
            return {"error": "python-docx not installed. Run: pip install python-docx"}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="documents.parse_docx",
        version="1.0.0",
        title="Parse DOCX",
        description="Extract text from a Microsoft Word document",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=15000,
        handler=parse_docx,
        tags=["documents", "docx", "read"]
    ))

    async def parse_markdown(params: dict) -> dict:
        try:
            from .documents.markdown import MarkdownParser
            parser = MarkdownParser()
            doc = await parser.parse(Path(params["path"]))
            return {
                "text": doc.text,
                "sections": doc.sections,
                "links": doc.links,
                "code_blocks": doc.code_blocks,
                "metadata": doc.metadata
            }
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="documents.parse_markdown",
        version="1.0.0",
        title="Parse Markdown",
        description="Parse a Markdown file and extract sections, links, code blocks",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=parse_markdown,
        tags=["documents", "markdown", "read"]
    ))

    async def parse_html(params: dict) -> dict:
        try:
            from .documents.html import HTMLParser
            parser = HTMLParser()
            doc = await parser.parse(Path(params["path"]))
            return {
                "text": doc.text,
                "title": doc.title,
                "links": doc.links,
                "metadata": doc.metadata
            }
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="documents.parse_html",
        version="1.0.0",
        title="Parse HTML",
        description="Extract text and links from an HTML file",
        input_schema={
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=parse_html,
        tags=["documents", "html", "read"]
    ))


# ==========================================
# WEB TOOLS (decorator-based, auto-register on import)
# ==========================================

def register_web_tools(registry: ToolRegistry) -> None:
    # web.search, web.fetch, web.extract use @tool decorator
    # importing the module auto-registers them into the global registry
    # we then copy them into the provided registry
    try:
        import src.tools.web.search as _  # noqa: F401
        from .registry import get_global_registry
        global_reg = get_global_registry()
        for tool_id in ["web.search", "web.fetch", "web.extract"]:
            if global_reg.has(tool_id) and not registry.has(tool_id):
                registry.register(global_reg.get(tool_id))
    except ImportError as e:
        print(f"Note: web tools require httpx + beautifulsoup4: {e}")
    except Exception as e:
        print(f"Note: web tools skipped: {e}")


# ==========================================
# EMBEDDINGS TOOLS (decorator-based)
# ==========================================

def register_embeddings_tools(registry: ToolRegistry) -> None:
    try:
        import src.tools.embeddings.encode as _  # noqa: F401
        from .registry import get_global_registry
        global_reg = get_global_registry()
        for tool_id in ["embeddings.encode_text", "embeddings.similarity"]:
            if global_reg.has(tool_id) and not registry.has(tool_id):
                registry.register(global_reg.get(tool_id))
    except Exception as e:
        print(f"Note: embeddings tools skipped: {e}")


# ==========================================
# AUDIO TOOLS
# ==========================================

def register_audio_tools(registry: ToolRegistry) -> None:

    async def transcribe_audio(params: dict) -> dict:
        try:
            from .audio.transcribe import AudioTranscriber
            transcriber = AudioTranscriber(
                provider=params.get("provider", "openai"),
                model=params.get("model", "whisper-1")
            )
            result = await transcriber.transcribe(
                Path(params["audio_path"]),
                language=params.get("language")
            )
            return {
                "text": result.text,
                "language": result.language,
                "duration": result.duration
            }
        except ImportError:
            return {"error": "openai not installed. Run: pip install openai"}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="audio.transcribe",
        version="1.0.0",
        title="Transcribe Audio",
        description="Transcribe audio file to text using Whisper",
        input_schema={
            "type": "object",
            "properties": {
                "audio_path": {"type": "string"},
                "language": {"type": "string"},
                "provider": {"type": "string", "default": "openai"},
                "model": {"type": "string", "default": "whisper-1"}
            },
            "required": ["audio_path"]
        },
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_REMOTE,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=120000,
        handler=transcribe_audio,
        tags=["audio", "transcribe", "whisper"]
    ))

    async def synthesize_speech(params: dict) -> dict:
        try:
            from .audio.synthesize import AudioSynthesizer
            synth = AudioSynthesizer(provider=params.get("provider", "openai"))
            result = await synth.synthesize(
                text=params["text"],
                voice=params.get("voice", "alloy"),
                speed=params.get("speed", 1.0)
            )
            output_path = params.get("output_path", "output.mp3")
            Path(output_path).write_bytes(result.audio_bytes)
            return {"success": True, "output_path": output_path, "format": result.format}
        except ImportError:
            return {"error": "openai not installed. Run: pip install openai"}
        except Exception as e:
            return {"error": str(e)}

    registry.register(ToolDefinition(
        tool_id="audio.synthesize",
        version="1.0.0",
        title="Synthesize Speech",
        description="Convert text to speech (TTS)",
        input_schema={
            "type": "object",
            "properties": {
                "text": {"type": "string"},
                "voice": {"type": "string", "default": "alloy"},
                "speed": {"type": "number", "default": 1.0},
                "output_path": {"type": "string"},
                "provider": {"type": "string", "default": "openai"}
            },
            "required": ["text"]
        },
        output_schema=None,
        risk_class=RiskClass.REVERSIBLE_REMOTE_WRITE,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=60000,
        handler=synthesize_speech,
        tags=["audio", "tts", "speech"]
    ))


# ==========================================
# PYTORCH TOOLS
# ==========================================

def register_pytorch_tools(registry: ToolRegistry) -> None:
    from .ml.pytorch import tensor_operation, check_cuda

    async def pytorch_tensor_op(params: dict) -> dict:
        return await tensor_operation(params)

    registry.register(ToolDefinition(
        tool_id="pytorch.tensor_operation",
        version="1.0.0",
        title="PyTorch Tensor Operation",
        description="Execute PyTorch tensor operations (add, matmul, softmax, relu, etc)",
        input_schema={
            "type": "object",
            "properties": {
                "operation": {"type": "string"},
                "tensor_a": {"type": "array"},
                "tensor_b": {"type": "array"},
                "dim": {"type": "integer"}
            },
            "required": ["operation", "tensor_a"]
        },
        output_schema=None,
        risk_class=RiskClass.PURE_COMPUTATION,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=10000,
        handler=pytorch_tensor_op,
        tags=["pytorch", "ml", "tensor"]
    ))

    async def pytorch_cuda_check(params: dict) -> dict:
        return await check_cuda(params)

    registry.register(ToolDefinition(
        tool_id="pytorch.check_cuda",
        version="1.0.0",
        title="Check CUDA Availability",
        description="Check if CUDA is available and list GPU devices",
        input_schema={"type": "object", "properties": {}},
        output_schema=None,
        risk_class=RiskClass.READ_ONLY_LOCAL,
        approval_policy=ApprovalPolicy.AUTOMATIC,
        sandbox_required=False,
        timeout_ms=5000,
        handler=pytorch_cuda_check,
        tags=["pytorch", "ml", "cuda"]
    ))


# ==========================================
# MASTER LOADER
# ==========================================

def load_all_tools(registry: ToolRegistry) -> int:
    """

    Load all available tools into registry.



    Returns:

        Number of tools loaded

    """
    count_before = len(registry.tools)

    # Core tools — always available
    register_filesystem_tools(registry)
    register_code_tools(registry)

    # Git tools (requires gitpython)
    try:
        register_git_tools(registry)
    except ImportError:
        print("Note: gitpython not installed, skipping git.* tools. Run: pip install gitpython")

    # Database tools (stdlib sqlite3, always available)
    register_database_tools(registry)

    # Document tools (optional deps)
    register_document_tools(registry)

    # Web tools (requires httpx + beautifulsoup4)
    register_web_tools(registry)

    # Embeddings tools (optional)
    register_embeddings_tools(registry)

    # Audio tools (requires openai)
    register_audio_tools(registry)

    # PyTorch tools (optional)
    try:
        register_pytorch_tools(registry)
    except ImportError:
        print("Note: torch not installed, skipping pytorch.* tools. Run: pip install torch")

    count_after = len(registry.tools)
    loaded = count_after - count_before

    print(f"OK: Loaded {loaded} tools into registry")
    return loaded