|
| 1 | +from typing import Dict, List, Optional, Union |
| 2 | + |
| 3 | +import sys |
| 4 | +import json |
| 5 | +import contextlib |
| 6 | +import io |
| 7 | +import traceback |
| 8 | +import uuid |
| 9 | + |
| 10 | +STDIN = sys.stdin |
| 11 | +STDOUT = sys.stdout |
| 12 | +STDERR = sys.stderr |
| 13 | +USER_GLOBALS = {} |
| 14 | + |
| 15 | + |
| 16 | +def send_message(msg: str): |
| 17 | + length_msg = len(msg) |
| 18 | + STDOUT.buffer.write(f"Content-Length: {length_msg}\r\n\r\n{msg}".encode(encoding="utf-8")) |
| 19 | + STDOUT.buffer.flush() |
| 20 | + |
| 21 | + |
| 22 | +def print_log(msg: str): |
| 23 | + send_message(json.dumps({"jsonrpc": "2.0", "method": "log", "params": msg})) |
| 24 | + |
| 25 | + |
| 26 | +def send_response(response: str, response_id: int): |
| 27 | + send_message(json.dumps({"jsonrpc": "2.0", "id": response_id, "result": response})) |
| 28 | + |
| 29 | + |
| 30 | +def send_request(params: Optional[Union[List, Dict]] = None): |
| 31 | + request_id = uuid.uuid4().hex |
| 32 | + if params is None: |
| 33 | + send_message(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": "input"})) |
| 34 | + else: |
| 35 | + send_message( |
| 36 | + json.dumps({"jsonrpc": "2.0", "id": request_id, "method": "input", "params": params}) |
| 37 | + ) |
| 38 | + return request_id |
| 39 | + |
| 40 | + |
| 41 | +original_input = input |
| 42 | + |
| 43 | + |
| 44 | +def custom_input(prompt=""): |
| 45 | + try: |
| 46 | + send_request({"prompt": prompt}) |
| 47 | + headers = get_headers() |
| 48 | + content_length = int(headers.get("Content-Length", 0)) |
| 49 | + |
| 50 | + if content_length: |
| 51 | + message_text = STDIN.read(content_length) |
| 52 | + message_json = json.loads(message_text) |
| 53 | + our_user_input = message_json["result"]["userInput"] |
| 54 | + return our_user_input |
| 55 | + except Exception: |
| 56 | + print_log(traceback.format_exc()) |
| 57 | + |
| 58 | + |
| 59 | +# Set input to our custom input |
| 60 | +USER_GLOBALS["input"] = custom_input |
| 61 | +input = custom_input |
| 62 | + |
| 63 | + |
| 64 | +def handle_response(request_id): |
| 65 | + while not STDIN.closed: |
| 66 | + try: |
| 67 | + headers = get_headers() |
| 68 | + content_length = int(headers.get("Content-Length", 0)) |
| 69 | + |
| 70 | + if content_length: |
| 71 | + message_text = STDIN.read(content_length) |
| 72 | + message_json = json.loads(message_text) |
| 73 | + our_user_input = message_json["result"]["userInput"] |
| 74 | + if message_json["id"] == request_id: |
| 75 | + send_response(our_user_input, message_json["id"]) |
| 76 | + elif message_json["method"] == "exit": |
| 77 | + sys.exit(0) |
| 78 | + |
| 79 | + except Exception: |
| 80 | + print_log(traceback.format_exc()) |
| 81 | + |
| 82 | + |
| 83 | +def exec_function(user_input): |
| 84 | + try: |
| 85 | + compile(user_input, "<stdin>", "eval") |
| 86 | + except SyntaxError: |
| 87 | + return exec |
| 88 | + return eval |
| 89 | + |
| 90 | + |
| 91 | +def execute(request, user_globals): |
| 92 | + str_output = CustomIO("<stdout>", encoding="utf-8") |
| 93 | + str_error = CustomIO("<stderr>", encoding="utf-8") |
| 94 | + |
| 95 | + with redirect_io("stdout", str_output): |
| 96 | + with redirect_io("stderr", str_error): |
| 97 | + str_input = CustomIO("<stdin>", encoding="utf-8", newline="\n") |
| 98 | + with redirect_io("stdin", str_input): |
| 99 | + exec_user_input(request["params"], user_globals) |
| 100 | + send_response(str_output.get_value(), request["id"]) |
| 101 | + |
| 102 | + |
| 103 | +def exec_user_input(user_input, user_globals): |
| 104 | + user_input = user_input[0] if isinstance(user_input, list) else user_input |
| 105 | + |
| 106 | + try: |
| 107 | + callable = exec_function(user_input) |
| 108 | + retval = callable(user_input, user_globals) |
| 109 | + if retval is not None: |
| 110 | + print(retval) |
| 111 | + except KeyboardInterrupt: |
| 112 | + print(traceback.format_exc()) |
| 113 | + except Exception: |
| 114 | + print(traceback.format_exc()) |
| 115 | + |
| 116 | + |
| 117 | +class CustomIO(io.TextIOWrapper): |
| 118 | + """Custom stream object to replace stdio.""" |
| 119 | + |
| 120 | + def __init__(self, name, encoding="utf-8", newline=None): |
| 121 | + self._buffer = io.BytesIO() |
| 122 | + self._custom_name = name |
| 123 | + super().__init__(self._buffer, encoding=encoding, newline=newline) |
| 124 | + |
| 125 | + def close(self): |
| 126 | + """Provide this close method which is used by some tools.""" |
| 127 | + # This is intentionally empty. |
| 128 | + |
| 129 | + def get_value(self) -> str: |
| 130 | + """Returns value from the buffer as string.""" |
| 131 | + self.seek(0) |
| 132 | + return self.read() |
| 133 | + |
| 134 | + |
| 135 | +@contextlib.contextmanager |
| 136 | +def redirect_io(stream: str, new_stream): |
| 137 | + """Redirect stdio streams to a custom stream.""" |
| 138 | + old_stream = getattr(sys, stream) |
| 139 | + setattr(sys, stream, new_stream) |
| 140 | + yield |
| 141 | + setattr(sys, stream, old_stream) |
| 142 | + |
| 143 | + |
| 144 | +def get_headers(): |
| 145 | + headers = {} |
| 146 | + while line := STDIN.readline().strip(): |
| 147 | + name, value = line.split(":", 1) |
| 148 | + headers[name] = value.strip() |
| 149 | + return headers |
| 150 | + |
| 151 | + |
| 152 | +if __name__ == "__main__": |
| 153 | + while not STDIN.closed: |
| 154 | + try: |
| 155 | + headers = get_headers() |
| 156 | + content_length = int(headers.get("Content-Length", 0)) |
| 157 | + |
| 158 | + if content_length: |
| 159 | + request_text = STDIN.read(content_length) |
| 160 | + request_json = json.loads(request_text) |
| 161 | + if request_json["method"] == "execute": |
| 162 | + execute(request_json, USER_GLOBALS) |
| 163 | + elif request_json["method"] == "exit": |
| 164 | + sys.exit(0) |
| 165 | + |
| 166 | + except Exception: |
| 167 | + print_log(traceback.format_exc()) |
0 commit comments