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.

@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class AgentCyberRangeError(Exception):
7
+ def __init__(
8
+ self,
9
+ message: str,
10
+ *,
11
+ status_code: int | None = None,
12
+ error_code: str | None = None,
13
+ request_id: str | None = None,
14
+ retryable: bool = False,
15
+ retry_after: float | None = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.status_code = status_code
20
+ self.error_code = error_code
21
+ self.request_id = request_id
22
+ self.retryable = retryable
23
+ self.retry_after = retry_after
24
+
25
+ def __str__(self) -> str:
26
+ details: list[str] = []
27
+ if self.error_code is not None:
28
+ details.append(f"code={self.error_code}")
29
+ if self.status_code is not None:
30
+ details.append(f"status={self.status_code}")
31
+ if self.request_id is not None:
32
+ details.append(f"request_id={self.request_id}")
33
+ message = super().__str__()
34
+ return f"{message} ({', '.join(details)})" if details else message
35
+
36
+
37
+ class AuthenticationError(AgentCyberRangeError):
38
+ pass
39
+
40
+
41
+ class RevokedTokenError(AuthenticationError):
42
+ pass
43
+
44
+
45
+ class InvalidRequestError(AgentCyberRangeError):
46
+ pass
47
+
48
+
49
+ class ChallengeNotFoundError(AgentCyberRangeError):
50
+ pass
51
+
52
+
53
+ class CapacityExhaustedError(AgentCyberRangeError):
54
+ pass
55
+
56
+
57
+ class ArenaNotFoundError(AgentCyberRangeError):
58
+ pass
59
+
60
+
61
+ class ArenaNotOwnedError(AgentCyberRangeError):
62
+ pass
63
+
64
+
65
+ class ArenaStateError(AgentCyberRangeError):
66
+ pass
67
+
68
+
69
+ class ArenaBusyError(ArenaStateError):
70
+ pass
71
+
72
+
73
+ class SubmissionFailedError(AgentCyberRangeError):
74
+ pass
75
+
76
+
77
+ class LaunchFailedError(AgentCyberRangeError):
78
+ pass
79
+
80
+
81
+ class ServerError(AgentCyberRangeError):
82
+ pass
83
+
84
+
85
+ class ProtocolError(AgentCyberRangeError):
86
+ pass
87
+
88
+
89
+ class TransportError(AgentCyberRangeError):
90
+ pass
91
+
92
+
93
+ ERROR_TYPES: dict[str, type[AgentCyberRangeError]] = {
94
+ "invalid_request": InvalidRequestError,
95
+ "agent_output_too_large": InvalidRequestError,
96
+ "invalid_token": AuthenticationError,
97
+ "revoked_token": RevokedTokenError,
98
+ "challenge_not_found": ChallengeNotFoundError,
99
+ "capacity_exhausted": CapacityExhaustedError,
100
+ "arena_not_found": ArenaNotFoundError,
101
+ "arena_not_owned": ArenaNotOwnedError,
102
+ "arena_not_running": ArenaStateError,
103
+ "invalid_state": ArenaStateError,
104
+ "arena_busy": ArenaBusyError,
105
+ "submission_grace_expired": ArenaStateError,
106
+ "cleanup_uncertain": ArenaStateError,
107
+ "submit_unknown": TransportError,
108
+ "launch_failed": LaunchFailedError,
109
+ "internal_error": ServerError,
110
+ }
111
+
112
+
113
+ def error_from_response(
114
+ status_code: int, payload: Any, *, retry_after: float | None = None
115
+ ) -> AgentCyberRangeError:
116
+ if (
117
+ not isinstance(payload, dict)
118
+ or set(payload) != {"error"}
119
+ or not isinstance(payload.get("error"), dict)
120
+ ):
121
+ return ProtocolError("Invalid error response", status_code=status_code)
122
+ error = payload["error"]
123
+ if set(error) != {"code", "message", "request_id"}:
124
+ return ProtocolError("Invalid error response", status_code=status_code)
125
+ code = error.get("code")
126
+ message = error.get("message")
127
+ request_id = error.get("request_id")
128
+ if not isinstance(code, str) or not isinstance(message, str) or not isinstance(request_id, str):
129
+ return ProtocolError("Invalid error response", status_code=status_code)
130
+ error_type = ERROR_TYPES.get(code, ServerError)
131
+ retryable = code in {"capacity_exhausted", "internal_error"} or status_code in {
132
+ 429,
133
+ 502,
134
+ 503,
135
+ 504,
136
+ }
137
+ return error_type(
138
+ "Agent Cyber Range request failed",
139
+ status_code=status_code,
140
+ error_code=code,
141
+ request_id=request_id,
142
+ retryable=retryable,
143
+ retry_after=retry_after,
144
+ )
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable, Callable
5
+ from datetime import datetime
6
+ from typing import Literal, Protocol
7
+
8
+ from .models import AgentOutputPath, Arena, ArenaEndpoint, SubmissionResult
9
+
10
+
11
+ class SubmitClient(Protocol):
12
+ async def submit(
13
+ self,
14
+ arena_id: str,
15
+ *,
16
+ agent_output: AgentOutputPath | None = None,
17
+ ) -> SubmissionResult: ...
18
+
19
+
20
+ class ArenaHandle:
21
+ def __init__(
22
+ self,
23
+ client: SubmitClient,
24
+ arena: Arena,
25
+ *,
26
+ on_submit_started: Callable[[Literal["manual", "deadline"]], Awaitable[None]]
27
+ | None = None,
28
+ ) -> None:
29
+ if not arena.ready:
30
+ raise ValueError("ArenaHandle requires a ready running Arena")
31
+ self.arena = arena
32
+ self.cancel_event = asyncio.Event()
33
+ self._client = client
34
+ self._on_submit_started = on_submit_started
35
+ self._submit_lock = asyncio.Lock()
36
+ self._submit_task: asyncio.Task[SubmissionResult] | None = None
37
+ self._result: SubmissionResult | None = None
38
+ self._submitted = asyncio.Event()
39
+ self._submit_trigger: Literal["manual", "deadline"] = "manual"
40
+
41
+ @property
42
+ def arena_id(self) -> str:
43
+ return self.arena.arena_id
44
+
45
+ @property
46
+ def challenge_id(self) -> str:
47
+ return self.arena.challenge_id
48
+
49
+ @property
50
+ def task_prompt(self) -> str:
51
+ assert self.arena.task_prompt is not None
52
+ return self.arena.task_prompt
53
+
54
+ @property
55
+ def entry_urls(self) -> list[ArenaEndpoint]:
56
+ return list(self.arena.entry_urls)
57
+
58
+ @property
59
+ def lease_expires_at(self) -> datetime:
60
+ assert self.arena.lease_expires_at is not None
61
+ return self.arena.lease_expires_at
62
+
63
+ async def submit(
64
+ self,
65
+ *,
66
+ agent_output: AgentOutputPath | None = None,
67
+ ) -> SubmissionResult:
68
+ async with self._submit_lock:
69
+ if self._result is not None:
70
+ return self._result
71
+ if self._submit_task is None:
72
+ if self._on_submit_started is not None:
73
+ await self._on_submit_started(self._submit_trigger)
74
+ if agent_output is None:
75
+ submit = self._client.submit(self.arena_id)
76
+ else:
77
+ submit = self._client.submit(
78
+ self.arena_id,
79
+ agent_output=agent_output,
80
+ )
81
+ self._submit_task = asyncio.create_task(submit)
82
+ task = self._submit_task
83
+ result = await task
84
+ async with self._submit_lock:
85
+ self._result = result
86
+ self._submitted.set()
87
+ return result
88
+
89
+ async def submit_at_deadline(
90
+ self,
91
+ *,
92
+ agent_output: AgentOutputPath | None = None,
93
+ ) -> SubmissionResult:
94
+ self._submit_trigger = "deadline"
95
+ return await self.submit(agent_output=agent_output)
96
+
97
+ async def wait_submitted(self) -> SubmissionResult:
98
+ await self._submitted.wait()
99
+ assert self._result is not None
100
+ return self._result
101
+
102
+ async def accept_external_submission(self, result: SubmissionResult) -> None:
103
+ async with self._submit_lock:
104
+ if self._result is None:
105
+ self._result = result
106
+ self._submitted.set()
@@ -0,0 +1,249 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from os import PathLike
5
+ from typing import Annotated, Any, Literal, TypeAlias
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ JsonValue,
12
+ StrictBool,
13
+ StrictFloat,
14
+ StrictInt,
15
+ StrictStr,
16
+ StringConstraints,
17
+ model_validator,
18
+ )
19
+
20
+ ArenaStatus: TypeAlias = Literal[
21
+ "launch_pending",
22
+ "launching",
23
+ "launch_unknown",
24
+ "running",
25
+ "submit_pending",
26
+ "submit_grace",
27
+ "submit_unknown",
28
+ "scored",
29
+ "close_pending",
30
+ "closed",
31
+ "failed",
32
+ "lost",
33
+ ]
34
+ ExecutionStatus: TypeAlias = Literal["completed", "completed_with_errors", "cancelled"]
35
+ TaskOutcomeStatus: TypeAlias = Literal[
36
+ "submitted", "not_found", "failed", "lost", "cancelled"
37
+ ]
38
+ ChallengeID: TypeAlias = Annotated[
39
+ StrictStr,
40
+ StringConstraints(
41
+ max_length=128,
42
+ pattern=r"^[a-z0-9]+(-[a-z0-9]+)*$",
43
+ ),
44
+ ]
45
+ ArenaID: TypeAlias = Annotated[
46
+ StrictStr,
47
+ StringConstraints(
48
+ pattern=(
49
+ r"^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-"
50
+ r"[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$"
51
+ ),
52
+ ),
53
+ ]
54
+ ArenaPollURL: TypeAlias = Annotated[
55
+ StrictStr,
56
+ StringConstraints(
57
+ pattern=(
58
+ r"^/v1/arenas/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-"
59
+ r"[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$"
60
+ ),
61
+ ),
62
+ ]
63
+ SubmissionStatus: TypeAlias = Literal["scored", "close_pending", "closed"]
64
+ AgentOutputPath: TypeAlias = str | PathLike[str]
65
+ NonNegativeInt: TypeAlias = Annotated[StrictInt, Field(ge=0)]
66
+ Port: TypeAlias = Annotated[StrictInt, Field(ge=1, le=65535)]
67
+ PositiveSeconds: TypeAlias = Annotated[float, Field(gt=0)]
68
+
69
+
70
+ class SDKModel(BaseModel):
71
+ model_config = ConfigDict(extra="forbid")
72
+
73
+
74
+ class Challenge(SDKModel):
75
+ challenge_id: ChallengeID
76
+ name: StrictStr
77
+ description: StrictStr
78
+ entry_roles: list[StrictStr] = Field(default_factory=list)
79
+
80
+
81
+ class Capacity(SDKModel):
82
+ total_nodes: NonNegativeInt
83
+ available_nodes: NonNegativeInt
84
+ active_arenas_for_token: NonNegativeInt
85
+ lease_minutes: Literal[120]
86
+ server_time: datetime
87
+
88
+
89
+ class ArenaEndpoint(SDKModel):
90
+ name: StrictStr
91
+ role: StrictStr
92
+ url: StrictStr
93
+ host: StrictStr
94
+ port: Port
95
+ protocol: StrictStr
96
+
97
+
98
+ class PublicVerdict(SDKModel):
99
+ score: StrictFloat
100
+ passed: StrictBool
101
+ summary: StrictStr
102
+
103
+
104
+ class Arena(SDKModel):
105
+ arena_id: ArenaID
106
+ challenge_id: StrictStr
107
+ status: ArenaStatus
108
+ task_prompt: StrictStr | None = None
109
+ entry_urls: list[ArenaEndpoint] = Field(default_factory=list)
110
+ lease_expires_at: datetime | None = None
111
+ submission_grace_expires_at: datetime | None = None
112
+ submitted_at: datetime | None = None
113
+ submission_trigger: Literal["manual", "deadline"] | None = None
114
+ verdict: PublicVerdict | None = None
115
+ closed_at: datetime | None = None
116
+ poll_url: ArenaPollURL | None = None
117
+
118
+ @model_validator(mode="after")
119
+ def validate_status_shape(self) -> Arena:
120
+ common = {"arena_id", "challenge_id", "status"}
121
+ if self.status in {"launch_pending", "launching", "launch_unknown"}:
122
+ allowed = common | {"poll_url"}
123
+ if self.poll_url is None or self.model_fields_set - allowed:
124
+ raise ValueError("launching Arena requires poll_url")
125
+ elif self.status == "running":
126
+ allowed = common | {
127
+ "task_prompt",
128
+ "entry_urls",
129
+ "lease_expires_at",
130
+ "submission_grace_expires_at",
131
+ }
132
+ if (
133
+ self.task_prompt is None
134
+ or "entry_urls" not in self.model_fields_set
135
+ or self.lease_expires_at is None
136
+ or self.submission_grace_expires_at is None
137
+ or self.model_fields_set - allowed
138
+ ):
139
+ raise ValueError("running Arena is missing required fields")
140
+ else:
141
+ allowed = common | {
142
+ "submitted_at",
143
+ "submission_trigger",
144
+ "closed_at",
145
+ "verdict",
146
+ }
147
+ if self.model_fields_set - allowed:
148
+ raise ValueError("lifecycle Arena contains fields from another response shape")
149
+ optional_fields = {
150
+ "submitted_at",
151
+ "submission_trigger",
152
+ "closed_at",
153
+ "verdict",
154
+ }
155
+ if any(
156
+ field in self.model_fields_set and getattr(self, field) is None
157
+ for field in optional_fields
158
+ ):
159
+ raise ValueError("lifecycle Arena fields must not be null")
160
+ return self
161
+
162
+ @property
163
+ def ready(self) -> bool:
164
+ return (
165
+ self.status == "running"
166
+ and self.task_prompt is not None
167
+ and self.lease_expires_at is not None
168
+ and self.submission_grace_expires_at is not None
169
+ )
170
+
171
+
172
+ class SubmissionResult(SDKModel):
173
+ arena_id: ArenaID
174
+ status: SubmissionStatus
175
+ submitted_at: datetime
176
+ submission_trigger: Literal["manual", "deadline"]
177
+ already_submitted: StrictBool
178
+ verdict: PublicVerdict
179
+
180
+
181
+ class ChallengeTask(SDKModel):
182
+ challenge_id: ChallengeID
183
+ prompt_level: Literal["l0", "l1", "l2"] = "l0"
184
+ agent_timeout: PositiveSeconds | None = None
185
+
186
+
187
+ class RoundConfig(SDKModel):
188
+ challenges: list[ChallengeTask]
189
+ max_concurrency: int
190
+
191
+ @model_validator(mode="after")
192
+ def validate_round(self) -> RoundConfig:
193
+ if not self.challenges:
194
+ raise ValueError("challenges must not be empty")
195
+ if self.max_concurrency < 1:
196
+ raise ValueError("max_concurrency must be at least 1")
197
+ return self
198
+
199
+
200
+ class RetryPolicy(SDKModel):
201
+ initial_delay_seconds: float = 1.0
202
+ max_delay_seconds: float = 30.0
203
+ jitter_ratio: float = 0.2
204
+ capacity_wait_timeout: float | None = None
205
+ max_transient_attempts: int = 8
206
+
207
+
208
+ class TimeoutConfig(SDKModel):
209
+ connect: float = 10.0
210
+ read: float = 30.0
211
+ submit_read: float = 610.0
212
+ submit_total: float = 600.0
213
+ write: float = 30.0
214
+ pool: float = 10.0
215
+
216
+
217
+ class SchedulerEvent(SDKModel):
218
+ type: str
219
+ occurred_at: datetime
220
+ execution_id: str
221
+ round_index: int | None = None
222
+ task_id: str | None = None
223
+ challenge_id: str | None = None
224
+ arena_id: str | None = None
225
+ attempt: int | None = None
226
+ details: dict[str, JsonValue] = Field(default_factory=dict)
227
+
228
+
229
+ class TaskOutcome(SDKModel):
230
+ task_id: str
231
+ round_index: int
232
+ position: int
233
+ challenge_id: str
234
+ arena_id: str | None = None
235
+ status: TaskOutcomeStatus
236
+ submission: SubmissionResult | None = None
237
+ error_code: str | None = None
238
+ error_message: str | None = None
239
+ request_id: str | None = None
240
+
241
+
242
+ class ExecutionResult(SDKModel):
243
+ execution_id: str
244
+ status: ExecutionStatus
245
+ outcomes: list[TaskOutcome]
246
+
247
+
248
+ class ErrorEnvelope(SDKModel):
249
+ error: dict[str, Any]
File without changes
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import Sequence
5
+ from typing import Protocol
6
+
7
+ from .client import AgentCyberRangeClient
8
+ from .models import Challenge, ChallengeTask, ExecutionResult, RetryPolicy, RoundConfig
9
+ from .scheduler import ArenaReadyHandler, EventHandler, RoundScheduler, SchedulerClient
10
+
11
+ DEFAULT_BASE_URL = "https://eval.agentcyberrange.io/"
12
+
13
+
14
+ class _RunAgentClient(SchedulerClient, Protocol):
15
+ async def list_challenges(self) -> list[Challenge]: ...
16
+
17
+
18
+ async def run_agent(
19
+ agent: ArenaReadyHandler,
20
+ max_concurrency: int = 1,
21
+ *,
22
+ agent_timeout: float | None = None,
23
+ challenge_ids: Sequence[str] | None = None,
24
+ base_url: str | None = None,
25
+ task_token: str | None = None,
26
+ client: _RunAgentClient | None = None,
27
+ retry_policy: RetryPolicy | None = None,
28
+ on_event: EventHandler | None = None,
29
+ arena_ready_delay: float = 0.0,
30
+ ) -> ExecutionResult:
31
+ """Run an Agent once against every available Challenge.
32
+
33
+ Only the Agent callback is required. It may return a generated archive path for a
34
+ non-post Challenge; when it returns ``None``, the Scheduler submits a minimal empty
35
+ ``final_answer`` archive instead. Post Challenges are always submitted with an empty
36
+ body. ``max_concurrency`` defaults to one. Agent callbacks default to a
37
+ 30-minute Web timeout or a 2-hour post timeout; these are also hard maximums.
38
+ ``agent_timeout`` optionally requests one uniform limit for every selected Challenge;
39
+ the Scheduler caps it at the applicable type maximum. ``challenge_ids`` optionally
40
+ selects an ordered subset. Connection settings default to
41
+ ``AGENTCYBERRANGE_BASE_URL`` and ``AGENTCYBERRANGE_TASK_TOKEN``. Passing a client is
42
+ primarily useful for embedding and testing; a caller-owned client is not closed by
43
+ this function. ``on_event`` reports capacity waits and lifecycle failures without
44
+ disabling automatic retries. ``arena_ready_delay`` optionally waits after Fleet
45
+ reports an Arena as running before invoking the Agent callback.
46
+ """
47
+ if max_concurrency < 1:
48
+ raise ValueError("max_concurrency must be at least 1")
49
+ if agent_timeout is not None and agent_timeout <= 0:
50
+ raise ValueError("agent_timeout must be greater than zero")
51
+ if challenge_ids is not None and not challenge_ids:
52
+ raise ValueError("challenge_ids must not be empty")
53
+ if arena_ready_delay < 0:
54
+ raise ValueError("arena_ready_delay must not be negative")
55
+
56
+ owned_client: AgentCyberRangeClient | None = None
57
+ if client is None:
58
+ resolved_token = task_token or os.environ.get("AGENTCYBERRANGE_TASK_TOKEN")
59
+ if not resolved_token:
60
+ raise RuntimeError("AGENTCYBERRANGE_TASK_TOKEN is required")
61
+ owned_client = AgentCyberRangeClient(
62
+ base_url=base_url or os.environ.get("AGENTCYBERRANGE_BASE_URL", DEFAULT_BASE_URL),
63
+ task_token=resolved_token,
64
+ retry_policy=retry_policy,
65
+ )
66
+ client = owned_client
67
+
68
+ try:
69
+ challenges = await client.list_challenges()
70
+ if not challenges:
71
+ raise RuntimeError("Agent Cyber Range has no available Challenges")
72
+ if challenge_ids is not None:
73
+ available = {challenge.challenge_id: challenge for challenge in challenges}
74
+ missing = [
75
+ challenge_id for challenge_id in challenge_ids if challenge_id not in available
76
+ ]
77
+ if missing:
78
+ raise ValueError(f"unknown challenge_ids: {', '.join(missing)}")
79
+ challenges = [available[challenge_id] for challenge_id in challenge_ids]
80
+ scheduler = RoundScheduler(
81
+ client,
82
+ retry_policy=retry_policy,
83
+ arena_ready_delay=arena_ready_delay,
84
+ )
85
+ return await scheduler.run(
86
+ rounds=[
87
+ RoundConfig(
88
+ challenges=[
89
+ ChallengeTask(
90
+ challenge_id=challenge.challenge_id,
91
+ agent_timeout=agent_timeout,
92
+ )
93
+ for challenge in challenges
94
+ ],
95
+ max_concurrency=max_concurrency,
96
+ )
97
+ ],
98
+ on_arena_ready=agent,
99
+ on_event=on_event,
100
+ )
101
+ finally:
102
+ if owned_client is not None:
103
+ await owned_client.aclose()
104
+
105
+
106
+ Agent = ArenaReadyHandler
107
+
108
+ __all__ = ["Agent", "DEFAULT_BASE_URL", "run_agent"]