koi-handler 0.12.1__tar.gz → 0.12.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {koi_handler-0.12.1/src/koi_handler.egg-info → koi_handler-0.12.3}/PKG-INFO +1 -1
- {koi_handler-0.12.1 → koi_handler-0.12.3}/pyproject.toml +1 -1
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/listener.py +37 -10
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/mcp/server.py +0 -14
- koi_handler-0.12.3/src/koi/modules/loader.py +236 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/secrets_dump.py +284 -195
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/cli.py +46 -11
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/connect/__init__.py +4 -3
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/connect/base.py +18 -0
- koi_handler-0.12.3/src/koi/utils/connect/ntlm.py +109 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/connect/ssh.py +16 -0
- koi_handler-0.12.3/src/koi/utils/connect/winrm.py +222 -0
- koi_handler-0.12.3/src/koi/utils/connect/wsman.py +246 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/interact.py +9 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3/src/koi_handler.egg-info}/PKG-INFO +1 -1
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi_handler.egg-info/SOURCES.txt +3 -0
- koi_handler-0.12.1/src/koi/modules/loader.py +0 -87
- {koi_handler-0.12.1 → koi_handler-0.12.3}/LICENSE +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/setup.cfg +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/main.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/mcp/__init__.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/mcp/schema.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/blueprint.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/download.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/duplicate.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/get_processes.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/get_users.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/ligolo.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/network_enum.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/peas.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/populate_win.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/sharphound.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/ssh_persist.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/sysinfo.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/upload.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/upload64.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/wifi_enum.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/modules/winscalate.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/session.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/__init__.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/agent_payload.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/__init__.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/__main__.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/agent.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/packet.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/proxy.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/stack.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/tcp.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/transport.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/engine/tun.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/tunnel/manager.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/__init__.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/bash_obfuscate.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/cache.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/config.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/config_ui.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/constants.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/detect.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/logger.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/models.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/obfuscate_ui.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/payloads.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/powerupgrade.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/ps_obfuscate.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/tcp.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/terminal.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/tls.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi/utils/ui.py +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi_handler.egg-info/dependency_links.txt +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi_handler.egg-info/entry_points.txt +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi_handler.egg-info/requires.txt +0 -0
- {koi_handler-0.12.1 → koi_handler-0.12.3}/src/koi_handler.egg-info/top_level.txt +0 -0
|
@@ -28,7 +28,7 @@ from koi.utils.cli import (
|
|
|
28
28
|
SCREENABLE_SENTINEL,
|
|
29
29
|
TOGGLE_SENTINEL,
|
|
30
30
|
)
|
|
31
|
-
from koi.utils.connect import TRANSPORTS, get_transport
|
|
31
|
+
from koi.utils.connect import TRANSPORTS, TransportError, get_transport
|
|
32
32
|
from koi.utils.powerupgrade import upgrade_windows_conptyshell
|
|
33
33
|
from koi.utils.tls import server_context, is_tls_client_hello, try_tls_handshake, encrypt_payload
|
|
34
34
|
from koi.utils.interact import interact
|
|
@@ -588,18 +588,20 @@ class Listener:
|
|
|
588
588
|
if self.host not in ("0.0.0.0", "::", local_ip):
|
|
589
589
|
notify('warning', f"Listener is bound to {bold(self._mask_ip(self.host, 'local'))}, the callback goes elsewhere.")
|
|
590
590
|
notify('status', muted(f"Nothing accepts it: rebind with {bold('--host 0.0.0.0')}, or the payload is lost."))
|
|
591
|
-
if self.screenable_mode:
|
|
592
|
-
# The transport inherits the real stdout, so _MaskStream never sees its prompts.
|
|
591
|
+
if self.screenable_mode and not transport.direct:
|
|
593
592
|
notify('warning', f"{transport.name} writes straight to the terminal, its output is not masked.")
|
|
594
593
|
|
|
595
594
|
known = {s.id for s in self._snapshot()}
|
|
596
|
-
|
|
597
|
-
env = transport.env(target)
|
|
595
|
+
script = transport.remote_script(local_ip, self.port)
|
|
598
596
|
|
|
599
597
|
try:
|
|
600
|
-
returncode =
|
|
601
|
-
except FileNotFoundError:
|
|
602
|
-
|
|
598
|
+
returncode = transport.execute(target, script)
|
|
599
|
+
except FileNotFoundError as exc:
|
|
600
|
+
binary = getattr(exc, 'filename', None) or transport.name
|
|
601
|
+
notify('error', f"{accent(binary)} is not installed on this machine.")
|
|
602
|
+
return
|
|
603
|
+
except TransportError as exc:
|
|
604
|
+
notify('error', str(exc))
|
|
603
605
|
return
|
|
604
606
|
except KeyboardInterrupt:
|
|
605
607
|
print()
|
|
@@ -611,7 +613,8 @@ class Listener:
|
|
|
611
613
|
notify('error', f"{transport.name} failed ({reason}), payload not delivered.")
|
|
612
614
|
return
|
|
613
615
|
|
|
614
|
-
|
|
616
|
+
expect_ip = None if (host is None or transport.direct) else target_ip
|
|
617
|
+
landed = self._wait_for_callback(known, expect_ip)
|
|
615
618
|
if not landed:
|
|
616
619
|
notify('warning', f"No callback after {int(_CONNECT_WAIT)}s.")
|
|
617
620
|
notify('status', muted(
|
|
@@ -709,6 +712,8 @@ class Listener:
|
|
|
709
712
|
"logs": (self._cmd_logs, 0),
|
|
710
713
|
"modules": (self._cmd_modules, 0),
|
|
711
714
|
"reload": (self._cmd_reload, 0),
|
|
715
|
+
"import": (self._cmd_import, 1),
|
|
716
|
+
"unimport": (self._cmd_unimport, 1),
|
|
712
717
|
"go": (self._cmd_go, 1),
|
|
713
718
|
"upgrade": (self._cmd_upgrade, 1),
|
|
714
719
|
"encrypt": (self._cmd_encrypt, 1),
|
|
@@ -765,6 +770,28 @@ class Listener:
|
|
|
765
770
|
modules = load_modules(reload=True)
|
|
766
771
|
notify('info', f"Loaded {accent(str(len(modules)))} modules.")
|
|
767
772
|
|
|
773
|
+
def _cmd_import(self, path: Optional[str]) -> None:
|
|
774
|
+
if path is None:
|
|
775
|
+
notify('status', f"Usage: import {accent('<path>')}")
|
|
776
|
+
return
|
|
777
|
+
from koi.modules.loader import import_module
|
|
778
|
+
ok, msg = import_module(path)
|
|
779
|
+
if ok:
|
|
780
|
+
notify('success', f"Module {accent(msg)} imported.")
|
|
781
|
+
else:
|
|
782
|
+
notify('error', msg)
|
|
783
|
+
|
|
784
|
+
def _cmd_unimport(self, name: Optional[str]) -> None:
|
|
785
|
+
if name is None:
|
|
786
|
+
notify('status', f"Usage: unimport {accent('<name>')}")
|
|
787
|
+
return
|
|
788
|
+
from koi.modules.loader import unimport_module
|
|
789
|
+
ok, msg = unimport_module(name)
|
|
790
|
+
if ok:
|
|
791
|
+
notify('success', f"Module {accent(msg)} removed.")
|
|
792
|
+
else:
|
|
793
|
+
notify('error', msg)
|
|
794
|
+
|
|
768
795
|
def _cmd_upgrade(self, ref: str) -> None:
|
|
769
796
|
sess = self._require_alive_session(ref)
|
|
770
797
|
if sess is None:
|
|
@@ -932,7 +959,7 @@ class Listener:
|
|
|
932
959
|
print()
|
|
933
960
|
notify('info', f"Entering session {bold(alert(f'#{sid}'))} {plain(self._mask_ip(ip))}{muted(f':{port}')}")
|
|
934
961
|
if sess.os_type in ("windows_cmd", "windows_ps") and not sess.upgraded:
|
|
935
|
-
notify('status', muted('Ctrl+Z to background · line-by-line mode'))
|
|
962
|
+
notify('status', muted('Ctrl+Z to background · Ctrl+C interrupts remote · line-by-line mode'))
|
|
936
963
|
else:
|
|
937
964
|
notify('status', muted('Ctrl+Z to background · Ctrl+C sends SIGINT to remote'))
|
|
938
965
|
print()
|
|
@@ -42,7 +42,6 @@ _MAX_OUTPUT_BYTES = 256 * 1024
|
|
|
42
42
|
|
|
43
43
|
# MCP file transfers are confined here; a CLI operator stays unrestricted.
|
|
44
44
|
_DOWNLOAD_ROOT = Path.home() / ".koi" / "downloads"
|
|
45
|
-
_UPLOAD_ROOT = Path.home() / ".koi" / "uploads"
|
|
46
45
|
|
|
47
46
|
# Tools that mutate state or run code: never offered on a read-only connection.
|
|
48
47
|
_EXEC_ONLY_TOOLS = {"koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop"}
|
|
@@ -115,17 +114,6 @@ def _confine_download_output(client_value, remote_path: str) -> str:
|
|
|
115
114
|
return str(_DOWNLOAD_ROOT / (base or "download"))
|
|
116
115
|
|
|
117
116
|
|
|
118
|
-
def _confine_upload_source(client_value) -> str:
|
|
119
|
-
_UPLOAD_ROOT.mkdir(parents=True, exist_ok=True)
|
|
120
|
-
root = _UPLOAD_ROOT.resolve()
|
|
121
|
-
candidate = Path(str(client_value or ""))
|
|
122
|
-
if not candidate.is_absolute():
|
|
123
|
-
candidate = root / candidate
|
|
124
|
-
candidate = candidate.resolve()
|
|
125
|
-
if candidate != root and root not in candidate.parents:
|
|
126
|
-
raise ValueError(f"upload local_path must stay under {root}")
|
|
127
|
-
return str(candidate)
|
|
128
|
-
|
|
129
117
|
|
|
130
118
|
def _uptime(since: Optional[float]) -> Optional[str]:
|
|
131
119
|
if since is None:
|
|
@@ -606,8 +594,6 @@ class KoiMCPServer:
|
|
|
606
594
|
remote = safe_args.get("remote_path")
|
|
607
595
|
remote_str = " ".join(remote) if isinstance(remote, list) else str(remote or "")
|
|
608
596
|
safe_args["output"] = _confine_download_output(safe_args.get("output"), remote_str)
|
|
609
|
-
elif mod_name == "upload":
|
|
610
|
-
safe_args["local_path"] = _confine_upload_source(safe_args.get("local_path"))
|
|
611
597
|
argv = schema_to_argv(mod_cls, safe_args)
|
|
612
598
|
|
|
613
599
|
error: Optional[str] = None
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import importlib.util
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import pkgutil
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict, Optional, Type
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("koi.modules.loader")
|
|
16
|
+
|
|
17
|
+
_cache: Optional[Dict[str, Type]] = None
|
|
18
|
+
|
|
19
|
+
_MODULES_JSON = Path.home() / ".koi" / "modules.json"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _modules_dir() -> Path:
|
|
23
|
+
return Path(__file__).parent
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_external_paths() -> list[str]:
|
|
27
|
+
try:
|
|
28
|
+
data = json.loads(_MODULES_JSON.read_text())
|
|
29
|
+
if isinstance(data, list):
|
|
30
|
+
return [p for p in data if isinstance(p, str)]
|
|
31
|
+
except (OSError, json.JSONDecodeError):
|
|
32
|
+
pass
|
|
33
|
+
return []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _write_external_paths(paths: list[str]) -> None:
|
|
37
|
+
_MODULES_JSON.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
fd, tmp = tempfile.mkstemp(
|
|
39
|
+
dir=str(_MODULES_JSON.parent), prefix=".modules.", suffix=".tmp",
|
|
40
|
+
)
|
|
41
|
+
try:
|
|
42
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
43
|
+
f.write(json.dumps(paths, indent=2) + "\n")
|
|
44
|
+
os.replace(tmp, _MODULES_JSON)
|
|
45
|
+
except OSError:
|
|
46
|
+
try:
|
|
47
|
+
os.unlink(tmp)
|
|
48
|
+
except OSError:
|
|
49
|
+
pass
|
|
50
|
+
raise
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ext_mod_id(filepath: str) -> str:
|
|
54
|
+
return f"_koi_ext.{Path(filepath).resolve()}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load_external_file(filepath: str, koi_module_cls: type) -> Optional[type]:
|
|
58
|
+
mod_id = _ext_mod_id(filepath)
|
|
59
|
+
spec = importlib.util.spec_from_file_location(mod_id, filepath)
|
|
60
|
+
if spec is None or spec.loader is None:
|
|
61
|
+
return None
|
|
62
|
+
module = importlib.util.module_from_spec(spec)
|
|
63
|
+
try:
|
|
64
|
+
spec.loader.exec_module(module)
|
|
65
|
+
except Exception:
|
|
66
|
+
sys.modules.pop(mod_id, None)
|
|
67
|
+
raise
|
|
68
|
+
sys.modules[mod_id] = module
|
|
69
|
+
for _attr, obj in inspect.getmembers(module, inspect.isclass):
|
|
70
|
+
if (
|
|
71
|
+
issubclass(obj, koi_module_cls)
|
|
72
|
+
and obj is not koi_module_cls
|
|
73
|
+
and obj.__module__ == mod_id
|
|
74
|
+
):
|
|
75
|
+
return obj
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_modules(reload: bool = False) -> Dict[str, Type]:
|
|
80
|
+
global _cache
|
|
81
|
+
if _cache is not None and not reload:
|
|
82
|
+
return _cache
|
|
83
|
+
|
|
84
|
+
from koi.modules.blueprint import KoiModule
|
|
85
|
+
|
|
86
|
+
discovered: Dict[str, Type[KoiModule]] = {}
|
|
87
|
+
pkg_path = str(_modules_dir())
|
|
88
|
+
|
|
89
|
+
for finder, mod_name, _ in pkgutil.iter_modules([pkg_path]):
|
|
90
|
+
if mod_name.startswith("_") or mod_name in ("blueprint", "loader"):
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
full_name = f"koi.modules.{mod_name}"
|
|
94
|
+
try:
|
|
95
|
+
if full_name in sys.modules:
|
|
96
|
+
module = importlib.reload(sys.modules[full_name])
|
|
97
|
+
else:
|
|
98
|
+
module = importlib.import_module(full_name)
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
logger.warning(f"Could not import module {full_name!r}: {exc}")
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
for _attr_name, obj in inspect.getmembers(module, inspect.isclass):
|
|
104
|
+
if (
|
|
105
|
+
issubclass(obj, KoiModule)
|
|
106
|
+
and obj is not KoiModule
|
|
107
|
+
and obj.__module__ == full_name
|
|
108
|
+
):
|
|
109
|
+
key = obj.name
|
|
110
|
+
if key in discovered:
|
|
111
|
+
logger.warning(
|
|
112
|
+
f"Name collision: {full_name!r} and "
|
|
113
|
+
f"{discovered[key].__module__!r} both claim name {key!r}. "
|
|
114
|
+
"Keeping first one found."
|
|
115
|
+
)
|
|
116
|
+
continue
|
|
117
|
+
discovered[key] = obj
|
|
118
|
+
logger.debug(f"Loaded module {key!r} from {full_name!r}")
|
|
119
|
+
|
|
120
|
+
builtin_names = set(discovered)
|
|
121
|
+
|
|
122
|
+
external_paths = _read_external_paths()
|
|
123
|
+
dead: list[str] = []
|
|
124
|
+
for filepath in external_paths:
|
|
125
|
+
if not Path(filepath).is_file():
|
|
126
|
+
dead.append(filepath)
|
|
127
|
+
continue
|
|
128
|
+
try:
|
|
129
|
+
cls = _load_external_file(filepath, KoiModule)
|
|
130
|
+
except Exception as exc:
|
|
131
|
+
logger.warning(f"Could not load external module {filepath!r}: {exc}")
|
|
132
|
+
continue
|
|
133
|
+
if cls is None:
|
|
134
|
+
logger.warning(f"No KoiModule subclass found in {filepath!r}")
|
|
135
|
+
continue
|
|
136
|
+
key = cls.name
|
|
137
|
+
if key in builtin_names:
|
|
138
|
+
logger.warning(f"External {filepath!r} name {key!r} collides with built-in, skipped.")
|
|
139
|
+
continue
|
|
140
|
+
if key in discovered:
|
|
141
|
+
logger.warning(f"External {filepath!r} name {key!r} already loaded, skipped.")
|
|
142
|
+
continue
|
|
143
|
+
discovered[key] = cls
|
|
144
|
+
logger.debug(f"Loaded external module {key!r} from {filepath!r}")
|
|
145
|
+
|
|
146
|
+
if dead:
|
|
147
|
+
_write_external_paths([p for p in external_paths if p not in dead])
|
|
148
|
+
|
|
149
|
+
_cache = discovered
|
|
150
|
+
return discovered
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def import_module(path: str) -> tuple[bool, str]:
|
|
154
|
+
resolved = str(Path(path).resolve())
|
|
155
|
+
if not resolved.endswith(".py"):
|
|
156
|
+
return False, "File must be a .py file."
|
|
157
|
+
if not Path(resolved).is_file():
|
|
158
|
+
return False, f"File not found: {resolved}"
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
source = Path(resolved).read_text()
|
|
162
|
+
compile(source, resolved, "exec")
|
|
163
|
+
except SyntaxError as exc:
|
|
164
|
+
return False, f"Syntax error: {exc}"
|
|
165
|
+
|
|
166
|
+
from koi.modules.blueprint import KoiModule
|
|
167
|
+
try:
|
|
168
|
+
cls = _load_external_file(resolved, KoiModule)
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
return False, f"Import failed: {exc}"
|
|
171
|
+
if cls is None:
|
|
172
|
+
return False, "No KoiModule subclass found in file."
|
|
173
|
+
|
|
174
|
+
name = cls.name
|
|
175
|
+
if not name:
|
|
176
|
+
return False, "Module has no name attribute."
|
|
177
|
+
|
|
178
|
+
current = load_modules()
|
|
179
|
+
existing = current.get(name)
|
|
180
|
+
if existing:
|
|
181
|
+
if existing.__module__.startswith("koi.modules."):
|
|
182
|
+
return False, f"Name {name!r} collides with built-in module."
|
|
183
|
+
ext_path = existing.__module__.removeprefix("_koi_ext.")
|
|
184
|
+
if ext_path != resolved:
|
|
185
|
+
return False, f"Name {name!r} already taken by {ext_path}."
|
|
186
|
+
|
|
187
|
+
paths = _read_external_paths()
|
|
188
|
+
if resolved not in paths:
|
|
189
|
+
paths.append(resolved)
|
|
190
|
+
_write_external_paths(paths)
|
|
191
|
+
|
|
192
|
+
load_modules(reload=True)
|
|
193
|
+
return True, name
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def unimport_module(name: str) -> tuple[bool, str]:
|
|
197
|
+
current = load_modules()
|
|
198
|
+
cls = current.get(name)
|
|
199
|
+
if cls is None:
|
|
200
|
+
return False, f"No module named {name!r}."
|
|
201
|
+
if cls.__module__.startswith("koi.modules."):
|
|
202
|
+
return False, f"{name!r} is a built-in module."
|
|
203
|
+
|
|
204
|
+
paths = _read_external_paths()
|
|
205
|
+
ext_path = cls.__module__.removeprefix("_koi_ext.")
|
|
206
|
+
remaining = [p for p in paths if str(Path(p).resolve()) != ext_path]
|
|
207
|
+
if len(remaining) == len(paths):
|
|
208
|
+
return False, f"Could not find {name!r} in external modules registry."
|
|
209
|
+
_write_external_paths(remaining)
|
|
210
|
+
load_modules(reload=True)
|
|
211
|
+
return True, name
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def get_module(name: str) -> Optional[Type]:
|
|
215
|
+
return load_modules().get(name)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def collect_external_resources() -> list[dict]:
|
|
219
|
+
"""Collect the external resources every loaded module wants pre-cached.
|
|
220
|
+
|
|
221
|
+
Goes through ``resolve_external_resources()`` so a module can compute its
|
|
222
|
+
list dynamically. A failing resolver is skipped with a warning rather than
|
|
223
|
+
aborting the whole ``--local-prepare`` run.
|
|
224
|
+
"""
|
|
225
|
+
resources = []
|
|
226
|
+
for mod_cls in load_modules().values():
|
|
227
|
+
try:
|
|
228
|
+
module_resources = mod_cls.resolve_external_resources()
|
|
229
|
+
except Exception as exc:
|
|
230
|
+
logger.warning(
|
|
231
|
+
f"Could not resolve external resources for {mod_cls.__name__!r}: {exc}"
|
|
232
|
+
)
|
|
233
|
+
continue
|
|
234
|
+
if module_resources:
|
|
235
|
+
resources.extend(module_resources)
|
|
236
|
+
return resources
|