agentcyberrange 0.1.3__tar.gz → 0.2.0__tar.gz

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.
Files changed (22) hide show
  1. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/PKG-INFO +39 -15
  2. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/README.md +38 -14
  3. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/examples/codex_cli.py +15 -2
  4. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/__init__.py +2 -0
  5. agentcyberrange-0.2.0/src/agentcyberrange/_version.py +1 -0
  6. agentcyberrange-0.2.0/src/agentcyberrange/archive.py +59 -0
  7. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/client.py +2 -0
  8. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/errors.py +1 -0
  9. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/handles.py +15 -3
  10. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/models.py +14 -3
  11. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/runner.py +6 -3
  12. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/scheduler.py +96 -49
  13. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/state.py +2 -0
  14. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/submission.py +3 -5
  15. agentcyberrange-0.1.3/src/agentcyberrange/_version.py +0 -1
  16. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/.gitignore +0 -0
  17. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/LICENSE +0 -0
  18. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/examples/manual_client.py +0 -0
  19. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/examples/quickstart.py +0 -0
  20. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/pyproject.toml +0 -0
  21. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/src/agentcyberrange/py.typed +0 -0
  22. {agentcyberrange-0.1.3 → agentcyberrange-0.2.0}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcyberrange
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Summary: Async Python SDK for Agent Cyber Range
5
5
  Author: Agent Cyber Range contributors
6
6
  License-Expression: MIT
@@ -121,14 +121,15 @@ the final resource deadline.
121
121
  value instead of the default. For example, `agent_timeout=3600` runs
122
122
  both Web and post Agents for up to 60 minutes. The effective deadline is the earlier of
123
123
  this local limit and the Arena's `lease_expires_at`. When the local timeout is reached,
124
- the SDK signals `arena.cancel_event` and cancels the Agent callback. It then allows
125
- cancellation cleanup and Web output finalization for up to two minutes before submitting;
126
- submission happens sooner when cleanup finishes sooner. A post Challenge is submitted
127
- with an empty body. A non-post callback may return its output archive during cancellation;
128
- if no archive is available by the finalization deadline, the SDK submits a minimal empty
129
- `final_answer` archive instead. The backend closes the Arena after this terminal
130
- submission. The returned task outcome records the timeout in `error_code` and
131
- `error_message`.
124
+ the SDK signals `arena.cancel_event`. Archive callbacks should observe this event, stop
125
+ workers, collect files and return their archive. Collection gets up to two minutes for an
126
+ explicit local timeout, or 30 seconds for the default timeout, cancellation and lease
127
+ deadline. On collection failure the SDK records the error and closes the Arena without
128
+ submitting an empty archive. Empty-body Challenges submit immediately. Callbacks must
129
+ cooperate with cancellation and own subprocess/container termination: Python cannot
130
+ forcibly stop arbitrary coroutine code; a callback that suppresses cancellation may
131
+ outlive the scheduler and delay application event-loop shutdown.
132
+
132
133
 
133
134
  `on_event` receives lifecycle and retry events. Capacity waits include the HTTP status,
134
135
  error code, request ID, `Retry-After`, and attempt number in `SchedulerEvent`, so callers
@@ -147,8 +148,8 @@ The SDK automatically:
147
148
  - refills a Work Slot as soon as an Arena is submitted;
148
149
  - submits a post Challenge when the Agent returns, raises, times out, or reaches the
149
150
  server deadline;
150
- - submits a non-post Challenge with the returned output archive, or with a minimal empty
151
- `final_answer` archive when the Agent returns no path or raises.
151
+ - submits an archive Challenge only with a valid nonempty archive; missing output or
152
+ callback failures close the Arena and produce a failed Task Outcome.
152
153
 
153
154
  ## Run Codex
154
155
 
@@ -169,10 +170,10 @@ environment, so Codex cannot directly operate the control plane. If Codex create
169
170
  `final_answer/` directory for a non-post Challenge, the callback archives it under
170
171
  `.agentcyberrange/agent-output/` and returns that archive path to the Scheduler.
171
172
 
172
- When an SDK timeout or Arena deadline cancels the callback, the example first stops Codex
173
+ When an SDK timeout or Arena deadline signals the callback, the example first stops Codex
173
174
  and then archives any existing `final_answer/` before the temporary workspace is removed.
174
175
  The Scheduler submits that archive immediately. If the directory does not exist, the
175
- Scheduler submits a minimal empty `final_answer` archive instead. A post Challenge returns
176
+ Scheduler closes the Arena without submission and records missing output. A post Challenge returns
176
177
  `None` and is submitted with an empty body.
177
178
 
178
179
  ## Low-level client
@@ -225,8 +226,9 @@ The SDK resolves a relative output path against the process working directory wh
225
226
  the same archive. The file must be non-empty and no larger than 10 MiB.
226
227
 
227
228
  With `run_agent()`, return the archive path when a non-post Agent produced one. Returning
228
- `None` is valid for both Challenge types: the Scheduler uses an empty request body for a
229
- post Challenge and a minimal empty `final_answer` archive for a non-post Challenge.
229
+ `None` is valid only for an empty-body Challenge. Archive Challenges require a nonempty
230
+ regular file inside a valid archive. Validation rejects unsafe paths, links, corruption,
231
+ more than 4096 entries or more than 100 MiB of expanded data.
230
232
 
231
233
  ```python
232
234
  from agentcyberrange import AgentOutputPath, ArenaHandle
@@ -273,3 +275,25 @@ uv run python scripts/run_agent_test.py \
273
275
 
274
276
  The default base URL is `https://eval.agentcyberrange.io/`. Override it with
275
277
  `AGENTCYBERRANGE_BASE_URL` when testing another deployment.
278
+
279
+ ## Execution results and migration to 0.2.0
280
+
281
+ Use `AgentResult(agent_output=path, succeeded=False, stop_reason="abnormal_exit")`
282
+ to submit partial findings while preserving the execution failure. Set `collection_error`
283
+ when file collection failed. Returning a plain path remains supported, but cannot express
284
+ an internal engine failure. A successful worker exit code is not an engine result.
285
+
286
+ `PublicVerdict.assessment_status` defaults to `complete` for legacy responses. An
287
+ `incomplete` assessment retains its provisional score and is excluded from a successful
288
+ Execution result; do not compare that score with complete assessments. Objective counts
289
+ are optional. This SDK does not automatically resubmit an incomplete assessment.
290
+
291
+ Set `ChallengeTask(submission_mode="archive")` or `"empty_body"` explicitly; `run_agent`
292
+ also accepts this setting for all selected Challenges. When omitted, legacy IDs `post`,
293
+ `post-*` and `pb-postexp-*` use empty bodies. Arbitrary occurrences of `post` no longer
294
+ select submission behavior. Per-Challenge settings should use `RoundScheduler`.
295
+
296
+ An invalid archive rejection permits corrected submission through the same ArenaHandle.
297
+ Cancelling a caller waiting for a shared submission does not cancel the HTTP operation.
298
+ Unknown outcomes remain attached to the original operation; client transport recovery
299
+ queries Fleet before retrying. Missing output is no longer replaced with an empty tarball.
@@ -94,14 +94,15 @@ the final resource deadline.
94
94
  value instead of the default. For example, `agent_timeout=3600` runs
95
95
  both Web and post Agents for up to 60 minutes. The effective deadline is the earlier of
96
96
  this local limit and the Arena's `lease_expires_at`. When the local timeout is reached,
97
- the SDK signals `arena.cancel_event` and cancels the Agent callback. It then allows
98
- cancellation cleanup and Web output finalization for up to two minutes before submitting;
99
- submission happens sooner when cleanup finishes sooner. A post Challenge is submitted
100
- with an empty body. A non-post callback may return its output archive during cancellation;
101
- if no archive is available by the finalization deadline, the SDK submits a minimal empty
102
- `final_answer` archive instead. The backend closes the Arena after this terminal
103
- submission. The returned task outcome records the timeout in `error_code` and
104
- `error_message`.
97
+ the SDK signals `arena.cancel_event`. Archive callbacks should observe this event, stop
98
+ workers, collect files and return their archive. Collection gets up to two minutes for an
99
+ explicit local timeout, or 30 seconds for the default timeout, cancellation and lease
100
+ deadline. On collection failure the SDK records the error and closes the Arena without
101
+ submitting an empty archive. Empty-body Challenges submit immediately. Callbacks must
102
+ cooperate with cancellation and own subprocess/container termination: Python cannot
103
+ forcibly stop arbitrary coroutine code; a callback that suppresses cancellation may
104
+ outlive the scheduler and delay application event-loop shutdown.
105
+
105
106
 
106
107
  `on_event` receives lifecycle and retry events. Capacity waits include the HTTP status,
107
108
  error code, request ID, `Retry-After`, and attempt number in `SchedulerEvent`, so callers
@@ -120,8 +121,8 @@ The SDK automatically:
120
121
  - refills a Work Slot as soon as an Arena is submitted;
121
122
  - submits a post Challenge when the Agent returns, raises, times out, or reaches the
122
123
  server deadline;
123
- - submits a non-post Challenge with the returned output archive, or with a minimal empty
124
- `final_answer` archive when the Agent returns no path or raises.
124
+ - submits an archive Challenge only with a valid nonempty archive; missing output or
125
+ callback failures close the Arena and produce a failed Task Outcome.
125
126
 
126
127
  ## Run Codex
127
128
 
@@ -142,10 +143,10 @@ environment, so Codex cannot directly operate the control plane. If Codex create
142
143
  `final_answer/` directory for a non-post Challenge, the callback archives it under
143
144
  `.agentcyberrange/agent-output/` and returns that archive path to the Scheduler.
144
145
 
145
- When an SDK timeout or Arena deadline cancels the callback, the example first stops Codex
146
+ When an SDK timeout or Arena deadline signals the callback, the example first stops Codex
146
147
  and then archives any existing `final_answer/` before the temporary workspace is removed.
147
148
  The Scheduler submits that archive immediately. If the directory does not exist, the
148
- Scheduler submits a minimal empty `final_answer` archive instead. A post Challenge returns
149
+ Scheduler closes the Arena without submission and records missing output. A post Challenge returns
149
150
  `None` and is submitted with an empty body.
150
151
 
151
152
  ## Low-level client
@@ -198,8 +199,9 @@ The SDK resolves a relative output path against the process working directory wh
198
199
  the same archive. The file must be non-empty and no larger than 10 MiB.
199
200
 
200
201
  With `run_agent()`, return the archive path when a non-post Agent produced one. Returning
201
- `None` is valid for both Challenge types: the Scheduler uses an empty request body for a
202
- post Challenge and a minimal empty `final_answer` archive for a non-post Challenge.
202
+ `None` is valid only for an empty-body Challenge. Archive Challenges require a nonempty
203
+ regular file inside a valid archive. Validation rejects unsafe paths, links, corruption,
204
+ more than 4096 entries or more than 100 MiB of expanded data.
203
205
 
204
206
  ```python
205
207
  from agentcyberrange import AgentOutputPath, ArenaHandle
@@ -246,3 +248,25 @@ uv run python scripts/run_agent_test.py \
246
248
 
247
249
  The default base URL is `https://eval.agentcyberrange.io/`. Override it with
248
250
  `AGENTCYBERRANGE_BASE_URL` when testing another deployment.
251
+
252
+ ## Execution results and migration to 0.2.0
253
+
254
+ Use `AgentResult(agent_output=path, succeeded=False, stop_reason="abnormal_exit")`
255
+ to submit partial findings while preserving the execution failure. Set `collection_error`
256
+ when file collection failed. Returning a plain path remains supported, but cannot express
257
+ an internal engine failure. A successful worker exit code is not an engine result.
258
+
259
+ `PublicVerdict.assessment_status` defaults to `complete` for legacy responses. An
260
+ `incomplete` assessment retains its provisional score and is excluded from a successful
261
+ Execution result; do not compare that score with complete assessments. Objective counts
262
+ are optional. This SDK does not automatically resubmit an incomplete assessment.
263
+
264
+ Set `ChallengeTask(submission_mode="archive")` or `"empty_body"` explicitly; `run_agent`
265
+ also accepts this setting for all selected Challenges. When omitted, legacy IDs `post`,
266
+ `post-*` and `pb-postexp-*` use empty bodies. Arbitrary occurrences of `post` no longer
267
+ select submission behavior. Per-Challenge settings should use `RoundScheduler`.
268
+
269
+ An invalid archive rejection permits corrected submission through the same ArenaHandle.
270
+ Cancelling a caller waiting for a shared submission does not cancel the HTTP operation.
271
+ Unknown outcomes remain attached to the original operation; client transport recovery
272
+ queries Fleet before retrying. Missing output is no longer replaced with an empty tarball.
@@ -59,15 +59,28 @@ async def call_codex(arena: ArenaHandle) -> AgentOutputPath | None:
59
59
  env=codex_environment,
60
60
  stdin=asyncio.subprocess.PIPE,
61
61
  )
62
+ communication = asyncio.create_task(process.communicate(arena.task_prompt.encode()))
63
+ stopping = asyncio.create_task(arena.cancel_event.wait())
62
64
  try:
63
- await process.communicate(arena.task_prompt.encode())
65
+ done, _ = await asyncio.wait(
66
+ {communication, stopping}, return_when=asyncio.FIRST_COMPLETED
67
+ )
68
+ if stopping in done and not communication.done():
69
+ await stop_codex(process)
70
+ communication.cancel()
71
+ else:
72
+ await communication
64
73
  except asyncio.CancelledError:
65
74
  await stop_codex(process)
66
75
  if not arena.cancel_event.is_set():
67
76
  raise
68
77
  else:
69
- if process.returncode != 0:
78
+ if process.returncode != 0 and not arena.cancel_event.is_set():
70
79
  raise RuntimeError(f"Codex exited with status {process.returncode}")
80
+ finally:
81
+ communication.cancel()
82
+ stopping.cancel()
83
+ await asyncio.gather(communication, stopping, return_exceptions=True)
71
84
  if is_post_challenge(arena.challenge_id):
72
85
  return None
73
86
  return archive_agent_output(workspace, arena.arena_id)
@@ -20,6 +20,7 @@ from .errors import (
20
20
  from .handles import ArenaHandle
21
21
  from .models import (
22
22
  AgentOutputPath,
23
+ AgentResult,
23
24
  Arena,
24
25
  ArenaEndpoint,
25
26
  Capacity,
@@ -40,6 +41,7 @@ from .submission import is_post_challenge
40
41
 
41
42
  __all__ = [
42
43
  "AgentOutputPath",
44
+ "AgentResult",
43
45
  "Arena",
44
46
  "ArenaBusyError",
45
47
  "ArenaHandle",
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,59 @@
1
+ """Bounded archive validation; never extracts or executes agent files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import io
7
+ import tarfile
8
+ import zipfile
9
+ from pathlib import PurePosixPath
10
+
11
+
12
+ def validate_archive(content: bytes, filename: str) -> None:
13
+ total = 0
14
+ count = 0
15
+ nonempty = False
16
+
17
+ def check(name: str, size: int) -> None:
18
+ nonlocal total, count, nonempty
19
+ path = PurePosixPath(name)
20
+ if path.is_absolute() or ".." in path.parts or "\\" in name:
21
+ raise ValueError("agent_output contains an unsafe path")
22
+ count += 1
23
+ total += size
24
+ nonempty |= size > 0
25
+ if count > 4096 or total > 100 * 1024 * 1024:
26
+ raise ValueError("agent_output exceeds archive expansion limits")
27
+
28
+ try:
29
+ if filename.endswith(".zip"):
30
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
31
+ for entry in archive.infolist():
32
+ mode = entry.external_attr >> 16
33
+ if mode & 0o170000 not in (0, 0o100000, 0o040000):
34
+ raise ValueError("agent_output contains a special file")
35
+ check(entry.filename, entry.file_size)
36
+ with archive.open(entry) as stream:
37
+ while stream.read(65536):
38
+ pass
39
+ else:
40
+ # Bound the entire decompressed stream, including metadata and padding,
41
+ # and force gzip trailer/CRC validation before reading tar entries.
42
+ with gzip.GzipFile(fileobj=io.BytesIO(content)) as compressed:
43
+ expanded = compressed.read(100 * 1024 * 1024 + 1)
44
+ if len(expanded) > 100 * 1024 * 1024:
45
+ raise ValueError("agent_output exceeds archive expansion limits")
46
+ with tarfile.open(fileobj=io.BytesIO(expanded), mode="r:") as tar_archive:
47
+ for member in tar_archive:
48
+ if not (member.isfile() or member.isdir()):
49
+ raise ValueError("agent_output contains a special file")
50
+ check(member.name, member.size)
51
+ tar_stream = tar_archive.extractfile(member) if member.isfile() else None
52
+ if tar_stream is not None:
53
+ with tar_stream:
54
+ while tar_stream.read(65536):
55
+ pass
56
+ except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError, RuntimeError) as exc:
57
+ raise ValueError("agent_output is not a valid archive") from exc
58
+ if not nonempty:
59
+ raise ValueError("agent_output must contain a nonempty regular file")
@@ -13,6 +13,7 @@ import httpx
13
13
  from pydantic import BaseModel, ValidationError
14
14
 
15
15
  from ._version import __version__
16
+ from .archive import validate_archive
16
17
  from .errors import (
17
18
  AgentCyberRangeError,
18
19
  ArenaBusyError,
@@ -437,6 +438,7 @@ class AgentCyberRangeClient:
437
438
  if len(content) > MAX_AGENT_OUTPUT_BYTES:
438
439
  raise ValueError("agent_output must not exceed 10 MiB")
439
440
 
441
+ validate_archive(content, filename)
440
442
  return {"agent_output": (filename, content, "application/octet-stream")}
441
443
 
442
444
  async def _recover_submission(
@@ -92,6 +92,7 @@ class TransportError(AgentCyberRangeError):
92
92
 
93
93
  ERROR_TYPES: dict[str, type[AgentCyberRangeError]] = {
94
94
  "invalid_request": InvalidRequestError,
95
+ "invalid_agent_output": InvalidRequestError,
95
96
  "agent_output_too_large": InvalidRequestError,
96
97
  "invalid_token": AuthenticationError,
97
98
  "revoked_token": RevokedTokenError,
@@ -5,6 +5,7 @@ from collections.abc import Awaitable, Callable
5
5
  from datetime import datetime
6
6
  from typing import Literal, Protocol
7
7
 
8
+ from .errors import InvalidRequestError
8
9
  from .models import AgentOutputPath, Arena, ArenaEndpoint, SubmissionResult
9
10
 
10
11
 
@@ -23,8 +24,7 @@ class ArenaHandle:
23
24
  client: SubmitClient,
24
25
  arena: Arena,
25
26
  *,
26
- on_submit_started: Callable[[Literal["manual", "deadline"]], Awaitable[None]]
27
- | None = None,
27
+ on_submit_started: Callable[[Literal["manual", "deadline"]], Awaitable[None]] | None = None,
28
28
  ) -> None:
29
29
  if not arena.ready:
30
30
  raise ValueError("ArenaHandle requires a ready running Arena")
@@ -38,6 +38,10 @@ class ArenaHandle:
38
38
  self._submitted = asyncio.Event()
39
39
  self._submit_trigger: Literal["manual", "deadline"] = "manual"
40
40
 
41
+ @property
42
+ def submission_result(self) -> SubmissionResult | None:
43
+ return self._result
44
+
41
45
  @property
42
46
  def arena_id(self) -> str:
43
47
  return self.arena.arena_id
@@ -80,7 +84,15 @@ class ArenaHandle:
80
84
  )
81
85
  self._submit_task = asyncio.create_task(submit)
82
86
  task = self._submit_task
83
- result = await task
87
+ try:
88
+ result = await asyncio.shield(task)
89
+ except (InvalidRequestError, ValueError):
90
+ # A definite rejection permits a corrected archive. Unknown outcomes
91
+ # stay attached to the original operation and must be recovered first.
92
+ async with self._submit_lock:
93
+ if self._submit_task is task:
94
+ self._submit_task = None
95
+ raise
84
96
  async with self._submit_lock:
85
97
  self._result = result
86
98
  self._submitted.set()
@@ -32,9 +32,7 @@ ArenaStatus: TypeAlias = Literal[
32
32
  "lost",
33
33
  ]
34
34
  ExecutionStatus: TypeAlias = Literal["completed", "completed_with_errors", "cancelled"]
35
- TaskOutcomeStatus: TypeAlias = Literal[
36
- "submitted", "not_found", "failed", "lost", "cancelled"
37
- ]
35
+ TaskOutcomeStatus: TypeAlias = Literal["submitted", "not_found", "failed", "lost", "cancelled"]
38
36
  ChallengeID: TypeAlias = Annotated[
39
37
  StrictStr,
40
38
  StringConstraints(
@@ -97,6 +95,9 @@ class ArenaEndpoint(SDKModel):
97
95
 
98
96
 
99
97
  class PublicVerdict(SDKModel):
98
+ assessment_status: Literal["complete", "incomplete"] = "complete"
99
+ objective_achieved: NonNegativeInt | None = None
100
+ objective_total: NonNegativeInt | None = None
100
101
  score: StrictFloat
101
102
  passed: StrictBool
102
103
  summary: StrictStr
@@ -179,7 +180,17 @@ class SubmissionResult(SDKModel):
179
180
  verdict: PublicVerdict
180
181
 
181
182
 
183
+ class AgentResult(SDKModel):
184
+ """Execution and collection status, independent of the scoring result."""
185
+
186
+ agent_output: AgentOutputPath | None = None
187
+ succeeded: StrictBool
188
+ stop_reason: str | None = None
189
+ collection_error: str | None = None
190
+
191
+
182
192
  class ChallengeTask(SDKModel):
193
+ submission_mode: Literal["archive", "empty_body"] | None = None
183
194
  challenge_id: ChallengeID
184
195
  prompt_level: Literal["l0", "l1", "l2"] = "l0"
185
196
  agent_timeout: PositiveSeconds | None = None
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import os
4
4
  from collections.abc import Sequence
5
- from typing import Protocol
5
+ from typing import Literal, Protocol
6
6
 
7
7
  from .client import AgentCyberRangeClient
8
8
  from .models import Challenge, ChallengeTask, ExecutionResult, RetryPolicy, RoundConfig
@@ -20,6 +20,7 @@ async def run_agent(
20
20
  max_concurrency: int = 1,
21
21
  *,
22
22
  agent_timeout: float | None = None,
23
+ submission_mode: Literal["archive", "empty_body"] | None = None,
23
24
  challenge_ids: Sequence[str] | None = None,
24
25
  base_url: str | None = None,
25
26
  task_token: str | None = None,
@@ -32,8 +33,9 @@ async def run_agent(
32
33
 
33
34
  Args:
34
35
  agent: Async callback invoked with a ready Arena. Return a ``.tar.gz`` or
35
- ``.zip`` output path for a non-post Challenge, or ``None`` to let the SDK
36
- submit a minimal empty ``final_answer`` archive. Post Challenges are always
36
+ ``.zip`` output path for a non-post Challenge, or an ``AgentResult`` carrying
37
+ execution and collection status.
38
+ Missing archives fail without submission. Post Challenges are always
37
39
  submitted with an empty body.
38
40
  max_concurrency: Maximum number of Challenge Tasks active at once. Defaults to 1.
39
41
  agent_timeout: Local Agent runtime limit in seconds for every selected Challenge.
@@ -107,6 +109,7 @@ async def run_agent(
107
109
  ChallengeTask(
108
110
  challenge_id=challenge.challenge_id,
109
111
  agent_timeout=agent_timeout,
112
+ submission_mode=submission_mode,
110
113
  )
111
114
  for challenge in challenges
112
115
  ],
@@ -2,13 +2,10 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import random
5
- import tarfile
6
- import tempfile
7
5
  from collections.abc import Awaitable, Callable, Sequence
8
6
  from contextlib import suppress
9
7
  from datetime import UTC, datetime
10
- from pathlib import Path
11
- from typing import Literal, Protocol, cast
8
+ from typing import Any, Literal, Protocol, cast
12
9
  from uuid import uuid4
13
10
 
14
11
  from pydantic import JsonValue
@@ -25,6 +22,7 @@ from .errors import (
25
22
  from .handles import ArenaHandle
26
23
  from .models import (
27
24
  AgentOutputPath,
25
+ AgentResult,
28
26
  Arena,
29
27
  ExecutionResult,
30
28
  ExecutionStatus,
@@ -37,12 +35,17 @@ from .models import (
37
35
  from .state import RuntimeState, StoredTask
38
36
  from .submission import is_post_challenge, resolve_agent_timeout
39
37
 
40
- ArenaReadyHandler = Callable[[ArenaHandle], Awaitable[AgentOutputPath | None]]
38
+ ArenaReadyHandler = Callable[[ArenaHandle], Awaitable[AgentOutputPath | AgentResult | None]]
41
39
  EventHandler = Callable[[SchedulerEvent], Awaitable[None] | None]
42
40
  AGENT_OUTPUT_FINALIZATION_TIMEOUT_SECONDS = 30.0
43
41
  CUSTOM_TIMEOUT_FINALIZATION_SECONDS = 2 * 60.0
44
42
 
45
43
 
44
+ def _consume_task_exception(task: asyncio.Future[Any]) -> None:
45
+ if not task.cancelled():
46
+ task.exception()
47
+
48
+
46
49
  def _error_details(error: AgentCyberRangeError) -> dict[str, JsonValue]:
47
50
  details: dict[str, JsonValue] = {}
48
51
  if error.error_code is not None:
@@ -409,7 +412,11 @@ class RoundScheduler:
409
412
  else:
410
413
  await self._finish_error(task, "failed", exc, on_event, "arena_failed")
411
414
  return
412
- except SubmissionFailedError as exc:
415
+ except AuthenticationError:
416
+ raise
417
+ except AgentCyberRangeError as exc:
418
+ if not isinstance(exc, SubmissionFailedError):
419
+ await self._client.close(arena.arena_id)
413
420
  self._state.update_task(
414
421
  task.id,
415
422
  status="failed",
@@ -453,8 +460,7 @@ class RoundScheduler:
453
460
  await asyncio.shield(cleanup)
454
461
  except BaseException as cleanup_error:
455
462
  error.add_note(
456
- f"Failed to close Arena {arena.arena_id} during cleanup: "
457
- f"{cleanup_error}"
463
+ f"Failed to close Arena {arena.arena_id} during cleanup: {cleanup_error}"
458
464
  )
459
465
  raise
460
466
  finally:
@@ -467,14 +473,27 @@ class RoundScheduler:
467
473
  on_event: EventHandler | None,
468
474
  task: StoredTask,
469
475
  ) -> tuple[SubmissionResult | None, str | None, str | None]:
470
- callback_task: asyncio.Future[AgentOutputPath | None] = asyncio.ensure_future(
471
- callback(handle)
476
+ agent_result: AgentResult | None = None
477
+
478
+ async def invoke_agent() -> AgentOutputPath | None:
479
+ nonlocal agent_result
480
+ result = await callback(handle)
481
+ if isinstance(result, AgentResult):
482
+ agent_result = result
483
+ return result.agent_output
484
+ return result
485
+
486
+ empty_body = (
487
+ task.submission_mode == "empty_body"
488
+ if task.submission_mode is not None
489
+ else is_post_challenge(handle.challenge_id)
472
490
  )
491
+ callback_task = asyncio.ensure_future(invoke_agent())
473
492
  submitted_task = asyncio.create_task(handle.wait_submitted())
474
493
  deadline_task = asyncio.create_task(self._wait_for_deadline(handle))
475
494
  timeout_task = asyncio.create_task(
476
495
  self._wait_for_agent_timeout(
477
- resolve_agent_timeout(handle.challenge_id, task.agent_timeout)
496
+ resolve_agent_timeout("post" if empty_body else "web", task.agent_timeout)
478
497
  )
479
498
  )
480
499
  cancel_task = asyncio.create_task(self._cancel_event.wait())
@@ -501,11 +520,10 @@ class RoundScheduler:
501
520
  error_message: str | None = None
502
521
  if cancel_task in done:
503
522
  handle.cancel_event.set()
504
- callback_task.cancel()
505
523
  if self._cancel_mode == "close":
506
524
  await self._client.close(handle.arena_id)
507
525
  submission = None
508
- elif is_post_challenge(handle.challenge_id):
526
+ elif empty_body:
509
527
  submission = await handle.submit()
510
528
  else:
511
529
  submission = await self._submit_cancelled_non_post(
@@ -515,13 +533,11 @@ class RoundScheduler:
515
533
  )
516
534
  elif external_task in done:
517
535
  handle.cancel_event.set()
518
- callback_task.cancel()
519
536
  submission = external_task.result()
520
- elif submitted_task in done:
521
- submission = submitted_task.result()
537
+ elif submitted_task in done or handle.submission_result is not None:
538
+ submission = await handle.wait_submitted()
522
539
  elif deadline_task in done:
523
540
  handle.cancel_event.set()
524
- callback_task.cancel()
525
541
  await self._emit(
526
542
  on_event,
527
543
  "arena_deadline_reached",
@@ -531,7 +547,7 @@ class RoundScheduler:
531
547
  )
532
548
  error_code = "agent_deadline_reached"
533
549
  error_message = "Arena deadline was reached before the Agent returned"
534
- if is_post_challenge(handle.challenge_id):
550
+ if empty_body:
535
551
  submission = await handle.submit_at_deadline()
536
552
  else:
537
553
  submission = await self._submit_cancelled_non_post(
@@ -541,7 +557,6 @@ class RoundScheduler:
541
557
  )
542
558
  elif timeout_task in done:
543
559
  handle.cancel_event.set()
544
- callback_task.cancel()
545
560
  await self._emit(
546
561
  on_event,
547
562
  "agent_timeout_reached",
@@ -551,12 +566,7 @@ class RoundScheduler:
551
566
  )
552
567
  error_code = "agent_timeout_reached"
553
568
  error_message = "Agent did not return before its configured timeout"
554
- if is_post_challenge(handle.challenge_id):
555
- if task.agent_timeout is not None:
556
- await self._cancelled_agent_output(
557
- callback_task,
558
- timeout_seconds=CUSTOM_TIMEOUT_FINALIZATION_SECONDS,
559
- )
569
+ if empty_body:
560
570
  submission = await handle.submit()
561
571
  else:
562
572
  submission = await self._submit_cancelled_non_post(
@@ -583,26 +593,57 @@ class RoundScheduler:
583
593
  task=task,
584
594
  arena=handle.arena,
585
595
  )
586
- if is_post_challenge(handle.challenge_id):
596
+ if error_code is not None and not empty_body:
597
+ raise AgentCyberRangeError(error_message or error_code, error_code=error_code)
598
+ if (
599
+ agent_result is not None
600
+ and agent_output is None
601
+ and (not agent_result.succeeded or agent_result.collection_error)
602
+ ):
603
+ raise AgentCyberRangeError(
604
+ agent_result.collection_error or agent_result.stop_reason or "Agent failed",
605
+ error_code=(
606
+ "agent_collection_failed"
607
+ if agent_result.collection_error
608
+ else "agent_execution_failed"
609
+ ),
610
+ )
611
+ if empty_body:
587
612
  submission = await handle.submit()
588
613
  else:
589
614
  if agent_output is None:
590
615
  error_code = error_code or "agent_output_required"
591
616
  error_message = error_message or (
592
617
  "Non-post Challenge did not return an output archive; "
593
- "an empty final_answer archive was submitted"
618
+ "no submission was made"
594
619
  )
595
620
  submission = await self._submit_non_post(
596
621
  handle,
597
622
  agent_output,
598
623
  deadline=False,
599
624
  )
625
+ if agent_result is not None:
626
+ if agent_result.collection_error:
627
+ error_code = "agent_collection_failed"
628
+ error_message = agent_result.collection_error
629
+ elif not agent_result.succeeded:
630
+ error_code = "agent_execution_failed"
631
+ error_message = agent_result.stop_reason or "Agent execution failed"
632
+ if submission is not None and submission.verdict.assessment_status == "incomplete":
633
+ error_code = error_code or "assessment_incomplete"
634
+ error_message = error_message or "Assessment did not complete"
600
635
  return submission, error_code, error_message
601
636
  finally:
602
637
  for child_task in child_tasks:
603
638
  if not child_task.done():
604
639
  child_task.cancel()
605
- await asyncio.gather(*child_tasks, return_exceptions=True)
640
+ # Do not let a callback that suppresses cancellation hold the slot forever.
641
+ done_tasks, pending = await asyncio.wait(child_tasks, timeout=0.1)
642
+ for child in done_tasks:
643
+ if not child.cancelled():
644
+ child.exception()
645
+ for child in pending:
646
+ child.add_done_callback(_consume_task_exception)
606
647
 
607
648
  @staticmethod
608
649
  async def _cancelled_agent_output(
@@ -610,15 +651,23 @@ class RoundScheduler:
610
651
  *,
611
652
  timeout_seconds: float = AGENT_OUTPUT_FINALIZATION_TIMEOUT_SECONDS,
612
653
  ) -> AgentOutputPath | None:
613
- try:
614
- return await asyncio.wait_for(
615
- callback_task,
616
- timeout=timeout_seconds,
654
+ done, _ = await asyncio.wait({callback_task}, timeout=timeout_seconds)
655
+ if not done:
656
+ callback_task.cancel()
657
+ raise AgentCyberRangeError(
658
+ "Agent output collection exceeded its deadline",
659
+ error_code="agent_collection_timeout",
617
660
  )
618
- except asyncio.CancelledError:
619
- return None
620
- except Exception:
621
- return None
661
+ try:
662
+ return callback_task.result()
663
+ except asyncio.CancelledError as exc:
664
+ raise AgentCyberRangeError(
665
+ "Agent cancelled before collecting output", error_code="agent_collection_cancelled"
666
+ ) from exc
667
+ except Exception as exc:
668
+ raise AgentCyberRangeError(
669
+ f"{type(exc).__name__}: {exc}", error_code="agent_collection_failed"
670
+ ) from exc
622
671
 
623
672
  async def _submit_cancelled_non_post(
624
673
  self,
@@ -642,19 +691,17 @@ class RoundScheduler:
642
691
  deadline: bool,
643
692
  ) -> SubmissionResult:
644
693
  if agent_output is not None:
645
- if deadline:
646
- return await handle.submit_at_deadline(agent_output=agent_output)
647
- return await handle.submit(agent_output=agent_output)
648
-
649
- with tempfile.TemporaryDirectory(prefix="agentcyberrange-empty-output-") as directory:
650
- final_answer = Path(directory) / "final_answer"
651
- final_answer.mkdir()
652
- output_path = Path(directory) / f"{handle.arena_id}.tar.gz"
653
- with tarfile.open(output_path, "w:gz") as archive:
654
- archive.add(final_answer, arcname="final_answer")
655
- if deadline:
656
- return await handle.submit_at_deadline(agent_output=output_path)
657
- return await handle.submit(agent_output=output_path)
694
+ try:
695
+ if deadline:
696
+ return await handle.submit_at_deadline(agent_output=agent_output)
697
+ return await handle.submit(agent_output=agent_output)
698
+ except ValueError as exc:
699
+ raise AgentCyberRangeError(str(exc), error_code="invalid_agent_output") from exc
700
+
701
+ raise AgentCyberRangeError(
702
+ "Non-post Challenge did not return an output archive; no submission was made",
703
+ error_code="agent_output_required",
704
+ )
658
705
 
659
706
  async def _wait_for_deadline(self, handle: ArenaHandle) -> None:
660
707
  seconds = max(0.0, (handle.lease_expires_at - self._now()).total_seconds())
@@ -36,6 +36,7 @@ class StoredTask:
36
36
  prompt_level: str
37
37
  agent_timeout: float | None
38
38
  idempotency_key: str
39
+ submission_mode: Literal["archive", "empty_body"] | None = None
39
40
  arena_id: str | None = None
40
41
  status: StoredTaskStatus = "pending"
41
42
  submission: SubmissionResult | None = None
@@ -62,6 +63,7 @@ class RuntimeState:
62
63
  challenge_id=challenge.challenge_id,
63
64
  prompt_level=challenge.prompt_level,
64
65
  agent_timeout=challenge.agent_timeout,
66
+ submission_mode=challenge.submission_mode,
65
67
  idempotency_key=str(uuid4()),
66
68
  )
67
69
  self._tasks[task.id] = task
@@ -5,8 +5,8 @@ POST_AGENT_TIMEOUT_SECONDS = 2 * 60 * 60
5
5
 
6
6
 
7
7
  def is_post_challenge(challenge_id: str) -> bool:
8
- """Return whether a Challenge uses the empty-body post submission mode."""
9
- return "post" in challenge_id
8
+ """Identify the legacy post namespace; prefer explicit submission_mode."""
9
+ return challenge_id == "post" or challenge_id.startswith(("pb-postexp-", "post-"))
10
10
 
11
11
 
12
12
  def resolve_agent_timeout(challenge_id: str, requested_timeout: float | None) -> float:
@@ -14,9 +14,7 @@ def resolve_agent_timeout(challenge_id: str, requested_timeout: float | None) ->
14
14
  if requested_timeout is not None:
15
15
  return requested_timeout
16
16
  default = (
17
- POST_AGENT_TIMEOUT_SECONDS
18
- if is_post_challenge(challenge_id)
19
- else WEB_AGENT_TIMEOUT_SECONDS
17
+ POST_AGENT_TIMEOUT_SECONDS if is_post_challenge(challenge_id) else WEB_AGENT_TIMEOUT_SECONDS
20
18
  )
21
19
  return float(default)
22
20
 
@@ -1 +0,0 @@
1
- __version__ = "0.1.3"
File without changes
File without changes