python-repl-mcp 0.2.5__py3-none-any.whl
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.
- python_repl_mcp/__init__.py +5 -0
- python_repl_mcp/_helper.py +197 -0
- python_repl_mcp/_winjob.py +175 -0
- python_repl_mcp/config.py +84 -0
- python_repl_mcp/errors.py +63 -0
- python_repl_mcp/fileio.py +130 -0
- python_repl_mcp/kernel.py +724 -0
- python_repl_mcp/launcher.py +43 -0
- python_repl_mcp/opencode.py +195 -0
- python_repl_mcp/protocol.py +210 -0
- python_repl_mcp/server.py +318 -0
- python_repl_mcp/service.py +866 -0
- python_repl_mcp/worker.py +549 -0
- python_repl_mcp-0.2.5.dist-info/METADATA +218 -0
- python_repl_mcp-0.2.5.dist-info/RECORD +19 -0
- python_repl_mcp-0.2.5.dist-info/WHEEL +5 -0
- python_repl_mcp-0.2.5.dist-info/entry_points.txt +2 -0
- python_repl_mcp-0.2.5.dist-info/licenses/LICENSE +21 -0
- python_repl_mcp-0.2.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Bounded one-shot helper processes.
|
|
2
|
+
|
|
3
|
+
Both the OpenCode directory lookup and the ``repl_run_file`` preflight need the
|
|
4
|
+
same Windows-safe pattern: launch a fixed executable without a shell, cap its
|
|
5
|
+
output, keep an absolute deadline, and prove that the child exited before the
|
|
6
|
+
caller releases its admission permit. Only the argv and the error mapping
|
|
7
|
+
differ, so the mechanism lives here once.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import contextlib
|
|
14
|
+
import os
|
|
15
|
+
import subprocess # nosec B404
|
|
16
|
+
from collections.abc import Awaitable, Callable
|
|
17
|
+
from typing import Final
|
|
18
|
+
|
|
19
|
+
BASE_ENV: Final = (
|
|
20
|
+
"SYSTEMROOT",
|
|
21
|
+
"SYSTEMDRIVE",
|
|
22
|
+
"WINDIR",
|
|
23
|
+
"PATH",
|
|
24
|
+
"PATHEXT",
|
|
25
|
+
"COMSPEC",
|
|
26
|
+
"NUMBER_OF_PROCESSORS",
|
|
27
|
+
)
|
|
28
|
+
_DEFAULT_MAX_OUTPUT: Final = 256 * 1024
|
|
29
|
+
_DEFAULT_EXIT_SECONDS: Final = 5.0
|
|
30
|
+
|
|
31
|
+
type BeforePublish = Callable[[int], Awaitable[None]]
|
|
32
|
+
type BeforeExit = Callable[[], Awaitable[None]]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class HelperTimeout(Exception):
|
|
36
|
+
"""The operation deadline expired; the child has been terminated."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class HelperOutput(Exception):
|
|
40
|
+
"""The helper wrote more than its bounded output."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class HelperFailed(Exception):
|
|
44
|
+
"""The helper could not be started or did not report a usable exit."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ExitUnconfirmed(Exception):
|
|
48
|
+
"""The transport closed, but the helper's process exit was not observed."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def base_environment() -> dict[str, str]:
|
|
52
|
+
"""The Windows runtime the helpers need; never host credentials or proxies."""
|
|
53
|
+
wanted = {name.upper() for name in BASE_ENV}
|
|
54
|
+
return {name: value for name, value in os.environ.items() if name.upper() in wanted}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _remaining(deadline: float) -> float:
|
|
58
|
+
return deadline - asyncio.get_running_loop().time()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def run_helper(
|
|
62
|
+
argv: list[str],
|
|
63
|
+
*,
|
|
64
|
+
cwd: object,
|
|
65
|
+
env: dict[str, str],
|
|
66
|
+
deadline: float,
|
|
67
|
+
max_output: int = _DEFAULT_MAX_OUTPUT,
|
|
68
|
+
exit_seconds: float = _DEFAULT_EXIT_SECONDS,
|
|
69
|
+
before_publish: BeforePublish | None = None,
|
|
70
|
+
before_exit: BeforeExit | None = None,
|
|
71
|
+
) -> tuple[int, bytes]:
|
|
72
|
+
"""Run one bounded child and return its exit status and captured stdout.
|
|
73
|
+
|
|
74
|
+
The caller owns admission; this function owns the child from spawn through
|
|
75
|
+
confirmed exit. On cancellation it still terminates and confirms the child
|
|
76
|
+
before re-raising, so a permit is never released beside a live helper.
|
|
77
|
+
"""
|
|
78
|
+
if _remaining(deadline) <= 0:
|
|
79
|
+
raise HelperTimeout("the helper deadline expired before it started")
|
|
80
|
+
loop = asyncio.get_running_loop()
|
|
81
|
+
reply = _Reply(loop, max_output)
|
|
82
|
+
transport: asyncio.SubprocessTransport | None = None
|
|
83
|
+
try:
|
|
84
|
+
try:
|
|
85
|
+
transport, _ = await loop.subprocess_exec(
|
|
86
|
+
lambda: reply,
|
|
87
|
+
*argv,
|
|
88
|
+
cwd=str(cwd),
|
|
89
|
+
env=dict(env),
|
|
90
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
91
|
+
stdout=asyncio.subprocess.PIPE,
|
|
92
|
+
stderr=asyncio.subprocess.DEVNULL,
|
|
93
|
+
)
|
|
94
|
+
except (OSError, ValueError) as exc:
|
|
95
|
+
raise HelperFailed("the helper could not be started") from exc
|
|
96
|
+
process = transport.get_extra_info("subprocess")
|
|
97
|
+
if before_publish is not None and isinstance(process, subprocess.Popen):
|
|
98
|
+
# Test seam only: a publication barrier can outlive the deadline.
|
|
99
|
+
await before_publish(process.pid)
|
|
100
|
+
if _remaining(deadline) <= 0:
|
|
101
|
+
raise HelperTimeout("the helper deadline expired during startup")
|
|
102
|
+
try:
|
|
103
|
+
async with asyncio.timeout(max(0.0, _remaining(deadline))):
|
|
104
|
+
await asyncio.shield(reply.ready)
|
|
105
|
+
except TimeoutError as exc:
|
|
106
|
+
raise HelperTimeout("the helper did not finish before its deadline") from exc
|
|
107
|
+
if reply.overflow:
|
|
108
|
+
raise HelperOutput("the helper output exceeded its limit")
|
|
109
|
+
if _remaining(deadline) <= 0:
|
|
110
|
+
raise HelperTimeout("the helper deadline expired before its result was accepted")
|
|
111
|
+
status = transport.get_returncode()
|
|
112
|
+
if status is None:
|
|
113
|
+
raise HelperFailed("the helper exit was not observed")
|
|
114
|
+
return status, bytes(reply.output)
|
|
115
|
+
finally:
|
|
116
|
+
await _settle(transport, reply, exit_seconds, before_exit)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def _settle(
|
|
120
|
+
transport: asyncio.SubprocessTransport | None,
|
|
121
|
+
reply: _Reply,
|
|
122
|
+
exit_seconds: float,
|
|
123
|
+
before_exit: BeforeExit | None,
|
|
124
|
+
) -> None:
|
|
125
|
+
if transport is None:
|
|
126
|
+
return
|
|
127
|
+
process = transport.get_extra_info("subprocess")
|
|
128
|
+
if isinstance(process, subprocess.Popen) and process.poll() is None:
|
|
129
|
+
with contextlib.suppress(OSError):
|
|
130
|
+
process.kill()
|
|
131
|
+
if not transport.is_closing():
|
|
132
|
+
transport.close()
|
|
133
|
+
if before_exit is not None:
|
|
134
|
+
# Test seam: observe cancellation while the native exit is pending.
|
|
135
|
+
await before_exit()
|
|
136
|
+
if reply.closed.done():
|
|
137
|
+
return
|
|
138
|
+
waiter = asyncio.ensure_future(_wait_closed(reply, exit_seconds))
|
|
139
|
+
try:
|
|
140
|
+
await asyncio.shield(waiter)
|
|
141
|
+
except asyncio.CancelledError:
|
|
142
|
+
# A cancelled owner must still confirm (or report) the native exit.
|
|
143
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
144
|
+
await asyncio.shield(waiter)
|
|
145
|
+
raise
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def _wait_closed(reply: _Reply, exit_seconds: float) -> None:
|
|
149
|
+
try:
|
|
150
|
+
await asyncio.wait_for(asyncio.shield(reply.closed), exit_seconds)
|
|
151
|
+
except TimeoutError as exc:
|
|
152
|
+
raise ExitUnconfirmed("helper exit was not confirmed") from exc
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class _Reply(asyncio.SubprocessProtocol):
|
|
156
|
+
"""Bound the helper's output and close its pipes on every exit path."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, loop: asyncio.AbstractEventLoop, limit: int = _DEFAULT_MAX_OUTPUT) -> None:
|
|
159
|
+
self.output = bytearray()
|
|
160
|
+
self.overflow = False
|
|
161
|
+
self.ready: asyncio.Future[None] = loop.create_future()
|
|
162
|
+
self.closed: asyncio.Future[None] = loop.create_future()
|
|
163
|
+
self._limit = limit
|
|
164
|
+
self._lost = False
|
|
165
|
+
self._exited = False
|
|
166
|
+
|
|
167
|
+
def pipe_data_received(self, fd: int, data: bytes) -> None:
|
|
168
|
+
if self.overflow:
|
|
169
|
+
return
|
|
170
|
+
if len(self.output) + len(data) > self._limit:
|
|
171
|
+
self.overflow = True
|
|
172
|
+
self.ready.set_result(None)
|
|
173
|
+
else:
|
|
174
|
+
self.output.extend(data)
|
|
175
|
+
|
|
176
|
+
def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None:
|
|
177
|
+
if exc is not None:
|
|
178
|
+
self.overflow = True
|
|
179
|
+
self._lost = True
|
|
180
|
+
self._check_ready()
|
|
181
|
+
|
|
182
|
+
def process_exited(self) -> None:
|
|
183
|
+
self._exited = True
|
|
184
|
+
self._check_ready()
|
|
185
|
+
|
|
186
|
+
def connection_lost(self, exc: Exception | None) -> None:
|
|
187
|
+
if exc is not None:
|
|
188
|
+
self.overflow = True
|
|
189
|
+
self._lost = True
|
|
190
|
+
self._check_ready()
|
|
191
|
+
self.closed.set_result(None)
|
|
192
|
+
|
|
193
|
+
def _check_ready(self) -> None:
|
|
194
|
+
# The exit code is trustworthy only after both the pipe EOF and the
|
|
195
|
+
# process exit notification, whatever their order.
|
|
196
|
+
if self._lost and self._exited and not self.ready.done():
|
|
197
|
+
self.ready.set_result(None)
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Minimal Win32 Job Object ownership.
|
|
2
|
+
|
|
3
|
+
A job with ``KILL_ON_JOB_CLOSE`` is the only process-tree guarantee this server
|
|
4
|
+
offers on Windows. There is no weaker fallback: if the job cannot be created or
|
|
5
|
+
assigned, worker startup fails closed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ctypes
|
|
11
|
+
import sys
|
|
12
|
+
from ctypes import wintypes
|
|
13
|
+
from typing import Final
|
|
14
|
+
|
|
15
|
+
if sys.platform != "win32": # pragma: no cover - this server is Windows-only
|
|
16
|
+
raise ImportError("python_repl_mcp._winjob requires Windows")
|
|
17
|
+
|
|
18
|
+
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: Final = 0x0000_2000
|
|
19
|
+
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: Final = 9
|
|
20
|
+
_JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION: Final = 1
|
|
21
|
+
_PROCESS_SET_QUOTA: Final = 0x0100
|
|
22
|
+
_PROCESS_TERMINATE: Final = 0x0001
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _IoCounters(ctypes.Structure):
|
|
26
|
+
_fields_ = [
|
|
27
|
+
("ReadOperationCount", ctypes.c_ulonglong),
|
|
28
|
+
("WriteOperationCount", ctypes.c_ulonglong),
|
|
29
|
+
("OtherOperationCount", ctypes.c_ulonglong),
|
|
30
|
+
("ReadTransferCount", ctypes.c_ulonglong),
|
|
31
|
+
("WriteTransferCount", ctypes.c_ulonglong),
|
|
32
|
+
("OtherTransferCount", ctypes.c_ulonglong),
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _BasicLimitInformation(ctypes.Structure):
|
|
37
|
+
_fields_ = [
|
|
38
|
+
("PerProcessUserTimeLimit", wintypes.LARGE_INTEGER),
|
|
39
|
+
("PerJobUserTimeLimit", wintypes.LARGE_INTEGER),
|
|
40
|
+
("LimitFlags", wintypes.DWORD),
|
|
41
|
+
("MinimumWorkingSetSize", ctypes.c_size_t),
|
|
42
|
+
("MaximumWorkingSetSize", ctypes.c_size_t),
|
|
43
|
+
("ActiveProcessLimit", wintypes.DWORD),
|
|
44
|
+
("Affinity", ctypes.c_size_t),
|
|
45
|
+
("PriorityClass", wintypes.DWORD),
|
|
46
|
+
("SchedulingClass", wintypes.DWORD),
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _BasicAccountingInformation(ctypes.Structure):
|
|
51
|
+
_fields_ = [
|
|
52
|
+
("TotalUserTime", wintypes.LARGE_INTEGER),
|
|
53
|
+
("TotalKernelTime", wintypes.LARGE_INTEGER),
|
|
54
|
+
("ThisPeriodTotalUserTime", wintypes.LARGE_INTEGER),
|
|
55
|
+
("ThisPeriodTotalKernelTime", wintypes.LARGE_INTEGER),
|
|
56
|
+
("TotalPageFaultCount", wintypes.DWORD),
|
|
57
|
+
("TotalProcesses", wintypes.DWORD),
|
|
58
|
+
("ActiveProcesses", wintypes.DWORD),
|
|
59
|
+
("TotalTerminatedProcesses", wintypes.DWORD),
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _ExtendedLimitInformation(ctypes.Structure):
|
|
64
|
+
_fields_ = [
|
|
65
|
+
("BasicLimitInformation", _BasicLimitInformation),
|
|
66
|
+
("IoInfo", _IoCounters),
|
|
67
|
+
("ProcessMemoryLimit", ctypes.c_size_t),
|
|
68
|
+
("JobMemoryLimit", ctypes.c_size_t),
|
|
69
|
+
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
|
70
|
+
("PeakJobMemoryUsed", ctypes.c_size_t),
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
75
|
+
|
|
76
|
+
_kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
|
|
77
|
+
_kernel32.CreateJobObjectW.restype = wintypes.HANDLE
|
|
78
|
+
_kernel32.SetInformationJobObject.argtypes = [
|
|
79
|
+
wintypes.HANDLE,
|
|
80
|
+
ctypes.c_int,
|
|
81
|
+
ctypes.c_void_p,
|
|
82
|
+
wintypes.DWORD,
|
|
83
|
+
]
|
|
84
|
+
_kernel32.SetInformationJobObject.restype = wintypes.BOOL
|
|
85
|
+
_kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
|
86
|
+
_kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
|
|
87
|
+
_kernel32.TerminateJobObject.argtypes = [wintypes.HANDLE, wintypes.UINT]
|
|
88
|
+
_kernel32.TerminateJobObject.restype = wintypes.BOOL
|
|
89
|
+
_kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
|
90
|
+
_kernel32.OpenProcess.restype = wintypes.HANDLE
|
|
91
|
+
_kernel32.QueryInformationJobObject.argtypes = [
|
|
92
|
+
wintypes.HANDLE,
|
|
93
|
+
ctypes.c_int,
|
|
94
|
+
ctypes.c_void_p,
|
|
95
|
+
wintypes.DWORD,
|
|
96
|
+
ctypes.POINTER(wintypes.DWORD),
|
|
97
|
+
]
|
|
98
|
+
_kernel32.QueryInformationJobObject.restype = wintypes.BOOL
|
|
99
|
+
_kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
100
|
+
_kernel32.CloseHandle.restype = wintypes.BOOL
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class JobError(OSError):
|
|
104
|
+
"""A Win32 job operation failed; startup must not continue."""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _raise_last_error(operation: str) -> JobError:
|
|
108
|
+
code = ctypes.get_last_error()
|
|
109
|
+
return JobError(code, f"{operation} failed (WinError {code})")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Job:
|
|
113
|
+
"""A non-inheritable job that kills every member when its handle closes."""
|
|
114
|
+
|
|
115
|
+
def __init__(self) -> None:
|
|
116
|
+
handle = _kernel32.CreateJobObjectW(None, None)
|
|
117
|
+
if not handle:
|
|
118
|
+
raise _raise_last_error("CreateJobObjectW")
|
|
119
|
+
self._handle: int | None = int(handle)
|
|
120
|
+
try:
|
|
121
|
+
info = _ExtendedLimitInformation()
|
|
122
|
+
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
123
|
+
if not _kernel32.SetInformationJobObject(
|
|
124
|
+
handle,
|
|
125
|
+
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
|
126
|
+
ctypes.byref(info),
|
|
127
|
+
ctypes.sizeof(info),
|
|
128
|
+
):
|
|
129
|
+
raise _raise_last_error("SetInformationJobObject")
|
|
130
|
+
except BaseException:
|
|
131
|
+
self.close()
|
|
132
|
+
raise
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def closed(self) -> bool:
|
|
136
|
+
return self._handle is None
|
|
137
|
+
|
|
138
|
+
def assign(self, pid: int) -> None:
|
|
139
|
+
"""Assign ``pid`` and release the temporary process handle immediately."""
|
|
140
|
+
if self._handle is None:
|
|
141
|
+
raise JobError("job is closed")
|
|
142
|
+
process = _kernel32.OpenProcess(_PROCESS_SET_QUOTA | _PROCESS_TERMINATE, False, pid)
|
|
143
|
+
if not process:
|
|
144
|
+
raise _raise_last_error("OpenProcess")
|
|
145
|
+
try:
|
|
146
|
+
if not _kernel32.AssignProcessToJobObject(self._handle, process):
|
|
147
|
+
raise _raise_last_error("AssignProcessToJobObject")
|
|
148
|
+
finally:
|
|
149
|
+
_kernel32.CloseHandle(process)
|
|
150
|
+
|
|
151
|
+
def active_processes(self) -> int:
|
|
152
|
+
"""Live processes still assigned to the job, including descendants."""
|
|
153
|
+
if self._handle is None:
|
|
154
|
+
return 0
|
|
155
|
+
info = _BasicAccountingInformation()
|
|
156
|
+
if not _kernel32.QueryInformationJobObject(
|
|
157
|
+
self._handle,
|
|
158
|
+
_JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION,
|
|
159
|
+
ctypes.byref(info),
|
|
160
|
+
ctypes.sizeof(info),
|
|
161
|
+
None,
|
|
162
|
+
):
|
|
163
|
+
raise _raise_last_error("QueryInformationJobObject")
|
|
164
|
+
return int(info.ActiveProcesses)
|
|
165
|
+
|
|
166
|
+
def terminate(self) -> None:
|
|
167
|
+
if self._handle is None:
|
|
168
|
+
return
|
|
169
|
+
_kernel32.TerminateJobObject(self._handle, 1)
|
|
170
|
+
|
|
171
|
+
def close(self) -> None:
|
|
172
|
+
if self._handle is None:
|
|
173
|
+
return
|
|
174
|
+
handle, self._handle = self._handle, None
|
|
175
|
+
_kernel32.CloseHandle(handle)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Validated runtime settings.
|
|
2
|
+
|
|
3
|
+
The limits are initial defaults and are not a measured capacity claim.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
from collections.abc import Awaitable, Callable
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Final
|
|
15
|
+
|
|
16
|
+
from python_repl_mcp.opencode import OpenCode
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING: # pragma: no cover - type-only import avoids a runtime cycle
|
|
19
|
+
from python_repl_mcp.kernel import Kernel
|
|
20
|
+
|
|
21
|
+
WORKDIR_ENV: Final = "PYTHON_REPL_MCP_WORKDIR"
|
|
22
|
+
SESSION_ENV: Final = "PYTHON_REPL_MCP_SESSION"
|
|
23
|
+
IDLE_ENV: Final = "PYTHON_REPL_MCP_IDLE_TIMEOUT"
|
|
24
|
+
DEFAULT_SESSION: Final = "default"
|
|
25
|
+
MAX_SESSION_ID_CHARS: Final = 512
|
|
26
|
+
DEFAULT_IDLE_SECONDS: Final = 30.0 * 60.0
|
|
27
|
+
|
|
28
|
+
AfterSpawnHook = Callable[["Kernel"], Awaitable[None]]
|
|
29
|
+
BeforeConfirmExitHook = Callable[["Kernel"], Awaitable[None]]
|
|
30
|
+
BeforeTransportPublishHook = Callable[["Kernel", asyncio.SubprocessTransport], Awaitable[None]]
|
|
31
|
+
BeforeHelperPublishHook = Callable[[int], Awaitable[None]]
|
|
32
|
+
BeforeHelperExitHook = Callable[[], Awaitable[None]]
|
|
33
|
+
ExecutionWaitingHook = Callable[[str], Awaitable[None]]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class Hooks:
|
|
38
|
+
"""Narrow test seams; production configuration never sets them."""
|
|
39
|
+
|
|
40
|
+
after_spawn: AfterSpawnHook | None = None
|
|
41
|
+
before_transport_publish: BeforeTransportPublishHook | None = None
|
|
42
|
+
before_confirm_exit: BeforeConfirmExitHook | None = None
|
|
43
|
+
before_helper_publish: BeforeHelperPublishHook | None = None
|
|
44
|
+
before_helper_exit: BeforeHelperExitHook | None = None
|
|
45
|
+
execution_waiting: ExecutionWaitingHook | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True)
|
|
49
|
+
class Config:
|
|
50
|
+
workdir: Path
|
|
51
|
+
session_id: str | None = None
|
|
52
|
+
max_sessions: int = 16
|
|
53
|
+
handshake_timeout: float = 15.0
|
|
54
|
+
default_timeout: float = 30.0
|
|
55
|
+
max_timeout: float = 600.0
|
|
56
|
+
cleanup_timeout: float = 5.0
|
|
57
|
+
idle_timeout: float = DEFAULT_IDLE_SECONDS
|
|
58
|
+
hooks: Hooks | None = field(default=None)
|
|
59
|
+
opencode: OpenCode | None = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def load_config() -> Config:
|
|
63
|
+
raw = os.environ.get(WORKDIR_ENV)
|
|
64
|
+
workdir = Path(raw) if raw else Path.cwd()
|
|
65
|
+
if not workdir.is_dir():
|
|
66
|
+
raise ValueError(f"{WORKDIR_ENV} is not a directory: {workdir}")
|
|
67
|
+
session_id = os.environ.get(SESSION_ENV)
|
|
68
|
+
if session_id is not None and (not session_id or len(session_id) > MAX_SESSION_ID_CHARS):
|
|
69
|
+
raise ValueError(f"{SESSION_ENV} must be a nonempty string of at most {MAX_SESSION_ID_CHARS} characters")
|
|
70
|
+
idle_raw = os.environ.get(IDLE_ENV)
|
|
71
|
+
idle_timeout = DEFAULT_IDLE_SECONDS
|
|
72
|
+
if idle_raw is not None:
|
|
73
|
+
try:
|
|
74
|
+
idle_timeout = float(idle_raw)
|
|
75
|
+
except ValueError as exc:
|
|
76
|
+
raise ValueError(f"{IDLE_ENV} must be a number of seconds (0 disables idle eviction)") from exc
|
|
77
|
+
if not math.isfinite(idle_timeout) or idle_timeout < 0:
|
|
78
|
+
raise ValueError(f"{IDLE_ENV} must be a finite nonnegative number of seconds")
|
|
79
|
+
return Config(
|
|
80
|
+
workdir=workdir.resolve(),
|
|
81
|
+
session_id=session_id or None,
|
|
82
|
+
idle_timeout=idle_timeout,
|
|
83
|
+
opencode=OpenCode.from_environment(),
|
|
84
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Error taxonomy shared by the service and the MCP layer.
|
|
2
|
+
|
|
3
|
+
``ReplError`` instances become ``isError=true`` tool results; execution reports
|
|
4
|
+
are not exceptions and keep ``isError=false``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ReplError(Exception):
|
|
11
|
+
"""A tool-level failure: reported with ``isError=true``."""
|
|
12
|
+
|
|
13
|
+
code: str = "Error"
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, code: str | None = None) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.message = message
|
|
18
|
+
if code is not None:
|
|
19
|
+
self.code = code
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MissingSession(ReplError):
|
|
23
|
+
code = "MissingSession"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SessionDirectoryUnavailable(ReplError):
|
|
27
|
+
code = "SessionDirectoryUnavailable"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SessionBusy(ReplError):
|
|
31
|
+
code = "SessionBusy"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StaleWorker(ReplError):
|
|
35
|
+
code = "StaleWorker"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CapacityExceeded(ReplError):
|
|
39
|
+
code = "CapacityExceeded"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class FileError(ReplError):
|
|
43
|
+
code = "FileError"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class StartupFailed(ReplError):
|
|
47
|
+
code = "StartupFailed"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CleanupIncomplete(ReplError):
|
|
51
|
+
code = "CleanupIncomplete"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ShuttingDown(ReplError):
|
|
55
|
+
code = "ShuttingDown"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class KernelStartError(Exception):
|
|
59
|
+
"""Internal startup failure raised by the kernel."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class KernelNotReady(Exception):
|
|
63
|
+
"""The kernel cannot accept a cell."""
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Bounded, terminable script read for ``repl_run_file`` preflight.
|
|
2
|
+
|
|
3
|
+
The service validates sizes and UTF-8 *after* this read, before any worker is
|
|
4
|
+
started. Resolution and reading run in one isolated interpreter so a stalled
|
|
5
|
+
filesystem can be terminated; the file never executes there.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Final
|
|
14
|
+
|
|
15
|
+
from python_repl_mcp._helper import (
|
|
16
|
+
BeforeExit,
|
|
17
|
+
BeforePublish,
|
|
18
|
+
HelperFailed,
|
|
19
|
+
HelperOutput,
|
|
20
|
+
HelperTimeout,
|
|
21
|
+
base_environment,
|
|
22
|
+
run_helper,
|
|
23
|
+
)
|
|
24
|
+
from python_repl_mcp.errors import FileError
|
|
25
|
+
from python_repl_mcp.protocol import MAX_FRAME_BYTES
|
|
26
|
+
|
|
27
|
+
# ``data`` is capped with one extra byte; three BOM bytes may precede the code.
|
|
28
|
+
FILE_BYTES_LIMIT: Final = MAX_FRAME_BYTES + 3
|
|
29
|
+
# The reply body adds the resolved path to the script bytes.
|
|
30
|
+
_OUTPUT_LIMIT: Final = FILE_BYTES_LIMIT + 32 * 1024
|
|
31
|
+
_EXIT_SECONDS: Final = 5.0
|
|
32
|
+
# A stable local launch directory: the chat directory may be renamed while a
|
|
33
|
+
# warm worker keeps its namespace, and the script path is already absolute.
|
|
34
|
+
_LAUNCH_DIRECTORY: Final = Path(__file__).resolve().parent
|
|
35
|
+
_READ_CODE: Final = """
|
|
36
|
+
import os, sys
|
|
37
|
+
try:
|
|
38
|
+
raw, base, limit_text = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
39
|
+
limit = int(limit_text)
|
|
40
|
+
path = os.path.expanduser(raw)
|
|
41
|
+
if not os.path.isabs(path):
|
|
42
|
+
path = os.path.join(base, path)
|
|
43
|
+
import pathlib
|
|
44
|
+
path = str(pathlib.Path(path).resolve())
|
|
45
|
+
if not os.path.isfile(path):
|
|
46
|
+
raise SystemExit(4)
|
|
47
|
+
try:
|
|
48
|
+
with open(path, "rb") as handle:
|
|
49
|
+
data = handle.read(limit + 1)
|
|
50
|
+
except OSError:
|
|
51
|
+
raise SystemExit(2)
|
|
52
|
+
if len(data) > limit:
|
|
53
|
+
raise SystemExit(3)
|
|
54
|
+
encoded = os.fsencode(path)
|
|
55
|
+
os.write(1, len(encoded).to_bytes(4, "big") + encoded + data)
|
|
56
|
+
except SystemExit:
|
|
57
|
+
raise
|
|
58
|
+
except BaseException:
|
|
59
|
+
raise SystemExit(2)
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _python() -> str:
|
|
64
|
+
# The base interpreter avoids a venv redirector child for a short read.
|
|
65
|
+
return getattr(sys, "_base_executable", sys.executable)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def read_script(
|
|
69
|
+
file_path: str,
|
|
70
|
+
workdir: Path,
|
|
71
|
+
deadline: float,
|
|
72
|
+
before_publish: BeforePublish | None = None,
|
|
73
|
+
before_exit: BeforeExit | None = None,
|
|
74
|
+
) -> tuple[Path, str]:
|
|
75
|
+
"""Resolve and read one UTF-8 script outside the dispatcher process."""
|
|
76
|
+
status, output = await _run(file_path, workdir, deadline, before_publish, before_exit)
|
|
77
|
+
if status == 4:
|
|
78
|
+
raise FileError(f"file not found: {file_path}")
|
|
79
|
+
if status == 3:
|
|
80
|
+
raise FileError(f"file exceeds the private frame budget: {file_path}")
|
|
81
|
+
if status == 2:
|
|
82
|
+
raise FileError(f"could not read file: {file_path}")
|
|
83
|
+
if len(output) < 4:
|
|
84
|
+
raise FileError("the script read returned an invalid reply")
|
|
85
|
+
size = int.from_bytes(output[:4], "big")
|
|
86
|
+
if size <= 0 or size > len(output) - 4:
|
|
87
|
+
raise FileError("the script read returned an invalid reply")
|
|
88
|
+
path = Path(os.fsdecode(output[4 : 4 + size]))
|
|
89
|
+
try:
|
|
90
|
+
source = output[4 + size :].decode("utf-8-sig")
|
|
91
|
+
except UnicodeDecodeError as exc:
|
|
92
|
+
raise FileError(f"file is not valid UTF-8: {file_path}") from exc
|
|
93
|
+
return path, source
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def _run(
|
|
97
|
+
file_path: str,
|
|
98
|
+
workdir: Path,
|
|
99
|
+
deadline: float,
|
|
100
|
+
before_publish: BeforePublish | None,
|
|
101
|
+
before_exit: BeforeExit | None,
|
|
102
|
+
) -> tuple[int, bytes]:
|
|
103
|
+
argv = [
|
|
104
|
+
_python(),
|
|
105
|
+
"-I",
|
|
106
|
+
"-S",
|
|
107
|
+
"-B",
|
|
108
|
+
"-c",
|
|
109
|
+
_READ_CODE,
|
|
110
|
+
file_path,
|
|
111
|
+
str(workdir),
|
|
112
|
+
str(FILE_BYTES_LIMIT),
|
|
113
|
+
]
|
|
114
|
+
try:
|
|
115
|
+
return await run_helper(
|
|
116
|
+
argv,
|
|
117
|
+
cwd=_LAUNCH_DIRECTORY,
|
|
118
|
+
env=base_environment(),
|
|
119
|
+
deadline=deadline,
|
|
120
|
+
max_output=_OUTPUT_LIMIT,
|
|
121
|
+
exit_seconds=_EXIT_SECONDS,
|
|
122
|
+
before_publish=before_publish,
|
|
123
|
+
before_exit=before_exit,
|
|
124
|
+
)
|
|
125
|
+
except HelperTimeout as exc:
|
|
126
|
+
raise FileError("reading the script exceeded the file-preflight budget") from exc
|
|
127
|
+
except HelperOutput as exc:
|
|
128
|
+
raise FileError("the script read produced too much data") from exc
|
|
129
|
+
except HelperFailed as exc:
|
|
130
|
+
raise FileError("the script read did not report a usable result") from exc
|