Repository navigation
Expand file tree
/
Copy patherrors.py
More file actions
167 lines (134 loc) · 5.45 KB
/
Copy patherrors.py
File metadata and controls
167 lines (134 loc) · 5.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""SDK errors. Mirrors ``packages/code-sdk/src/errors.ts``."""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
from .types import ExecResult, ThreadItem
#: Exit codes of ``mcode exec`` (``MINIMAX_CODE_EXEC_EXIT_CODES`` in the CLI).
MCODE_EXEC_EXIT_CODES: dict[str, int] = {
"success": 0,
"invocation": 2,
"config": 3,
"runtime": 4,
"timeout": 6,
"limit": 7,
"internal": 70,
"cancelled": 130,
"broken_pipe": 141,
}
MCODE_INSTALL_HINT = "npm install -g @minimax-ai/code@latest"
class MCodeError(Exception):
"""Base class for every error raised by the SDK."""
def __init__(
self,
message: str,
*,
exit_code: int | None = None,
stderr: str = "",
session_id: str | None = None,
result: ExecResult | None = None,
items: Sequence[ThreadItem] = (),
) -> None:
super().__init__(message)
self.exit_code = exit_code
#: Tail of the CLI stderr, for diagnostics only.
self.stderr = stderr
self.session_id = session_id
self.result = result
self.items: list[ThreadItem] = list(items)
def __reduce__(self) -> tuple[Any, ...]:
# The default reduce calls ``cls(*self.args)``, which breaks subclasses whose
# ``__init__`` takes other arguments. Rebuild from ``args`` and restore the attributes.
return (_restore_error, (type(self), self.args), self.__dict__)
def _restore_error(cls: type[MCodeError], args: tuple[Any, ...]) -> MCodeError:
"""Unpickles an ``MCodeError`` without calling its ``__init__``."""
return cls.__new__(cls, *args)
class MCodeInvocationError(MCodeError):
"""Invalid SDK options, or the CLI rejected the invocation (exit code 2)."""
class MCodeRunError(MCodeError):
"""The Turn ended with ``failed``, ``timeout`` or ``limit_exceeded``."""
def __init__(self, message: str, *, status: str, category: str | None = None, **kw: Any):
super().__init__(message, **kw)
self.status = status
self.category = category
class MCodeAbortError(MCodeError):
"""The Turn was cancelled."""
class MCodeProtocolError(MCodeError):
"""The CLI produced output the SDK cannot understand."""
class MCodeNotFoundError(MCodeError):
"""The ``mcode`` CLI could not be found."""
class MCodeVersionError(MCodeError):
"""The CLI is too old or speaks an unsupported schema version."""
class ThreadBusyError(MCodeError):
"""A Thread already has a Turn in progress."""
def __init__(self, thread_id: str | None) -> None:
super().__init__(f"Thread {thread_id or '(new)'} already has a Turn in progress.")
_STATUS_BY_EXIT_CODE: dict[int, tuple[str, str | None]] = {
3: ("failed", "config"),
4: ("failed", "runtime"),
6: ("timeout", None),
7: ("limit_exceeded", None),
70: ("failed", "internal"),
}
def error_for_result(
result: ExecResult, items: Sequence[ThreadItem], *, exit_code: int | None, stderr: str
) -> MCodeError:
common: dict[str, Any] = {
"exit_code": exit_code,
"stderr": stderr,
"session_id": result["sessionId"],
"result": result,
"items": items,
}
if result["status"] == "cancelled":
return MCodeAbortError("The MCode run was cancelled.", **common)
status = "failed" if result["status"] == "succeeded" else result["status"]
error: Any = result.get("error")
if not isinstance(error, dict):
error = {}
message = error.get("message")
reason = message if isinstance(message, str) and message else f"status {result['status']}"
category = error.get("category")
if not isinstance(category, str):
category = None
return MCodeRunError(
f"The MCode run ended with {status}: {reason}", status=status, category=category, **common
)
def error_for_exit(
*,
exit_code: int | None,
stderr: str,
items: Sequence[ThreadItem],
session_id: str | None,
timed_out: bool = False,
) -> MCodeError:
"""Maps a CLI exit without ``exec.completed`` to an error. ``timed_out`` means the SDK's
``timeout_ms`` backstop killed the CLI, which is a timeout and not a cancellation."""
lines = [line.strip() for line in stderr.splitlines() if line.strip()]
reason = lines[-1] if lines else f"exit code {exit_code}"
common: dict[str, Any] = {
"exit_code": exit_code,
"stderr": stderr,
"items": items,
"session_id": session_id,
}
if timed_out:
return MCodeRunError(
"The MCode run exceeded timeout_ms and was force-stopped by the SDK.",
status="timeout",
**common,
)
if exit_code == MCODE_EXEC_EXIT_CODES["invocation"]:
return MCodeInvocationError(f"mcode rejected the invocation: {reason}", **common)
if exit_code == MCODE_EXEC_EXIT_CODES["cancelled"] or (exit_code is not None and exit_code < 0):
return MCodeAbortError("The MCode run was cancelled.", **common)
if exit_code == MCODE_EXEC_EXIT_CODES["broken_pipe"]:
return MCodeProtocolError(f"mcode reported a broken output pipe: {reason}", **common)
if exit_code == 0:
return MCodeProtocolError("mcode exited without emitting exec.completed.", **common)
status, category = _STATUS_BY_EXIT_CODE.get(exit_code or -1, ("failed", "internal"))
return MCodeRunError(
f"The MCode run ended without a result: {reason}",
status=status,
category=category,
**common,
)