agentcyberrange 0.1.0__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.
Potentially problematic release.
This version of agentcyberrange might be problematic. Click here for more details.
- agentcyberrange/__init__.py +79 -0
- agentcyberrange/_version.py +1 -0
- agentcyberrange/client.py +509 -0
- agentcyberrange/errors.py +144 -0
- agentcyberrange/handles.py +106 -0
- agentcyberrange/models.py +249 -0
- agentcyberrange/py.typed +0 -0
- agentcyberrange/runner.py +108 -0
- agentcyberrange/scheduler.py +784 -0
- agentcyberrange/state.py +108 -0
- agentcyberrange/submission.py +29 -0
- agentcyberrange-0.1.0.dist-info/METADATA +275 -0
- agentcyberrange-0.1.0.dist-info/RECORD +15 -0
- agentcyberrange-0.1.0.dist-info/WHEEL +4 -0
- agentcyberrange-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from ._version import __version__
|
|
2
|
+
from .client import AgentCyberRangeClient
|
|
3
|
+
from .errors import (
|
|
4
|
+
AgentCyberRangeError,
|
|
5
|
+
ArenaBusyError,
|
|
6
|
+
ArenaNotFoundError,
|
|
7
|
+
ArenaNotOwnedError,
|
|
8
|
+
ArenaStateError,
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
CapacityExhaustedError,
|
|
11
|
+
ChallengeNotFoundError,
|
|
12
|
+
InvalidRequestError,
|
|
13
|
+
LaunchFailedError,
|
|
14
|
+
ProtocolError,
|
|
15
|
+
RevokedTokenError,
|
|
16
|
+
ServerError,
|
|
17
|
+
SubmissionFailedError,
|
|
18
|
+
TransportError,
|
|
19
|
+
)
|
|
20
|
+
from .handles import ArenaHandle
|
|
21
|
+
from .models import (
|
|
22
|
+
AgentOutputPath,
|
|
23
|
+
Arena,
|
|
24
|
+
ArenaEndpoint,
|
|
25
|
+
Capacity,
|
|
26
|
+
Challenge,
|
|
27
|
+
ChallengeTask,
|
|
28
|
+
ExecutionResult,
|
|
29
|
+
PublicVerdict,
|
|
30
|
+
RetryPolicy,
|
|
31
|
+
RoundConfig,
|
|
32
|
+
SchedulerEvent,
|
|
33
|
+
SubmissionResult,
|
|
34
|
+
TaskOutcome,
|
|
35
|
+
TimeoutConfig,
|
|
36
|
+
)
|
|
37
|
+
from .runner import Agent, run_agent
|
|
38
|
+
from .scheduler import EventHandler, RoundScheduler
|
|
39
|
+
from .submission import is_post_challenge
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"AgentOutputPath",
|
|
43
|
+
"Arena",
|
|
44
|
+
"ArenaBusyError",
|
|
45
|
+
"ArenaHandle",
|
|
46
|
+
"ArenaEndpoint",
|
|
47
|
+
"ArenaNotFoundError",
|
|
48
|
+
"ArenaNotOwnedError",
|
|
49
|
+
"ArenaStateError",
|
|
50
|
+
"AuthenticationError",
|
|
51
|
+
"Agent",
|
|
52
|
+
"AgentCyberRangeClient",
|
|
53
|
+
"AgentCyberRangeError",
|
|
54
|
+
"Capacity",
|
|
55
|
+
"CapacityExhaustedError",
|
|
56
|
+
"Challenge",
|
|
57
|
+
"ChallengeNotFoundError",
|
|
58
|
+
"ChallengeTask",
|
|
59
|
+
"ExecutionResult",
|
|
60
|
+
"EventHandler",
|
|
61
|
+
"InvalidRequestError",
|
|
62
|
+
"LaunchFailedError",
|
|
63
|
+
"ProtocolError",
|
|
64
|
+
"PublicVerdict",
|
|
65
|
+
"RetryPolicy",
|
|
66
|
+
"RevokedTokenError",
|
|
67
|
+
"RoundConfig",
|
|
68
|
+
"RoundScheduler",
|
|
69
|
+
"is_post_challenge",
|
|
70
|
+
"run_agent",
|
|
71
|
+
"SchedulerEvent",
|
|
72
|
+
"ServerError",
|
|
73
|
+
"SubmissionResult",
|
|
74
|
+
"SubmissionFailedError",
|
|
75
|
+
"TaskOutcome",
|
|
76
|
+
"TimeoutConfig",
|
|
77
|
+
"TransportError",
|
|
78
|
+
"__version__",
|
|
79
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import random
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
6
|
+
from datetime import UTC, datetime, timedelta
|
|
7
|
+
from email.utils import parsedate_to_datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal, NoReturn, TypeVar
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from pydantic import BaseModel, ValidationError
|
|
14
|
+
|
|
15
|
+
from ._version import __version__
|
|
16
|
+
from .errors import (
|
|
17
|
+
AgentCyberRangeError,
|
|
18
|
+
ArenaBusyError,
|
|
19
|
+
CapacityExhaustedError,
|
|
20
|
+
LaunchFailedError,
|
|
21
|
+
ProtocolError,
|
|
22
|
+
SubmissionFailedError,
|
|
23
|
+
TransportError,
|
|
24
|
+
error_from_response,
|
|
25
|
+
)
|
|
26
|
+
from .models import (
|
|
27
|
+
AgentOutputPath,
|
|
28
|
+
Arena,
|
|
29
|
+
Capacity,
|
|
30
|
+
Challenge,
|
|
31
|
+
RetryPolicy,
|
|
32
|
+
SubmissionResult,
|
|
33
|
+
TimeoutConfig,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
SDK_VERSION = __version__
|
|
37
|
+
MAX_AGENT_OUTPUT_BYTES = 10 * 1024 * 1024
|
|
38
|
+
SUBMIT_BUSY_RETRY_INTERVAL_SECONDS = 60.0
|
|
39
|
+
SUBMIT_BUSY_MAX_RETRIES = 10
|
|
40
|
+
ModelT = TypeVar("ModelT", bound=BaseModel)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AgentCyberRangeClient:
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
base_url: str,
|
|
48
|
+
task_token: str,
|
|
49
|
+
retry_policy: RetryPolicy | None = None,
|
|
50
|
+
timeout: TimeoutConfig | None = None,
|
|
51
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
52
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
53
|
+
random_source: Callable[[], float] = random.random,
|
|
54
|
+
now: Callable[[], datetime] = lambda: datetime.now(UTC),
|
|
55
|
+
trust_env: bool = True,
|
|
56
|
+
) -> None:
|
|
57
|
+
self._retry_policy = retry_policy or RetryPolicy()
|
|
58
|
+
self._sleep = sleep
|
|
59
|
+
self._random_source = random_source
|
|
60
|
+
self._now = now
|
|
61
|
+
self._server_clock_offset = 0.0
|
|
62
|
+
timeout_config = timeout or TimeoutConfig()
|
|
63
|
+
self._submit_total_timeout = timeout_config.submit_total
|
|
64
|
+
self._submit_timeout = httpx.Timeout(
|
|
65
|
+
connect=timeout_config.connect,
|
|
66
|
+
read=timeout_config.submit_read,
|
|
67
|
+
write=timeout_config.write,
|
|
68
|
+
pool=timeout_config.pool,
|
|
69
|
+
)
|
|
70
|
+
self._http = httpx.AsyncClient(
|
|
71
|
+
base_url=base_url.rstrip("/") + "/v1",
|
|
72
|
+
headers={
|
|
73
|
+
"Authorization": f"Bearer {task_token}",
|
|
74
|
+
"Accept": "application/json",
|
|
75
|
+
"User-Agent": f"agentcyberrange/{SDK_VERSION}",
|
|
76
|
+
},
|
|
77
|
+
timeout=httpx.Timeout(
|
|
78
|
+
connect=timeout_config.connect,
|
|
79
|
+
read=timeout_config.read,
|
|
80
|
+
write=timeout_config.write,
|
|
81
|
+
pool=timeout_config.pool,
|
|
82
|
+
),
|
|
83
|
+
transport=transport,
|
|
84
|
+
trust_env=trust_env,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
async def __aenter__(self) -> AgentCyberRangeClient:
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
async def __aexit__(self, *exc_info: object) -> None:
|
|
91
|
+
await self.aclose()
|
|
92
|
+
|
|
93
|
+
async def aclose(self) -> None:
|
|
94
|
+
await self._http.aclose()
|
|
95
|
+
|
|
96
|
+
def server_now(self) -> datetime:
|
|
97
|
+
return self._now() + timedelta(seconds=self._server_clock_offset)
|
|
98
|
+
|
|
99
|
+
async def list_challenges(self) -> list[Challenge]:
|
|
100
|
+
payload, _ = await self._request_json("GET", "/challenges", expected_statuses={200})
|
|
101
|
+
return self._parse_items(payload, Challenge)
|
|
102
|
+
|
|
103
|
+
async def get_capacity(self) -> Capacity:
|
|
104
|
+
payload, _ = await self._request_json("GET", "/capacity", expected_statuses={200})
|
|
105
|
+
capacity = self._validate(Capacity, payload)
|
|
106
|
+
self._update_server_time(capacity.server_time)
|
|
107
|
+
return capacity
|
|
108
|
+
|
|
109
|
+
async def create_arena(
|
|
110
|
+
self,
|
|
111
|
+
challenge_id: str,
|
|
112
|
+
*,
|
|
113
|
+
prompt_level: str = "l0",
|
|
114
|
+
idempotency_key: str | None = None,
|
|
115
|
+
wait_for_capacity: bool = True,
|
|
116
|
+
cancel_event: asyncio.Event | None = None,
|
|
117
|
+
) -> Arena:
|
|
118
|
+
key = idempotency_key or str(uuid4())
|
|
119
|
+
attempt = 0
|
|
120
|
+
capacity_wait_started: float | None = None
|
|
121
|
+
while True:
|
|
122
|
+
if cancel_event is not None and cancel_event.is_set():
|
|
123
|
+
raise asyncio.CancelledError
|
|
124
|
+
try:
|
|
125
|
+
payload, response = await self._request_json(
|
|
126
|
+
"POST",
|
|
127
|
+
"/arenas",
|
|
128
|
+
headers={"Idempotency-Key": key},
|
|
129
|
+
json={"challenge_id": challenge_id, "prompt_level": prompt_level},
|
|
130
|
+
expected_statuses={201, 202},
|
|
131
|
+
)
|
|
132
|
+
except CapacityExhaustedError as exc:
|
|
133
|
+
if not wait_for_capacity:
|
|
134
|
+
raise
|
|
135
|
+
if capacity_wait_started is None:
|
|
136
|
+
capacity_wait_started = asyncio.get_running_loop().time()
|
|
137
|
+
timeout = self._retry_policy.capacity_wait_timeout
|
|
138
|
+
if (
|
|
139
|
+
timeout is not None
|
|
140
|
+
and asyncio.get_running_loop().time() - capacity_wait_started >= timeout
|
|
141
|
+
):
|
|
142
|
+
raise
|
|
143
|
+
await self._sleep_before_retry(attempt, exc.retry_after, cancel_event)
|
|
144
|
+
attempt += 1
|
|
145
|
+
continue
|
|
146
|
+
arena = self._validate(Arena, payload)
|
|
147
|
+
launching_statuses = {
|
|
148
|
+
"launch_pending",
|
|
149
|
+
"launching",
|
|
150
|
+
"launch_unknown",
|
|
151
|
+
}
|
|
152
|
+
if response.status_code == 201 and arena.status != "running":
|
|
153
|
+
raise ProtocolError(
|
|
154
|
+
"201 create response must contain a running Arena",
|
|
155
|
+
status_code=201,
|
|
156
|
+
)
|
|
157
|
+
if response.status_code == 202 and arena.status not in launching_statuses:
|
|
158
|
+
raise ProtocolError(
|
|
159
|
+
"202 create response must contain a launching Arena",
|
|
160
|
+
status_code=202,
|
|
161
|
+
)
|
|
162
|
+
if arena.status in launching_statuses:
|
|
163
|
+
arena = await self._wait_until_ready(arena, cancel_event)
|
|
164
|
+
if arena.status == "lost":
|
|
165
|
+
return arena
|
|
166
|
+
if not arena.ready:
|
|
167
|
+
raise LaunchFailedError(
|
|
168
|
+
f"Arena launch ended before it became ready (status={arena.status})",
|
|
169
|
+
error_code="launch_failed",
|
|
170
|
+
retryable=False,
|
|
171
|
+
)
|
|
172
|
+
return arena
|
|
173
|
+
|
|
174
|
+
async def get_arena(self, arena_id: str) -> Arena:
|
|
175
|
+
payload, _ = await self._request_json("GET", f"/arenas/{arena_id}", expected_statuses={200})
|
|
176
|
+
return self._validate(Arena, payload)
|
|
177
|
+
|
|
178
|
+
async def list_arenas(
|
|
179
|
+
self, scope: Literal["active", "completed", "all"] = "all"
|
|
180
|
+
) -> list[Arena]:
|
|
181
|
+
payload, _ = await self._request_json(
|
|
182
|
+
"GET", "/arenas", params={"scope": scope}, expected_statuses={200}
|
|
183
|
+
)
|
|
184
|
+
return self._parse_items(payload, Arena)
|
|
185
|
+
|
|
186
|
+
async def submit(
|
|
187
|
+
self,
|
|
188
|
+
arena_id: str,
|
|
189
|
+
*,
|
|
190
|
+
agent_output: AgentOutputPath | None = None,
|
|
191
|
+
) -> SubmissionResult:
|
|
192
|
+
files = self._prepare_agent_output(agent_output)
|
|
193
|
+
try:
|
|
194
|
+
async with asyncio.timeout(self._submit_total_timeout):
|
|
195
|
+
return await self._submit_with_retries(arena_id, files=files)
|
|
196
|
+
except TimeoutError as timeout_error:
|
|
197
|
+
recovery_error: AgentCyberRangeError | None = None
|
|
198
|
+
try:
|
|
199
|
+
recovered = await self._recover_submission(arena_id, retry_transient=False)
|
|
200
|
+
except AgentCyberRangeError as exc:
|
|
201
|
+
recovered = None
|
|
202
|
+
recovery_error = exc
|
|
203
|
+
if recovered is not None:
|
|
204
|
+
return recovered
|
|
205
|
+
await self._fail_submission_after_cleanup(
|
|
206
|
+
arena_id,
|
|
207
|
+
message="Arena submission exceeded its total deadline",
|
|
208
|
+
error_code="submit_timeout",
|
|
209
|
+
cause=recovery_error or timeout_error,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
async def _submit_with_retries(
|
|
213
|
+
self,
|
|
214
|
+
arena_id: str,
|
|
215
|
+
*,
|
|
216
|
+
files: Mapping[str, tuple[str, bytes, str]] | None,
|
|
217
|
+
) -> SubmissionResult:
|
|
218
|
+
transient_attempt = 0
|
|
219
|
+
busy_retries = 0
|
|
220
|
+
while True:
|
|
221
|
+
try:
|
|
222
|
+
payload, _ = await self._request_json(
|
|
223
|
+
"POST",
|
|
224
|
+
f"/arenas/{arena_id}/submit",
|
|
225
|
+
files=files,
|
|
226
|
+
expected_statuses={200},
|
|
227
|
+
retry_transient=False,
|
|
228
|
+
request_timeout=self._submit_timeout,
|
|
229
|
+
)
|
|
230
|
+
submission = self._validate(SubmissionResult, payload)
|
|
231
|
+
if submission.status == "scored":
|
|
232
|
+
raise ProtocolError(
|
|
233
|
+
"Submit response must contain a closing Arena",
|
|
234
|
+
status_code=200,
|
|
235
|
+
)
|
|
236
|
+
return submission
|
|
237
|
+
except ArenaBusyError as exc:
|
|
238
|
+
if busy_retries >= SUBMIT_BUSY_MAX_RETRIES:
|
|
239
|
+
await self._fail_submission_after_cleanup(
|
|
240
|
+
arena_id,
|
|
241
|
+
message="Arena submission remained busy",
|
|
242
|
+
status_code=exc.status_code,
|
|
243
|
+
error_code=exc.error_code,
|
|
244
|
+
request_id=exc.request_id,
|
|
245
|
+
cause=exc,
|
|
246
|
+
)
|
|
247
|
+
busy_retries += 1
|
|
248
|
+
await self._sleep(SUBMIT_BUSY_RETRY_INTERVAL_SECONDS)
|
|
249
|
+
except TransportError as exc:
|
|
250
|
+
recovered = await self._recover_submission(arena_id)
|
|
251
|
+
if recovered is not None:
|
|
252
|
+
return recovered
|
|
253
|
+
await self._sleep_before_retry(transient_attempt, exc.retry_after, None)
|
|
254
|
+
transient_attempt += 1
|
|
255
|
+
|
|
256
|
+
async def _fail_submission_after_cleanup(
|
|
257
|
+
self,
|
|
258
|
+
arena_id: str,
|
|
259
|
+
*,
|
|
260
|
+
message: str,
|
|
261
|
+
error_code: str | None,
|
|
262
|
+
cause: BaseException,
|
|
263
|
+
status_code: int | None = None,
|
|
264
|
+
request_id: str | None = None,
|
|
265
|
+
) -> NoReturn:
|
|
266
|
+
try:
|
|
267
|
+
await self.close(arena_id)
|
|
268
|
+
except AgentCyberRangeError as cleanup_error:
|
|
269
|
+
raise SubmissionFailedError(
|
|
270
|
+
f"{message} and cleanup failed",
|
|
271
|
+
status_code=status_code,
|
|
272
|
+
error_code=error_code,
|
|
273
|
+
request_id=request_id,
|
|
274
|
+
) from cleanup_error
|
|
275
|
+
raise SubmissionFailedError(
|
|
276
|
+
f"{message}; the Arena was closed",
|
|
277
|
+
status_code=status_code,
|
|
278
|
+
error_code=error_code,
|
|
279
|
+
request_id=request_id,
|
|
280
|
+
) from cause
|
|
281
|
+
|
|
282
|
+
async def close(self, arena_id: str) -> Arena:
|
|
283
|
+
payload, _ = await self._request_json(
|
|
284
|
+
"DELETE", f"/arenas/{arena_id}", expected_statuses={200}
|
|
285
|
+
)
|
|
286
|
+
return self._validate(Arena, payload)
|
|
287
|
+
|
|
288
|
+
async def _wait_until_ready(self, arena: Arena, cancel_event: asyncio.Event | None) -> Arena:
|
|
289
|
+
current = arena
|
|
290
|
+
while current.status in {"launch_pending", "launching", "launch_unknown"}:
|
|
291
|
+
await self._sleep_before_retry(0, None, cancel_event, base_delay=2.0)
|
|
292
|
+
current = await self.get_arena(current.arena_id)
|
|
293
|
+
return current
|
|
294
|
+
|
|
295
|
+
async def _sleep_before_retry(
|
|
296
|
+
self,
|
|
297
|
+
attempt: int,
|
|
298
|
+
retry_after: float | None,
|
|
299
|
+
cancel_event: asyncio.Event | None,
|
|
300
|
+
*,
|
|
301
|
+
base_delay: float | None = None,
|
|
302
|
+
) -> None:
|
|
303
|
+
base = min(
|
|
304
|
+
self._retry_policy.max_delay_seconds,
|
|
305
|
+
(base_delay or self._retry_policy.initial_delay_seconds) * (2**attempt),
|
|
306
|
+
)
|
|
307
|
+
jitter = self._retry_policy.jitter_ratio
|
|
308
|
+
delay = min(
|
|
309
|
+
self._retry_policy.max_delay_seconds,
|
|
310
|
+
base * (1 - jitter + (2 * jitter * self._random_source())),
|
|
311
|
+
)
|
|
312
|
+
if retry_after is not None:
|
|
313
|
+
delay = max(delay, retry_after)
|
|
314
|
+
if cancel_event is None:
|
|
315
|
+
await self._sleep(delay)
|
|
316
|
+
return
|
|
317
|
+
try:
|
|
318
|
+
await asyncio.wait_for(cancel_event.wait(), timeout=delay)
|
|
319
|
+
except TimeoutError:
|
|
320
|
+
return
|
|
321
|
+
raise asyncio.CancelledError
|
|
322
|
+
|
|
323
|
+
async def _request_json(
|
|
324
|
+
self,
|
|
325
|
+
method: str,
|
|
326
|
+
path: str,
|
|
327
|
+
*,
|
|
328
|
+
headers: Mapping[str, str] | None = None,
|
|
329
|
+
files: Mapping[str, tuple[str, bytes, str]] | None = None,
|
|
330
|
+
json: Any = None,
|
|
331
|
+
params: Mapping[str, str] | None = None,
|
|
332
|
+
expected_statuses: set[int] | None = None,
|
|
333
|
+
retry_transient: bool = True,
|
|
334
|
+
request_timeout: httpx.Timeout | None = None,
|
|
335
|
+
) -> tuple[Any, httpx.Response]:
|
|
336
|
+
kwargs: dict[str, Any] = {"headers": headers, "params": params}
|
|
337
|
+
if files is not None:
|
|
338
|
+
kwargs["files"] = files
|
|
339
|
+
if json is not None:
|
|
340
|
+
kwargs["json"] = json
|
|
341
|
+
if request_timeout is not None:
|
|
342
|
+
kwargs["timeout"] = request_timeout
|
|
343
|
+
attempt = 0
|
|
344
|
+
while True:
|
|
345
|
+
try:
|
|
346
|
+
response = await self._http.request(method, path, **kwargs)
|
|
347
|
+
except httpx.HTTPError as exc:
|
|
348
|
+
if not retry_transient or attempt >= self._retry_policy.max_transient_attempts:
|
|
349
|
+
raise TransportError("Transport request failed", retryable=True) from exc
|
|
350
|
+
await self._sleep_before_retry(attempt, None, None)
|
|
351
|
+
attempt += 1
|
|
352
|
+
continue
|
|
353
|
+
self._update_server_date(response.headers.get("Date"))
|
|
354
|
+
try:
|
|
355
|
+
payload = response.json()
|
|
356
|
+
except ValueError as exc:
|
|
357
|
+
if response.status_code in {429, 502, 503, 504}:
|
|
358
|
+
retry_after = self._parse_retry_after(response.headers.get("Retry-After"))
|
|
359
|
+
if not retry_transient:
|
|
360
|
+
raise TransportError(
|
|
361
|
+
"Transient response body is not valid JSON",
|
|
362
|
+
status_code=response.status_code,
|
|
363
|
+
retryable=True,
|
|
364
|
+
retry_after=retry_after,
|
|
365
|
+
) from exc
|
|
366
|
+
if attempt >= self._retry_policy.max_transient_attempts:
|
|
367
|
+
raise TransportError(
|
|
368
|
+
"Transient response retries exhausted",
|
|
369
|
+
status_code=response.status_code,
|
|
370
|
+
retryable=True,
|
|
371
|
+
retry_after=retry_after,
|
|
372
|
+
) from exc
|
|
373
|
+
await self._sleep_before_retry(attempt, retry_after, None)
|
|
374
|
+
attempt += 1
|
|
375
|
+
continue
|
|
376
|
+
raise ProtocolError(
|
|
377
|
+
"Response body is not valid JSON", status_code=response.status_code
|
|
378
|
+
) from exc
|
|
379
|
+
if not response.is_error:
|
|
380
|
+
if expected_statuses is not None and response.status_code not in expected_statuses:
|
|
381
|
+
raise ProtocolError(
|
|
382
|
+
"Response status does not match the protocol",
|
|
383
|
+
status_code=response.status_code,
|
|
384
|
+
)
|
|
385
|
+
return payload, response
|
|
386
|
+
error = error_from_response(
|
|
387
|
+
response.status_code,
|
|
388
|
+
payload,
|
|
389
|
+
retry_after=self._parse_retry_after(response.headers.get("Retry-After")),
|
|
390
|
+
)
|
|
391
|
+
if isinstance(error, CapacityExhaustedError) or not error.retryable:
|
|
392
|
+
raise error
|
|
393
|
+
if not retry_transient:
|
|
394
|
+
raise TransportError(
|
|
395
|
+
"Transient request failed",
|
|
396
|
+
status_code=error.status_code,
|
|
397
|
+
error_code=error.error_code,
|
|
398
|
+
request_id=error.request_id,
|
|
399
|
+
retryable=True,
|
|
400
|
+
retry_after=error.retry_after,
|
|
401
|
+
) from error
|
|
402
|
+
if attempt >= self._retry_policy.max_transient_attempts:
|
|
403
|
+
raise TransportError(
|
|
404
|
+
"Transient request retries exhausted",
|
|
405
|
+
status_code=error.status_code,
|
|
406
|
+
error_code=error.error_code,
|
|
407
|
+
request_id=error.request_id,
|
|
408
|
+
retryable=True,
|
|
409
|
+
retry_after=error.retry_after,
|
|
410
|
+
) from error
|
|
411
|
+
await self._sleep_before_retry(attempt, error.retry_after, None)
|
|
412
|
+
attempt += 1
|
|
413
|
+
|
|
414
|
+
@staticmethod
|
|
415
|
+
def _prepare_agent_output(
|
|
416
|
+
agent_output: AgentOutputPath | None,
|
|
417
|
+
) -> Mapping[str, tuple[str, bytes, str]] | None:
|
|
418
|
+
if agent_output is None:
|
|
419
|
+
return None
|
|
420
|
+
|
|
421
|
+
supplied_path = Path(agent_output).expanduser()
|
|
422
|
+
filename = supplied_path.name
|
|
423
|
+
if not filename.endswith((".tar.gz", ".zip")):
|
|
424
|
+
raise ValueError("agent_output filename must end in .tar.gz or .zip")
|
|
425
|
+
|
|
426
|
+
# Resolve a relative path against the cwd at the start of submit(). The
|
|
427
|
+
# absolute path and bytes are then independent of later cwd/file changes.
|
|
428
|
+
resolved_path = supplied_path.resolve(strict=True)
|
|
429
|
+
if not resolved_path.is_file():
|
|
430
|
+
raise ValueError("agent_output must be a regular file")
|
|
431
|
+
if resolved_path.stat().st_size > MAX_AGENT_OUTPUT_BYTES:
|
|
432
|
+
raise ValueError("agent_output must not exceed 10 MiB")
|
|
433
|
+
|
|
434
|
+
content = resolved_path.read_bytes()
|
|
435
|
+
if not content:
|
|
436
|
+
raise ValueError("agent_output must not be empty")
|
|
437
|
+
if len(content) > MAX_AGENT_OUTPUT_BYTES:
|
|
438
|
+
raise ValueError("agent_output must not exceed 10 MiB")
|
|
439
|
+
|
|
440
|
+
return {"agent_output": (filename, content, "application/octet-stream")}
|
|
441
|
+
|
|
442
|
+
async def _recover_submission(
|
|
443
|
+
self,
|
|
444
|
+
arena_id: str,
|
|
445
|
+
*,
|
|
446
|
+
retry_transient: bool = True,
|
|
447
|
+
) -> SubmissionResult | None:
|
|
448
|
+
payload, _ = await self._request_json(
|
|
449
|
+
"GET",
|
|
450
|
+
f"/arenas/{arena_id}",
|
|
451
|
+
expected_statuses={200},
|
|
452
|
+
retry_transient=retry_transient,
|
|
453
|
+
)
|
|
454
|
+
arena = self._validate(Arena, payload)
|
|
455
|
+
if (
|
|
456
|
+
arena.status not in {"scored", "close_pending", "closed"}
|
|
457
|
+
or arena.submitted_at is None
|
|
458
|
+
or arena.submission_trigger is None
|
|
459
|
+
or arena.verdict is None
|
|
460
|
+
):
|
|
461
|
+
return None
|
|
462
|
+
return SubmissionResult(
|
|
463
|
+
arena_id=arena.arena_id,
|
|
464
|
+
status=arena.status,
|
|
465
|
+
submitted_at=arena.submitted_at,
|
|
466
|
+
submission_trigger=arena.submission_trigger,
|
|
467
|
+
already_submitted=True,
|
|
468
|
+
verdict=arena.verdict,
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
@staticmethod
|
|
472
|
+
def _parse_retry_after(value: str | None) -> float | None:
|
|
473
|
+
if value is None:
|
|
474
|
+
return None
|
|
475
|
+
try:
|
|
476
|
+
return max(0.0, float(value))
|
|
477
|
+
except ValueError:
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
def _update_server_date(self, value: str | None) -> None:
|
|
481
|
+
if value is None:
|
|
482
|
+
return
|
|
483
|
+
try:
|
|
484
|
+
server_time = parsedate_to_datetime(value)
|
|
485
|
+
except (TypeError, ValueError, OverflowError):
|
|
486
|
+
return
|
|
487
|
+
self._update_server_time(server_time)
|
|
488
|
+
|
|
489
|
+
def _update_server_time(self, server_time: datetime) -> None:
|
|
490
|
+
if server_time.tzinfo is None:
|
|
491
|
+
server_time = server_time.replace(tzinfo=UTC)
|
|
492
|
+
self._server_clock_offset = (server_time.astimezone(UTC) - self._now()).total_seconds()
|
|
493
|
+
|
|
494
|
+
@staticmethod
|
|
495
|
+
def _validate(model_type: type[ModelT], payload: Any) -> ModelT:
|
|
496
|
+
try:
|
|
497
|
+
return model_type.model_validate(payload)
|
|
498
|
+
except ValidationError as exc:
|
|
499
|
+
raise ProtocolError("Response does not match the protocol") from exc
|
|
500
|
+
|
|
501
|
+
@classmethod
|
|
502
|
+
def _parse_items(cls, payload: Any, model_type: type[ModelT]) -> list[ModelT]:
|
|
503
|
+
if (
|
|
504
|
+
not isinstance(payload, dict)
|
|
505
|
+
or set(payload) != {"items"}
|
|
506
|
+
or not isinstance(payload.get("items"), list)
|
|
507
|
+
):
|
|
508
|
+
raise ProtocolError("Response does not contain an items list")
|
|
509
|
+
return [cls._validate(model_type, item) for item in payload["items"]]
|