Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

feat(CodeInterpreter): Convert messaging format to JSONRPC (#9226)

Isaac Miller98a11726abeb
diff --git a/dspy/primitives/code_interpreter.py b/dspy/primitives/code_interpreter.py
index 030503818..9eccb7960 100644
--- a/dspy/primitives/code_interpreter.py
+++ b/dspy/primitives/code_interpreter.py
@@ -14,10 +14,25 @@ SIMPLE_TYPES = (str, int, float, bool, list, dict, type(None))
class CodeInterpreterError(RuntimeError):
- """Error raised during code execution in an interpreter.
+ """Error raised during code interpretation.
- This covers runtime errors, undefined variables, tool call failures, etc.
- SyntaxError is raised separately for invalid Python syntax.
+ This exception covers two distinct failure modes:
+
+ 1. **Execution errors**: The sandbox ran user code that failed.
+ - NameError, TypeError, ValueError, etc.
+ - Tool call failures (unknown tool, tool raised exception)
+ - These are normal user code errors.
+
+ 2. **Protocol errors**: Communication between host and sandbox failed.
+ - Malformed JSON from sandbox
+ - Sandbox process crashed or became unresponsive
+ - Invalid JSON-RPC message structure
+ - These may indicate a corrupted sandbox needing restart.
+
+ The error message typically includes the original error type (e.g., "NameError: ...")
+ which can help distinguish the failure mode.
+
+ Note: SyntaxError is raised separately (not wrapped) for invalid Python syntax.
"""
diff --git a/dspy/primitives/python_interpreter.py b/dspy/primitives/python_interpreter.py
index 3136c4a08..830a59155 100644
--- a/dspy/primitives/python_interpreter.py
+++ b/dspy/primitives/python_interpreter.py
@@ -13,6 +13,7 @@ import keyword
import logging
import os
import subprocess
+import threading
from os import PathLike
from typing import Any, Callable
@@ -22,6 +23,57 @@ __all__ = ["PythonInterpreter", "FinalOutput", "CodeInterpreterError"]
logger = logging.getLogger(__name__)
+# =============================================================================
+# JSON-RPC 2.0 Helpers
+# =============================================================================
+
+# JSON-RPC 2.0 protocol errors (reserved range: -32700 to -32600)
+JSONRPC_PROTOCOL_ERRORS = {
+ "ParseError": -32700,
+ "InvalidRequest": -32600,
+ "MethodNotFound": -32601,
+}
+
+# Application errors (range: -32000 to -32099)
+JSONRPC_APP_ERRORS = {
+ "SyntaxError": -32000,
+ "NameError": -32001,
+ "TypeError": -32002,
+ "ValueError": -32003,
+ "AttributeError": -32004,
+ "IndexError": -32005,
+ "KeyError": -32006,
+ "RuntimeError": -32007,
+ "CodeInterpreterError": -32008,
+ "Unknown": -32099,
+}
+
+
+def _jsonrpc_request(method: str, params: dict, id: int | str) -> str:
+ """Create a JSON-RPC 2.0 request (expects response)."""
+ return json.dumps({"jsonrpc": "2.0", "method": method, "params": params, "id": id})
+
+
+def _jsonrpc_notification(method: str, params: dict | None = None) -> str:
+ """Create a JSON-RPC 2.0 notification (no response expected)."""
+ msg = {"jsonrpc": "2.0", "method": method}
+ if params:
+ msg["params"] = params
+ return json.dumps(msg)
+
+
+def _jsonrpc_result(result: Any, id: int | str) -> str:
+ """Create a JSON-RPC 2.0 success response."""
+ return json.dumps({"jsonrpc": "2.0", "result": result, "id": id})
+
+
+def _jsonrpc_error(code: int, message: str, id: int | str, data: dict | None = None) -> str:
+ """Create a JSON-RPC 2.0 error response."""
+ err = {"code": code, "message": message}
+ if data:
+ err["data"] = data
+ return json.dumps({"jsonrpc": "2.0", "error": err, "id": id})
+
class PythonInterpreter:
"""Local interpreter for secure Python execution using Deno and Pyodide.
@@ -125,6 +177,19 @@ class PythonInterpreter:
self.deno_process = None
self._mounted_files = False
+ self._request_id = 0
+ self._owner_thread: int | None = None
+
+ def _check_thread_ownership(self) -> None:
+ """Ensure this interpreter is only used from a single thread."""
+ current_thread = threading.current_thread().ident
+ if self._owner_thread is None:
+ self._owner_thread = current_thread
+ elif self._owner_thread != current_thread:
+ raise RuntimeError(
+ "PythonInterpreter is not thread-safe and cannot be shared across threads. "
+ "Create a separate interpreter instance for each thread."
+ )
@staticmethod
@functools.lru_cache(maxsize=1)
@@ -170,9 +235,19 @@ class PythonInterpreter:
else:
raise FileNotFoundError(f"Cannot mount non-existent file: {path}")
virtual_path = f"/sandbox/{os.path.basename(path)}"
- mount_msg = json.dumps({"mount_file": str(path), "virtual_path": virtual_path})
+ self._request_id += 1
+ request_id = self._request_id
+ mount_msg = _jsonrpc_request("mount_file", {"host_path": str(path), "virtual_path": virtual_path}, request_id)
self.deno_process.stdin.write(mount_msg + "\n")
self.deno_process.stdin.flush()
+ response_line = self.deno_process.stdout.readline().strip()
+ if not response_line:
+ raise CodeInterpreterError(f"No response when mounting file: {path}")
+ response = json.loads(response_line)
+ if response.get("id") != request_id:
+ raise CodeInterpreterError(f"Response ID mismatch when mounting: expected {request_id}, got {response.get('id')}")
+ if "error" in response:
+ raise CodeInterpreterError(f"Failed to mount {path}: {response['error'].get('message', 'Unknown error')}")
self._mounted_files = True
def _sync_files(self):
@@ -180,10 +255,7 @@ class PythonInterpreter:
return
for path in self.enable_write_paths:
virtual_path = f"/sandbox/{os.path.basename(path)}"
- sync_msg = json.dumps({
- "sync_file": virtual_path,
- "host_file": str(path)
- })
+ sync_msg = _jsonrpc_notification("sync_file", {"virtual_path": virtual_path, "host_path": str(path)})
self.deno_process.stdin.write(sync_msg + "\n")
self.deno_process.stdin.flush()
@@ -208,8 +280,8 @@ class PythonInterpreter:
if self._tools_registered:
return
- # Build registration message with typed tool signatures
- msg = {}
+ # Build registration params with typed tool signatures
+ params = {}
if self.tools:
tools_info = []
@@ -218,43 +290,52 @@ class PythonInterpreter:
"name": name,
"parameters": self._extract_parameters(fn)
})
- msg["register_tools"] = tools_info
+ params["tools"] = tools_info
if self.output_fields:
- msg["register_outputs"] = self.output_fields
+ params["outputs"] = self.output_fields
# Skip if nothing to register
- if not msg:
+ if not params:
self._tools_registered = True
return
- self.deno_process.stdin.write(json.dumps(msg) + "\n")
+ self._request_id += 1
+ request_id = self._request_id
+ register_msg = _jsonrpc_request("register", params, request_id)
+ self.deno_process.stdin.write(register_msg + "\n")
self.deno_process.stdin.flush()
response_line = self.deno_process.stdout.readline().strip()
if not response_line:
raise CodeInterpreterError("No response when registering tools/outputs")
response = json.loads(response_line)
- if "tools_registered" not in response and "outputs_registered" not in response:
+ if "result" not in response or response.get("id") != request_id:
raise CodeInterpreterError(f"Unexpected response when registering: {response_line}")
self._tools_registered = True
def _handle_tool_call(self, request: dict) -> None:
"""Handle a tool call request from the sandbox."""
- request_id, tool_name = request["id"], request["name"]
- call_args = request.get("args", {})
+ request_id = request["id"]
+ params = request.get("params", {})
+ tool_name = params.get("name")
+ args = params.get("args", [])
+ kwargs = params.get("kwargs", {})
try:
if tool_name not in self.tools:
raise CodeInterpreterError(f"Unknown tool: {tool_name}")
- result = self.tools[tool_name](*call_args.get("args", []), **call_args.get("kwargs", {}))
+ result = self.tools[tool_name](*args, **kwargs)
is_json = isinstance(result, (list, dict))
- response = {"type": "tool_response", "id": request_id, "error": None,
- "result": json.dumps(result) if is_json else str(result or ""),
- "result_type": "json" if is_json else "string"}
+ response = _jsonrpc_result(
+ {"value": json.dumps(result) if is_json else str(result or ""), "type": "json" if is_json else "string"},
+ request_id
+ )
except Exception as e:
- response = {"type": "tool_response", "id": request_id, "result": None, "error": str(e)}
+ error_type = type(e).__name__
+ error_code = JSONRPC_APP_ERRORS.get(error_type, JSONRPC_APP_ERRORS["Unknown"])
+ response = _jsonrpc_error(error_code, str(e), request_id, {"type": error_type})
- self.deno_process.stdin.write(json.dumps(response) + "\n")
+ self.deno_process.stdin.write(response + "\n")
self.deno_process.stdin.flush()
def _ensure_deno_process(self) -> None:
@@ -279,6 +360,21 @@ class PythonInterpreter:
"For additional configurations: https://docs.deno.com/runtime/getting_started/installation/"
)
raise CodeInterpreterError(install_instructions) from e
+ self._health_check()
+
+ def _health_check(self) -> None:
+ """Verify the subprocess is alive by executing a simple expression."""
+ self._request_id += 1
+ request_id = self._request_id
+ ping_msg = _jsonrpc_request("execute", {"code": "print(1+1)"}, request_id)
+ self.deno_process.stdin.write(ping_msg + "\n")
+ self.deno_process.stdin.flush()
+ response_line = self.deno_process.stdout.readline().strip()
+ if not response_line:
+ raise CodeInterpreterError("Subprocess not responding")
+ response = json.loads(response_line)
+ if response.get("result", {}).get("output", "").strip() != "2":
+ raise CodeInterpreterError(f"Unexpected ping response: {response_line}")
def _inject_variables(self, code: str, variables: dict[str, Any]) -> str:
"""Insert Python assignments for each variable at the top of the code."""
@@ -315,21 +411,26 @@ class PythonInterpreter:
code: str,
variables: dict[str, Any] | None = None,
) -> Any:
+ self._check_thread_ownership()
variables = variables or {}
code = self._inject_variables(code, variables)
self._ensure_deno_process()
self._mount_files()
self._register_tools()
- # Send the code as JSON
- input_data = json.dumps({"code": code})
+ # Send the code as JSON-RPC request
+ self._request_id += 1
+ execute_request_id = self._request_id
+ input_data = _jsonrpc_request("execute", {"code": code}, execute_request_id)
try:
self.deno_process.stdin.write(input_data + "\n")
self.deno_process.stdin.flush()
except BrokenPipeError:
# If the process died, restart and try again once
self._tools_registered = False
+ self._mounted_files = False
self._ensure_deno_process()
+ self._mount_files()
self._register_tools()
self.deno_process.stdin.write(input_data + "\n")
self.deno_process.stdin.flush()
@@ -345,34 +446,48 @@ class PythonInterpreter:
# Parse that line as JSON
try:
- result = json.loads(output_line)
+ msg = json.loads(output_line)
except json.JSONDecodeError:
# If not valid JSON, just return raw text
- result = {"output": output_line}
-
- # Handle tool call requests from sandbox
- if result.get("type") == "tool_call":
- self._handle_tool_call(result)
- continue
-
- # Handle errors based on errorType
- if "error" in result:
- error_msg = result["error"]
- error_type = result.get("errorType", "Sandbox Error")
- error_args = result.get("errorArgs", [])
-
- if error_type == "FinalOutput":
- output = error_args[0] if error_args else None
- self._sync_files()
- return FinalOutput(output)
- elif error_type == "SyntaxError":
- raise SyntaxError(f"Invalid Python syntax. message: {error_msg}")
+ self._sync_files()
+ return output_line
+
+ # Handle incoming requests (tool calls from sandbox)
+ if "method" in msg:
+ if msg["method"] == "tool_call":
+ self._handle_tool_call(msg)
+ continue
+
+ # Handle success response
+ if "result" in msg:
+ if msg.get("id") != execute_request_id:
+ raise CodeInterpreterError(f"Response ID mismatch: expected {execute_request_id}, got {msg.get('id')}")
+ result = msg["result"]
+ self._sync_files()
+ # Check for SUBMIT (encoded as success with "final" field)
+ if "final" in result:
+ return FinalOutput(result["final"])
+ return result.get("output", None)
+
+ # Handle error response
+ if "error" in msg:
+ # Errors with id=null are unsolicited errors (e.g., unhandled async rejections)
+ # Treat them as errors for the current request
+ if msg.get("id") is not None and msg.get("id") != execute_request_id:
+ raise CodeInterpreterError(f"Response ID mismatch: expected {execute_request_id}, got {msg.get('id')}")
+ error = msg["error"]
+ error_code = error.get("code", JSONRPC_APP_ERRORS["Unknown"])
+ error_message = error.get("message", "Unknown error")
+ error_data = error.get("data", {})
+ error_type = error_data.get("type", "Error")
+
+ if error_code == JSONRPC_APP_ERRORS["SyntaxError"]:
+ raise SyntaxError(f"Invalid Python syntax. message: {error_message}")
else:
- raise CodeInterpreterError(f"{error_type}: {error_args or error_msg}")
+ raise CodeInterpreterError(f"{error_type}: {error_data.get('args') or error_message}")
- # If there's no error or got `FinalAnswer`, return the "output" field
- self._sync_files()
- return result.get("output", None)
+ # Unexpected message format - neither a recognized method nor a response
+ raise CodeInterpreterError(f"Unexpected message format from sandbox: {msg}")
def start(self) -> None:
"""Initialize the Deno/Pyodide sandbox.
@@ -400,8 +515,9 @@ class PythonInterpreter:
def shutdown(self) -> None:
if self.deno_process and self.deno_process.poll() is None:
- self.deno_process.stdin.write(json.dumps({"shutdown": True}) + "\n")
+ self.deno_process.stdin.write(_jsonrpc_notification("shutdown") + "\n")
self.deno_process.stdin.flush()
self.deno_process.stdin.close()
self.deno_process.wait()
self.deno_process = None
+ self._owner_thread = None
diff --git a/dspy/primitives/runner.js b/dspy/primitives/runner.js
index b2dca376d..7fc79635e 100644
--- a/dspy/primitives/runner.js
+++ b/dspy/primitives/runner.js
@@ -96,14 +96,54 @@ def SUBMIT(${sigParts.join(', ')}):
`;
};
+// =============================================================================
+// JSON-RPC 2.0 Helpers
+// =============================================================================
+
+// JSON-RPC 2.0 protocol errors (reserved range: -32700 to -32600)
+const JSONRPC_PROTOCOL_ERRORS = {
+ ParseError: -32700,
+ InvalidRequest: -32600,
+ MethodNotFound: -32601,
+};
+
+// Application errors (range: -32000 to -32099)
+const JSONRPC_APP_ERRORS = {
+ SyntaxError: -32000,
+ NameError: -32001,
+ TypeError: -32002,
+ ValueError: -32003,
+ AttributeError: -32004,
+ IndexError: -32005,
+ KeyError: -32006,
+ RuntimeError: -32007,
+ CodeInterpreterError: -32008,
+ Unknown: -32099,
+};
+
+const jsonrpcRequest = (method, params, id) =>
+ JSON.stringify({ jsonrpc: "2.0", method, params, id });
+
+const jsonrpcNotification = (method, params = null) => {
+ const msg = { jsonrpc: "2.0", method };
+ if (params) msg.params = params;
+ return JSON.stringify(msg);
+};
+
+const jsonrpcResult = (result, id) =>
+ JSON.stringify({ jsonrpc: "2.0", result, id });
+
+const jsonrpcError = (code, message, id, data = null) => {
+ const err = { code, message };
+ if (data) err.data = data;
+ return JSON.stringify({ jsonrpc: "2.0", error: err, id });
+};
+
// Global handler to prevent uncaught promise rejections from crashing Deno
// These can occur during async Python <-> JS interop
globalThis.addEventListener("unhandledrejection", (event) => {
event.preventDefault();
- console.log(JSON.stringify({
- error: `Unhandled async error: ${event.reason?.message || event.reason}`,
- errorType: "UnhandledPromiseRejection"
- }));
+ console.log(jsonrpcError(JSONRPC_APP_ERRORS.RuntimeError, `Unhandled async error: ${event.reason?.message || event.reason}`, null));
});
const pyodide = await pyodideModule.loadPyodide();
@@ -115,16 +155,18 @@ let requestIdCounter = 0;
// This function is called from Python to invoke a host-side tool
async function toolCallBridge(name, argsJson) {
- const requestId = `req_${Date.now()}_${++requestIdCounter}`;
+ const requestId = `tc_${Date.now()}_${++requestIdCounter}`;
try {
- // Send tool call request to host
- console.log(JSON.stringify({
- type: "tool_call",
- id: requestId,
+ // Parse args to extract positional and keyword args
+ const parsedArgs = JSON.parse(argsJson);
+
+ // Send tool call request to host using JSON-RPC
+ console.log(jsonrpcRequest("tool_call", {
name: name,
- args: JSON.parse(argsJson)
- }));
+ args: parsedArgs.args || [],
+ kwargs: parsedArgs.kwargs || {}
+ }, requestId));
// Wait for response from host
const { value: responseLine, done } = await stdinReader.next();
@@ -133,19 +175,22 @@ async function toolCallBridge(name, argsJson) {
}
const response = JSON.parse(responseLine);
- if (response.type !== "tool_response" || response.id !== requestId) {
- throw new Error(`Unexpected response: expected tool_response with id ${requestId}`);
+
+ // Expect JSON-RPC result or error with matching id
+ if (response.id !== requestId) {
+ throw new Error(`Unexpected response: expected id ${requestId}, got ${response.id}`);
}
if (response.error) {
- throw new Error(response.error);
+ throw new Error(response.error.message || "Tool call failed");
}
// Deserialize result based on type
- if (response.result_type === "json") {
- return JSON.parse(response.result);
+ const result = response.result;
+ if (result.type === "json") {
+ return JSON.parse(result.value);
}
- return response.result;
+ return result.value;
} catch (error) {
// Re-throw with context so Python can catch it properly
throw new Error(`Tool bridge error for '${name}': ${error.message}`);
@@ -179,17 +224,39 @@ while (true) {
try {
input = JSON.parse(line);
} catch (error) {
- console.log(JSON.stringify({
- error: "Invalid JSON input: " + error.message,
- errorType: "ValueError"
- }));
+ // JSON-RPC parse error
+ console.log(jsonrpcError(JSONRPC_PROTOCOL_ERRORS.ParseError, "Invalid JSON input: " + error.message, null));
+ continue;
+ }
+
+ // Validate JSON-RPC format
+ if (typeof input !== 'object' || input === null || input.jsonrpc !== "2.0") {
+ console.log(jsonrpcError(JSONRPC_PROTOCOL_ERRORS.InvalidRequest, "Invalid Request: not a JSON-RPC 2.0 message", null));
continue;
}
- if (input.mount_file) {
- const virtualPath = input.virtual_path || input.mount_file;
+ const method = input.method;
+ const params = input.params || {};
+ const requestId = input.id; // May be undefined for notifications
+
+ // Handle notifications (no response expected)
+ if (method === "sync_file") {
try {
- const contents = await Deno.readFile(input.mount_file);
+ const virtualPath = params.virtual_path;
+ const hostPath = params.host_path || virtualPath;
+ await Deno.writeFile(hostPath, pyodide.FS.readFile(virtualPath));
+ } catch (e) { /* ignore sync errors */ }
+ continue;
+ }
+
+ if (method === "shutdown") break;
+
+ // Handle requests (expect response)
+ if (method === "mount_file") {
+ const hostPath = params.host_path;
+ const virtualPath = params.virtual_path || hostPath;
+ try {
+ const contents = await Deno.readFile(hostPath);
const dirs = virtualPath.split('/').slice(1, -1);
let cur = '';
for (const d of dirs) {
@@ -203,33 +270,19 @@ while (true) {
}
}
pyodide.FS.writeFile(virtualPath, contents);
+ console.log(jsonrpcResult({ mounted: virtualPath }, requestId));
} catch (e) {
- console.log(JSON.stringify({error: "Failed to mount file: " + e.message}));
+ console.log(jsonrpcError(JSONRPC_APP_ERRORS.RuntimeError, `Failed to mount file: ${e.message}`, requestId));
}
continue;
}
- if (input.sync_file) {
- try {
- await Deno.writeFile(input.host_file || input.sync_file, pyodide.FS.readFile(input.sync_file));
- } catch (e) { /* ignore sync errors */ }
- continue;
- }
-
- if (typeof input !== 'object' || input === null) {
- console.log(JSON.stringify({ error: "Input is not a JSON object", errorType: "ValueError" }));
- continue;
- }
-
- if (input.shutdown) break;
-
- // Register tools and/or output fields
- if (input.register_tools || input.register_outputs) {
+ if (method === "register") {
const toolNames = [];
// Register tools with typed signatures
- if (input.register_tools) {
- for (const tool of input.register_tools) {
+ if (params.tools) {
+ for (const tool of params.tools) {
// Support both old format (string) and new format (object with parameters)
if (typeof tool === 'string') {
pyodide.runPython(makeToolWrapper(tool, []));
@@ -242,47 +295,77 @@ while (true) {
}
// Register SUBMIT with output signature
- if (input.register_outputs) {
- pyodide.runPython(makeSubmitWrapper(input.register_outputs));
+ if (params.outputs) {
+ pyodide.runPython(makeSubmitWrapper(params.outputs));
}
- console.log(JSON.stringify({
- tools_registered: toolNames,
- outputs_registered: input.register_outputs ? input.register_outputs.map(o => o.name) : []
- }));
+ console.log(jsonrpcResult({
+ tools: toolNames,
+ outputs: params.outputs ? params.outputs.map(o => o.name) : []
+ }, requestId));
continue;
}
- const code = input.code || "";
+ if (method === "execute") {
+ const code = params.code || "";
+ let setupCompleted = false; // Track if PYTHON_SETUP_CODE ran successfully
- try {
- await pyodide.loadPackagesFromImports(code);
- pyodide.runPython(PYTHON_SETUP_CODE);
- // Run the user's code
- const result = await pyodide.runPythonAsync(code);
- const capturedStdout = pyodide.runPython("buf_stdout.getvalue()");
- pyodide.runPython("sys.stdout, sys.stderr = old_stdout, old_stderr");
-
- // If result is None, output prints; otherwise output the result
- let output = (result === null || result === undefined) ? capturedStdout : (result.toJs?.() ?? result);
- console.log(JSON.stringify({ output }));
- } catch (error) {
- // We have an error => check if it's a SyntaxError or something else
- // The Python error class name is stored in error.type: https://pyodide.org/en/stable/usage/api/js-api.html#pyodide.ffi.PythonError
- const errorType = error.type || "Error";
- // error.message is mostly blank.
- const errorMessage = (error.message || "").trim();
- // The arguments of the exception are stored in sys.last_exc.args,
- // which is always helpful but pyodide don't extract them for us.
- // Use a bridge function to get them.
- let errorArgs = [];
- if (errorType !== "SyntaxError") {
- // Only python exceptions have args.
- const last_exception_args = pyodide.globals.get("last_exception_args");
- // Regarding https://pyodide.org/en/stable/usage/type-conversions.html#type-translations-errors,
- // we do a additional `json.dumps` and `JSON.parse` on the values, to avoid the possible memory leak.
- errorArgs = JSON.parse(last_exception_args()) || [];
+ try {
+ await pyodide.loadPackagesFromImports(code);
+ pyodide.runPython(PYTHON_SETUP_CODE);
+ setupCompleted = true; // Mark setup as complete - old_stdout/old_stderr now exist
+
+ // Run the user's code
+ const result = await pyodide.runPythonAsync(code);
+ const capturedStdout = pyodide.runPython("buf_stdout.getvalue()");
+
+ // If result is None, output prints; otherwise output the result
+ let output = (result === null || result === undefined) ? capturedStdout : (result.toJs?.() ?? result);
+ console.log(jsonrpcResult({ output }, requestId));
+ } catch (error) {
+ // We have an error => check if it's a SyntaxError or something else
+ // The Python error class name is stored in error.type: https://pyodide.org/en/stable/usage/api/js-api.html#pyodide.ffi.PythonError
+ const errorType = error.type || "Error";
+ // error.message is mostly blank.
+ const errorMessage = (error.message || "").trim();
+
+ // Handle FinalOutput as a success result, not an error
+ if (errorType === "FinalOutput") {
+ const last_exception_args = pyodide.globals.get("last_exception_args");
+ const errorArgs = JSON.parse(last_exception_args()) || [];
+ const answer = errorArgs[0] || null;
+ console.log(jsonrpcResult({ final: answer }, requestId));
+ continue;
+ }
+
+ // Get error args for other exception types
+ let errorArgs = [];
+ if (errorType !== "SyntaxError") {
+ // Only python exceptions have args.
+ const last_exception_args = pyodide.globals.get("last_exception_args");
+ // Regarding https://pyodide.org/en/stable/usage/type-conversions.html#type-translations-errors,
+ // we do a additional `json.dumps` and `JSON.parse` on the values, to avoid the possible memory leak.
+ errorArgs = JSON.parse(last_exception_args()) || [];
+ }
+
+ // Map error type to JSON-RPC error code
+ const errorCode = JSONRPC_APP_ERRORS[errorType] || JSONRPC_APP_ERRORS.Unknown;
+ console.log(jsonrpcError(errorCode, errorMessage, requestId, { type: errorType, args: errorArgs }));
+ } finally {
+ // Always restore stdout/stderr if setup completed, even after errors.
+ // This prevents stream corruption where subsequent executions capture
+ // StringIO buffers as old_stdout/old_stderr instead of real streams.
+ if (setupCompleted) {
+ try {
+ pyodide.runPython("sys.stdout, sys.stderr = old_stdout, old_stderr");
+ } catch (e) {
+ // Ignore restoration errors to avoid masking the original error
+ }
+ }
}
- console.log(JSON.stringify({ error: errorMessage, errorArgs, errorType }));
+ continue;
}
+
+ // Unknown method
+ console.log(jsonrpcError(JSONRPC_PROTOCOL_ERRORS.MethodNotFound, `Method not found: ${method}`, requestId));
}