ctfy.sdk.resources.instances

client.instances — launch, control, status, attachments, traffic.

Flat /instances/{id} ops plus the per-competition scoped twins (*_scoped) for callers who play in more than one competition and must address an instance unambiguously.

  1"""``client.instances`` — launch, control, status, attachments, traffic.
  2
  3Flat ``/instances/{id}`` ops plus the per-competition scoped twins
  4(``*_scoped``) for callers who play in more than one competition and must
  5address an instance unambiguously.
  6"""
  7
  8from __future__ import annotations
  9
 10import time
 11from collections.abc import Iterator
 12from typing import Any
 13
 14import httpx
 15
 16from ctfy.core.attachment_layout import attachment_url_path
 17from ctfy.core.enums import InstanceStatus
 18from ctfy.sdk._helpers import (
 19    InstanceReadyResult,
 20    PagedList,
 21    _extract_items,
 22    _poll_instance_ready,
 23    _raise_for_status,
 24)
 25from ctfy.sdk.base import BaseHttpClient
 26from ctfy.server.models import (
 27    AttachmentList,
 28    InstanceInfo,
 29    InstanceQuestionInfo,
 30    InstanceStatusResponse,
 31    PlayerShellTicket,
 32    RenewResponse,
 33    SharedEnvReportResult,
 34    SshCredential,
 35    StartHistory,
 36    StartResponse,
 37    StopResponse,
 38)
 39
 40__all__ = ["InstanceStopFailed", "InstancesResource"]
 41
 42
 43class InstanceStopFailed(RuntimeError):
 44    """The platform tried the stop and the instance's node refused it (#3736).
 45
 46    The box is still running and still listed; ``reason`` is the row's
 47    ``error_code`` (``node_stop_failed``). Stopping it again asks again.
 48    """
 49
 50    def __init__(self, instance_id: str, reason: str) -> None:
 51        super().__init__(f"instance {instance_id} was not stopped: {reason}")
 52        self.instance_id = instance_id
 53        self.reason = reason
 54
 55
 56class InstancesResource:
 57    """Start / inspect / tear down challenge instances."""
 58
 59    def __init__(self, http: BaseHttpClient) -> None:
 60        self._http = http
 61
 62    def start(
 63        self,
 64        challenge_id: str,
 65        ttl: int | None = None,
 66        *,
 67        competition_id: str = "",
 68        timeout: int = 300,
 69        poll_interval: float = 2.0,
 70    ) -> InstanceReadyResult:
 71        """Start instance and wait until ready.
 72
 73        Returns InstanceReadyResult with attack surface + sandbox network info.
 74        The .surface attribute provides backward compatibility.
 75
 76        **A shared challenge** (``InstanceInfo.shared`` / ``ChallengeInfo.shared``)
 77        is one environment for several teams: this call returns the box your
 78        group already shares (starting it if none is running), the flag is
 79        the same value for everyone on it, and you can neither ``stop``,
 80        ``renew`` nor ``reset`` it -- those answer 403, the organisers reset
 81        it. If it looks broken, :meth:`report_issue`. Your solves, wrong
 82        attempts and unlocked questions are still your own team's.
 83
 84        Args:
 85            challenge_id: Challenge ID (e.g., "XBOW-047").
 86            ttl: Per-instance TTL override in seconds. ``None`` (the
 87                default) delegates to the platform's
 88                ``default_instance_ttl_s`` setting (admin-tunable,
 89                currently 24h). Explicit values are clamped to the
 90                platform's ``max_instance_ttl_s``.
 91            competition_id: Which competition to spin the instance up
 92                under. Required when the calling user is on more than
 93                one team — agents tied to a single comp can leave it
 94                empty and the server picks the unambiguous team.
 95            timeout: Max seconds to wait for ready.
 96            poll_interval: Seconds between status polls.
 97
 98        ⚠️ **There is no ``proxy_output_dir`` here, and its absence is
 99        the feature.** It used to be a field on the player's own start
100        request, passed through the platform untouched and landing on
101        ``output_path.mkdir(parents=True, exist_ok=True)`` followed by
102        ``output_path.chmod(0o777)`` on a worker node, as root. Where a
103        capture goes is the *node's* decision — it reads
104        ``proxy_output_host_root`` from its own config, which the
105        rendered compose already sets — so a caller naming a host path
106        on somebody else's worker was never answering a question that
107        was theirs to answer.
108        """
109        start = self.begin_start(challenge_id, ttl, competition_id=competition_id)
110        return _poll_instance_ready(
111            self._http._client, start.id, timeout=timeout, poll_interval=poll_interval
112        )
113
114    def begin_start(
115        self, challenge_id: str, ttl: int | None = None, *, competition_id: str = ""
116    ) -> StartResponse:
117        """``POST /instances`` alone: the platform's ``202``, without the wait.
118
119        :meth:`start` is this plus the readiness wait. The remote MCP's
120        ``start_instance`` uses the two halves apart (#3649), so its wait
121        sleeps on the event loop instead of on a thread; the
122        :class:`StartResponse` carries ``start_wait`` for a start in line.
123        """
124        body: dict[str, Any] = {
125            "challenge_id": challenge_id,
126            "competition_id": competition_id,
127        }
128        if ttl is not None:
129            body["ttl"] = ttl
130        resp = self._http.request("POST", "/instances", json=body)
131        _raise_for_status(resp)
132        return StartResponse.model_validate(resp.json())
133
134    def status_read(self, instance_id: str) -> httpx.Response:
135        """One raw ``GET /instances/{id}/status``, as the readiness wait reads it.
136
137        Unretried and unraised, exactly the read :meth:`start`'s wait makes:
138        :class:`~ctfy.sdk._helpers.ReadyWait` decides what a 404, a 5xx or a
139        transport error means. :meth:`status` is the typed read.
140        """
141        return self._http._client.get(f"/instances/{instance_id}/status")
142
143    def get(self, instance_id: str) -> InstanceInfo:
144        """Get the full ``InstanceInfo`` for one running instance.
145
146        Carries the per-instance ``questions`` list with each question's
147        ``unlocked`` / ``answered_correctly`` / ``attempts_remaining``
148        state — the surface multi-milestone solvers iterate on. The
149        prompt is empty for still-locked questions so the route hint
150        doesn't leak before the prerequisite is solved.
151
152        See :meth:`status` for the lighter status-only payload (no
153        questions, no spec metadata) used by polling loops.
154        """
155        resp = self._http.request("GET", f"/instances/{instance_id}")
156        _raise_for_status(resp)
157        return InstanceInfo.model_validate(resp.json())
158
159    def iter_pending_questions(self, instance_id: str) -> Iterator[InstanceQuestionInfo]:
160        """Yield each currently-pending question on a running instance.
161
162        "Pending" = unlocked (the ``requires:`` chain is satisfied)
163        and not yet correctly answered by the calling team. After
164        every batch is exhausted, re-fetches ``InstanceInfo`` so
165        newly-unlocked questions (whose prerequisite was just solved
166        by the consumer) flow through on the next iteration.
167
168        Terminates on either:
169
170        * no pending questions left — the natural "challenge fully
171          solved" exit;
172        * **no progress** — the same set of pending question ids
173          comes back twice in a row, meaning the consumer's solver
174          isn't capturing anything. Stops silently rather than
175          infinite-looping; inspect the caller's last :meth:`get` to
176          see what's still stuck.
177
178        This is the ergonomic helper for the common multi-milestone
179        loop::
180
181            for q in client.instances.iter_pending_questions(instance_id):
182                ans = my_solver(q.prompt)
183                client.submissions.submit(instance_id, ans, question_id=q.id)
184
185        Args:
186            instance_id: The instance to walk.
187        """
188        previous_pending_ids: frozenset[str] | None = None
189        while True:
190            info = self.get(instance_id)
191            pending = [q for q in info.questions if q.unlocked and not q.answered_correctly]
192            if not pending:
193                return
194
195            pending_ids = frozenset(q.id for q in pending)
196            if pending_ids == previous_pending_ids:
197                # Solver made no progress against the last batch — stop
198                # rather than spin. The consumer can re-call this method
199                # later (after fixing their solver) to pick up where
200                # they left off.
201                return
202            previous_pending_ids = pending_ids
203
204            yield from pending
205
206    def status(self, instance_id: str) -> InstanceStatusResponse:
207        """Get instance status and attack surface."""
208        resp = self._http.request("GET", f"/instances/{instance_id}/status")
209        _raise_for_status(resp)
210        return InstanceStatusResponse.model_validate(resp.json())
211
212    def start_history(self, instance_id: str) -> StartHistory:
213        """The challenge's past starts on this start's footing (#3669): the
214        newest measured durations, ascending, and their p50 / p90 -- empty
215        below the minimum sample count, never a guess."""
216        resp = self._http.request("GET", f"/instances/{instance_id}/start-history")
217        _raise_for_status(resp)
218        return StartHistory.model_validate(resp.json())
219
220    def stop(
221        self,
222        instance_id: str,
223        *,
224        wait: bool = False,
225        timeout: float = 180.0,
226        poll_interval: float = 1.0,
227    ) -> StopResponse:
228        """Tear down ``instance_id``. Idempotent: a 404 from the server
229        means the instance is already gone (auto-stopped after solve,
230        TTL expiry, admin teardown) and is treated as success.
231
232        ⚠️ **The platform answers once the stop is handed off** (#3736):
233        ``status="stopping"``, and the box goes once its node confirms. A
234        ``stopping`` box still holds its team's slot, so a caller that
235        starts another next -- under a per-team cap of one, say -- passes
236        ``wait=True``: this then polls the instance until it is gone
237        (``status="stopped"``), raises :class:`InstanceStopFailed` if the
238        node refused the stop (the box is still running and listed, with
239        ``error_code="node_stop_failed"``), and ``TimeoutError`` after
240        *timeout* seconds still stopping. A second call on a stopping box
241        starts nothing and answers ``stopping`` again.
242        """
243        resp = self._http.request("DELETE", f"/instances/{instance_id}")
244        if resp.status_code == 404:
245            return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
246        _raise_for_status(resp)
247        answer = StopResponse.model_validate(resp.json())
248        if wait and answer.status == InstanceStatus.STOPPING:
249            return self.wait_stopped(instance_id, timeout=timeout, poll_interval=poll_interval)
250        return answer
251
252    def wait_stopped(
253        self, instance_id: str, *, timeout: float = 180.0, poll_interval: float = 1.0
254    ) -> StopResponse:
255        """Poll ``instance_id`` until its stop is done (#3736); see :meth:`stop`.
256
257        A transport error or a 5xx is no answer and is asked again; a ``404``
258        is the confirmation (the row is gone -- or, when its node was not
259        answering, out of the team's list and torn down when it returns).
260        """
261        deadline = time.monotonic() + timeout
262        while True:
263            try:
264                resp = self._http.request("GET", f"/instances/{instance_id}")
265            except httpx.TransportError:
266                resp = None
267            if resp is not None and resp.status_code == 404:
268                return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
269            if resp is not None and resp.status_code < 500:
270                _raise_for_status(resp)
271                info = InstanceInfo.model_validate(resp.json())
272                if info.status != InstanceStatus.STOPPING:
273                    raise InstanceStopFailed(instance_id, info.error_code or info.status.value)
274            if time.monotonic() >= deadline:
275                raise TimeoutError(f"instance {instance_id} still stopping after {timeout:.0f}s")
276            time.sleep(poll_interval)
277
278    def reset(self, instance_id: str, ttl: int | None = None) -> StartResponse:
279        """Swap ``instance_id`` for a freshly-built one, atomically.
280
281        Returns the **new** instance id — the old one is gone. Prefer
282        this over ``stop`` + ``start``: the team's slot is never
283        released between the two, so a full platform can still reset,
284        and every refusal (unknown challenge, no node with room) is
285        decided before the running environment is torn down.
286
287        Minted answers are new; solves, the ``requires:`` reveal chain
288        and the per-question wrong-attempt counters are keyed
289        ``(team, challenge)`` and carry over untouched.
290        """
291        params: dict[str, Any] = {}
292        if ttl is not None:
293            params["ttl"] = ttl
294        resp = self._http.request("POST", f"/instances/{instance_id}/reset", params=params)
295        _raise_for_status(resp)
296        return StartResponse.model_validate(resp.json())
297
298    def renew(self, instance_id: str, ttl: int | None = None) -> RenewResponse:
299        """Extend the TTL of a running instance.
300
301        ``ttl`` is an **increment**, not a new lifetime: it is added to
302        whatever time the box has left, and the resulting deadline is
303        capped at ``max_instance_ttl_s`` seconds from now. So a renewal
304        can never move a deadline backwards, and one on a box already
305        at the ceiling is a no-op rather than a refusal.
306
307        ``ttl=None`` (the default) delegates to the platform's
308        ``default_instance_ttl_s`` setting.
309
310        Read the granted deadline off ``RenewResponse.expires_at``
311        rather than computing it — see
312        :func:`ctfy.core.instance_ttl.plan_renewal`. ``0.0`` there means
313        the instance has no deadline at all (an AWD match gamebox), so
314        there was nothing to extend.
315        """
316        params: dict[str, Any] = {}
317        if ttl is not None:
318            params["ttl"] = ttl
319        resp = self._http.request("POST", f"/instances/{instance_id}/renew", params=params)
320        _raise_for_status(resp)
321        return RenewResponse.model_validate(resp.json())
322
323    def report_issue(self, instance_id: str) -> SharedEnvReportResult:
324        """Tell the organisers that a *shared* environment looks broken.
325
326        The only action a player has on a shared box: it changes nothing,
327        the organisers decide whether to reset. Limited to one report per
328        team per challenge every few minutes (429 ``shared_report_rate_limited``
329        beyond that); 409 on a box that is yours alone -- reset that one
330        yourself.
331        """
332        resp = self._http.request("POST", f"/instances/{instance_id}/report-issue")
333        _raise_for_status(resp)
334        return SharedEnvReportResult.model_validate(resp.json())
335
336    def shell_session(self, instance_id: str, *, shell: str = "bash") -> PlayerShellTicket:
337        """Mint a single-use ticket for a shell into your own AWD+ box.
338
339        This wraps the *mint* only. Opening the WebSocket the ticket
340        names is the caller's job, because the SDK is a sync httpx
341        client and a shell is a long-lived bidirectional stream — the
342        same reason ``events()`` is not a plain request. ``ctfy patch
343        shell`` is the reference consumer.
344
345        No container argument: the platform resolves the target from the
346        challenge's ``patch.live.service``, and answers
347        ``shell_unsupported`` for a challenge that declares none.
348        """
349        resp = self._http.request(
350            "POST",
351            f"/instances/{instance_id}/shell/sessions",
352            json={"shell": shell},
353        )
354        _raise_for_status(resp)
355        return PlayerShellTicket.model_validate(resp.json())
356
357    def ssh_credential(self, instance_id: str) -> SshCredential:
358        """Mint a short-lived SSH certificate for your own AWD+ box.
359
360        The other half of ``shell_session``: same authorisation, same
361        target, a different protocol in front of it. A defender who
362        would rather use ``ssh`` (and every agent that already drives
363        one) gets a throwaway keypair plus a certificate, and presents
364        them to the bastion — which trades the authenticated subject
365        back for the very ticket ``shell_session`` returns.
366
367        The credential expires in minutes: it only has to cover
368        *connecting*, and the session it opens outlives it. Ask again
369        rather than caching one.
370        """
371        resp = self._http.request("POST", f"/instances/{instance_id}/ssh")
372        _raise_for_status(resp)
373        return SshCredential.model_validate(resp.json())
374
375    def list(
376        self,
377        challenge_id: str = "",
378        status: str = "",
379        q: str = "",
380        offset: int = 0,
381        limit: int = 50,
382    ) -> PagedList[InstanceInfo]:
383        """List all running instances."""
384        params: dict[str, Any] = {"offset": offset, "limit": limit}
385        if challenge_id:
386            params["challenge_id"] = challenge_id
387        if status:
388            params["status"] = status
389        if q:
390            params["q"] = q
391        resp = self._http.request("GET", "/instances", params=params)
392        _raise_for_status(resp)
393        return _extract_items(resp.json(), InstanceInfo)
394
395    def attachments(self, instance_id: str) -> AttachmentList:
396        """List per-instance (post-launch) attachments.
397
398        For challenges with ``attachments/<name>.tpl`` Jinja templates
399        the names + sizes here are the *rendered* per-team-unique
400        siblings; for ones with only static attachments the list is
401        the same as :meth:`ChallengesResource.attachments`.
402        """
403        resp = self._http.request("GET", f"/instances/{instance_id}/attachments")
404        _raise_for_status(resp)
405        return AttachmentList.model_validate(resp.json())
406
407    def download_attachment(self, instance_id: str, filename: str) -> bytes:
408        """Download one per-instance attachment as raw bytes.
409
410        For challenges with per-team Jinja templates this returns the
411        team-specific render; for static attachments it's the same
412        bytes as :meth:`ChallengesResource.download_attachment` would yield.
413        """
414        # A 302 to a short-lived presigned object-store URL (#3939).
415        resp = self._http.request(
416            "GET",
417            f"/instances/{instance_id}/attachments/{attachment_url_path(filename)}",
418            follow_redirects=True,
419        )
420        _raise_for_status(resp)
421        return resp.content
422
423    def vpn_config(self, instance_id: str) -> bytes:
424        """Download the per-instance VPN client config as raw bytes.
425
426        Only meaningful for challenges that declare
427        ``network_topology: engagement`` in metadata.yaml. The body is
428        the rendered profile the player or automated agent hands to
429        their client to land on the challenge's DMZ docker network —
430        an OpenVPN ``.ovpn`` or a WireGuard ``.conf``, per the
431        challenge's ``vpn_backend`` (read it off
432        ``InstanceInfo.vpn_backend`` to know which client to run). The
433        platform serves a 404 for simple-mode instances.
434
435        ⚠️ **On WireGuard the filename matters**, and this returns only
436        bytes. ``wg-quick`` takes the interface name from the file's
437        basename and the kernel caps that at 15 characters, so writing
438        these bytes to ``<instance-id>.conf`` produces a file
439        ``wg-quick`` refuses. The ``Content-Disposition`` on the HTTP
440        response carries a name that works; a caller saving to disk
441        should use it, or pick its own short one.
442
443        Raises a ``CTFyError`` (404) when the challenge isn't an
444        engagement-mode one, when the instance hasn't yet reached the
445        running state, or when the node's VPN container hasn't finished
446        its key bootstrap.
447        """
448        resp = self._http.request("GET", f"/instances/{instance_id}/vpn-config")
449        _raise_for_status(resp)
450        return resp.content
451
452    def tunnel(self, instance_id: str, *, mode: str = "auto", timeout: float = 30.0) -> Any:
453        """Open a userspace tunnel to this instance; yields a SOCKS5 address.
454
455        The piece that lets an **unprivileged** caller — an agent, a
456        script, a CI job — reach an engagement challenge::
457
458            with client.instances.tunnel(iid) as tun:
459                requests.get(f"http://{host}/", proxies=tun.proxies)
460
461        ⚠️ Before this, fetching :meth:`vpn_config` was the end of the
462        road for anyone who could not run ``wg-quick`` as root. That is
463        every agent: the MCP surface has no tunnel tool, so an agent
464        received a ``config_url`` it had no way to act on, and an
465        engagement challenge was simply unplayable for it.
466
467        Terminating WireGuard in userspace removes the privilege
468        requirement entirely — no ``/dev/net/tun``, no ``CAP_NET_ADMIN``,
469        no root. See :mod:`ctfy.sdk.tunnel` for which backends are
470        accepted and why none is vendored.
471
472        ``mode`` picks the transport:
473
474        ``interface``
475            A real WireGuard device via ``wg-quick``. ICMP, UDP and raw
476            sockets all work, so `ping` and `nmap` behave — needs
477            ``CAP_NET_ADMIN`` and mutates host routes and resolver.
478        ``socks``
479            The userspace tunnel, reachable as ``tun.proxies``. No
480            privileges and no host state touched; ⚠️ **TCP only**.
481        ``auto`` (default)
482            The first of those that this process can use.
483
484        ⚠️ Ask explicitly when it matters. A challenge that needs ICMP
485        will look *broken* under ``socks`` rather than unreachable, and a
486        laptop does not want its routing table rewritten by a test.
487        """
488        from ctfy.sdk.tunnel import open_tunnel, validate_mode
489
490        # Before the request, so a typo is not reported as a missing
491        # instance.
492        validate_mode(mode)
493        return open_tunnel(self.vpn_config(instance_id).decode(), mode=mode, timeout=timeout)
494
495    def openvpn_config(self, instance_id: str) -> bytes:
496        """Deprecated alias for :meth:`vpn_config`.
497
498        Kept because agents and scripts written against the
499        engagement-mode API call it by this name. It returns whatever
500        the challenge actually runs — which for a WireGuard challenge
501        is a ``.conf``, since what the instance ships is not something
502        the method name gets a vote on.
503        """
504        return self.vpn_config(instance_id)
505
506    def traffic(
507        self,
508        instance_id: str,
509        *,
510        competition_id: str = "",
511        cursor: str = "",
512        limit: int = 0,
513    ) -> dict[str, Any]:
514        """Traffic captured since *cursor*.
515
516        Answers ``{flows, cursor, truncated, capture}``.
517
518        The capture lives on the worker node; the platform proxies the
519        fetch. An absent *cursor* means the whole capture, bounded by
520        the server's page limits — so a caller that wants everything
521        polls until ``truncated`` is false, carrying each reply's
522        ``cursor`` into the next call.
523
524        ⚠️ **This has been answering ``{}`` for every caller.** The
525        route used to return a bare JSON *list* while this method was
526        annotated ``dict`` and coerced anything else to an empty one —
527        so an SDK user got "no capture" from a box with a full one, with
528        nothing raising. The envelope is what makes the annotation true.
529
530        Still returns an empty dict on a genuinely absent capture
531        (sidecar disabled, node offline, instance never ran) so callers
532        can persist conditionally without try/except.
533        """
534        params: dict[str, Any] = {"competition_id": competition_id} if competition_id else {}
535        if cursor:
536            params["cursor"] = cursor
537        # ⚠️ A caller with a *context window* wants far fewer than the
538        # server default of 500 full flows. Omitted means the default,
539        # so an existing caller is unchanged.
540        if limit > 0:
541            params["limit"] = limit
542        resp = self._http.request("GET", f"/instances/{instance_id}/traffic", params=params)
543        _raise_for_status(resp)
544        data = resp.json()
545        return data if isinstance(data, dict) else {}
class InstanceStopFailed(builtins.RuntimeError):
44class InstanceStopFailed(RuntimeError):
45    """The platform tried the stop and the instance's node refused it (#3736).
46
47    The box is still running and still listed; ``reason`` is the row's
48    ``error_code`` (``node_stop_failed``). Stopping it again asks again.
49    """
50
51    def __init__(self, instance_id: str, reason: str) -> None:
52        super().__init__(f"instance {instance_id} was not stopped: {reason}")
53        self.instance_id = instance_id
54        self.reason = reason

The platform tried the stop and the instance's node refused it (#3736).

The box is still running and still listed; reason is the row's error_code (node_stop_failed). Stopping it again asks again.

InstanceStopFailed(instance_id: str, reason: str)
51    def __init__(self, instance_id: str, reason: str) -> None:
52        super().__init__(f"instance {instance_id} was not stopped: {reason}")
53        self.instance_id = instance_id
54        self.reason = reason
instance_id
reason
class InstancesResource:
 57class InstancesResource:
 58    """Start / inspect / tear down challenge instances."""
 59
 60    def __init__(self, http: BaseHttpClient) -> None:
 61        self._http = http
 62
 63    def start(
 64        self,
 65        challenge_id: str,
 66        ttl: int | None = None,
 67        *,
 68        competition_id: str = "",
 69        timeout: int = 300,
 70        poll_interval: float = 2.0,
 71    ) -> InstanceReadyResult:
 72        """Start instance and wait until ready.
 73
 74        Returns InstanceReadyResult with attack surface + sandbox network info.
 75        The .surface attribute provides backward compatibility.
 76
 77        **A shared challenge** (``InstanceInfo.shared`` / ``ChallengeInfo.shared``)
 78        is one environment for several teams: this call returns the box your
 79        group already shares (starting it if none is running), the flag is
 80        the same value for everyone on it, and you can neither ``stop``,
 81        ``renew`` nor ``reset`` it -- those answer 403, the organisers reset
 82        it. If it looks broken, :meth:`report_issue`. Your solves, wrong
 83        attempts and unlocked questions are still your own team's.
 84
 85        Args:
 86            challenge_id: Challenge ID (e.g., "XBOW-047").
 87            ttl: Per-instance TTL override in seconds. ``None`` (the
 88                default) delegates to the platform's
 89                ``default_instance_ttl_s`` setting (admin-tunable,
 90                currently 24h). Explicit values are clamped to the
 91                platform's ``max_instance_ttl_s``.
 92            competition_id: Which competition to spin the instance up
 93                under. Required when the calling user is on more than
 94                one team — agents tied to a single comp can leave it
 95                empty and the server picks the unambiguous team.
 96            timeout: Max seconds to wait for ready.
 97            poll_interval: Seconds between status polls.
 98
 99        ⚠️ **There is no ``proxy_output_dir`` here, and its absence is
100        the feature.** It used to be a field on the player's own start
101        request, passed through the platform untouched and landing on
102        ``output_path.mkdir(parents=True, exist_ok=True)`` followed by
103        ``output_path.chmod(0o777)`` on a worker node, as root. Where a
104        capture goes is the *node's* decision — it reads
105        ``proxy_output_host_root`` from its own config, which the
106        rendered compose already sets — so a caller naming a host path
107        on somebody else's worker was never answering a question that
108        was theirs to answer.
109        """
110        start = self.begin_start(challenge_id, ttl, competition_id=competition_id)
111        return _poll_instance_ready(
112            self._http._client, start.id, timeout=timeout, poll_interval=poll_interval
113        )
114
115    def begin_start(
116        self, challenge_id: str, ttl: int | None = None, *, competition_id: str = ""
117    ) -> StartResponse:
118        """``POST /instances`` alone: the platform's ``202``, without the wait.
119
120        :meth:`start` is this plus the readiness wait. The remote MCP's
121        ``start_instance`` uses the two halves apart (#3649), so its wait
122        sleeps on the event loop instead of on a thread; the
123        :class:`StartResponse` carries ``start_wait`` for a start in line.
124        """
125        body: dict[str, Any] = {
126            "challenge_id": challenge_id,
127            "competition_id": competition_id,
128        }
129        if ttl is not None:
130            body["ttl"] = ttl
131        resp = self._http.request("POST", "/instances", json=body)
132        _raise_for_status(resp)
133        return StartResponse.model_validate(resp.json())
134
135    def status_read(self, instance_id: str) -> httpx.Response:
136        """One raw ``GET /instances/{id}/status``, as the readiness wait reads it.
137
138        Unretried and unraised, exactly the read :meth:`start`'s wait makes:
139        :class:`~ctfy.sdk._helpers.ReadyWait` decides what a 404, a 5xx or a
140        transport error means. :meth:`status` is the typed read.
141        """
142        return self._http._client.get(f"/instances/{instance_id}/status")
143
144    def get(self, instance_id: str) -> InstanceInfo:
145        """Get the full ``InstanceInfo`` for one running instance.
146
147        Carries the per-instance ``questions`` list with each question's
148        ``unlocked`` / ``answered_correctly`` / ``attempts_remaining``
149        state — the surface multi-milestone solvers iterate on. The
150        prompt is empty for still-locked questions so the route hint
151        doesn't leak before the prerequisite is solved.
152
153        See :meth:`status` for the lighter status-only payload (no
154        questions, no spec metadata) used by polling loops.
155        """
156        resp = self._http.request("GET", f"/instances/{instance_id}")
157        _raise_for_status(resp)
158        return InstanceInfo.model_validate(resp.json())
159
160    def iter_pending_questions(self, instance_id: str) -> Iterator[InstanceQuestionInfo]:
161        """Yield each currently-pending question on a running instance.
162
163        "Pending" = unlocked (the ``requires:`` chain is satisfied)
164        and not yet correctly answered by the calling team. After
165        every batch is exhausted, re-fetches ``InstanceInfo`` so
166        newly-unlocked questions (whose prerequisite was just solved
167        by the consumer) flow through on the next iteration.
168
169        Terminates on either:
170
171        * no pending questions left — the natural "challenge fully
172          solved" exit;
173        * **no progress** — the same set of pending question ids
174          comes back twice in a row, meaning the consumer's solver
175          isn't capturing anything. Stops silently rather than
176          infinite-looping; inspect the caller's last :meth:`get` to
177          see what's still stuck.
178
179        This is the ergonomic helper for the common multi-milestone
180        loop::
181
182            for q in client.instances.iter_pending_questions(instance_id):
183                ans = my_solver(q.prompt)
184                client.submissions.submit(instance_id, ans, question_id=q.id)
185
186        Args:
187            instance_id: The instance to walk.
188        """
189        previous_pending_ids: frozenset[str] | None = None
190        while True:
191            info = self.get(instance_id)
192            pending = [q for q in info.questions if q.unlocked and not q.answered_correctly]
193            if not pending:
194                return
195
196            pending_ids = frozenset(q.id for q in pending)
197            if pending_ids == previous_pending_ids:
198                # Solver made no progress against the last batch — stop
199                # rather than spin. The consumer can re-call this method
200                # later (after fixing their solver) to pick up where
201                # they left off.
202                return
203            previous_pending_ids = pending_ids
204
205            yield from pending
206
207    def status(self, instance_id: str) -> InstanceStatusResponse:
208        """Get instance status and attack surface."""
209        resp = self._http.request("GET", f"/instances/{instance_id}/status")
210        _raise_for_status(resp)
211        return InstanceStatusResponse.model_validate(resp.json())
212
213    def start_history(self, instance_id: str) -> StartHistory:
214        """The challenge's past starts on this start's footing (#3669): the
215        newest measured durations, ascending, and their p50 / p90 -- empty
216        below the minimum sample count, never a guess."""
217        resp = self._http.request("GET", f"/instances/{instance_id}/start-history")
218        _raise_for_status(resp)
219        return StartHistory.model_validate(resp.json())
220
221    def stop(
222        self,
223        instance_id: str,
224        *,
225        wait: bool = False,
226        timeout: float = 180.0,
227        poll_interval: float = 1.0,
228    ) -> StopResponse:
229        """Tear down ``instance_id``. Idempotent: a 404 from the server
230        means the instance is already gone (auto-stopped after solve,
231        TTL expiry, admin teardown) and is treated as success.
232
233        ⚠️ **The platform answers once the stop is handed off** (#3736):
234        ``status="stopping"``, and the box goes once its node confirms. A
235        ``stopping`` box still holds its team's slot, so a caller that
236        starts another next -- under a per-team cap of one, say -- passes
237        ``wait=True``: this then polls the instance until it is gone
238        (``status="stopped"``), raises :class:`InstanceStopFailed` if the
239        node refused the stop (the box is still running and listed, with
240        ``error_code="node_stop_failed"``), and ``TimeoutError`` after
241        *timeout* seconds still stopping. A second call on a stopping box
242        starts nothing and answers ``stopping`` again.
243        """
244        resp = self._http.request("DELETE", f"/instances/{instance_id}")
245        if resp.status_code == 404:
246            return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
247        _raise_for_status(resp)
248        answer = StopResponse.model_validate(resp.json())
249        if wait and answer.status == InstanceStatus.STOPPING:
250            return self.wait_stopped(instance_id, timeout=timeout, poll_interval=poll_interval)
251        return answer
252
253    def wait_stopped(
254        self, instance_id: str, *, timeout: float = 180.0, poll_interval: float = 1.0
255    ) -> StopResponse:
256        """Poll ``instance_id`` until its stop is done (#3736); see :meth:`stop`.
257
258        A transport error or a 5xx is no answer and is asked again; a ``404``
259        is the confirmation (the row is gone -- or, when its node was not
260        answering, out of the team's list and torn down when it returns).
261        """
262        deadline = time.monotonic() + timeout
263        while True:
264            try:
265                resp = self._http.request("GET", f"/instances/{instance_id}")
266            except httpx.TransportError:
267                resp = None
268            if resp is not None and resp.status_code == 404:
269                return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
270            if resp is not None and resp.status_code < 500:
271                _raise_for_status(resp)
272                info = InstanceInfo.model_validate(resp.json())
273                if info.status != InstanceStatus.STOPPING:
274                    raise InstanceStopFailed(instance_id, info.error_code or info.status.value)
275            if time.monotonic() >= deadline:
276                raise TimeoutError(f"instance {instance_id} still stopping after {timeout:.0f}s")
277            time.sleep(poll_interval)
278
279    def reset(self, instance_id: str, ttl: int | None = None) -> StartResponse:
280        """Swap ``instance_id`` for a freshly-built one, atomically.
281
282        Returns the **new** instance id — the old one is gone. Prefer
283        this over ``stop`` + ``start``: the team's slot is never
284        released between the two, so a full platform can still reset,
285        and every refusal (unknown challenge, no node with room) is
286        decided before the running environment is torn down.
287
288        Minted answers are new; solves, the ``requires:`` reveal chain
289        and the per-question wrong-attempt counters are keyed
290        ``(team, challenge)`` and carry over untouched.
291        """
292        params: dict[str, Any] = {}
293        if ttl is not None:
294            params["ttl"] = ttl
295        resp = self._http.request("POST", f"/instances/{instance_id}/reset", params=params)
296        _raise_for_status(resp)
297        return StartResponse.model_validate(resp.json())
298
299    def renew(self, instance_id: str, ttl: int | None = None) -> RenewResponse:
300        """Extend the TTL of a running instance.
301
302        ``ttl`` is an **increment**, not a new lifetime: it is added to
303        whatever time the box has left, and the resulting deadline is
304        capped at ``max_instance_ttl_s`` seconds from now. So a renewal
305        can never move a deadline backwards, and one on a box already
306        at the ceiling is a no-op rather than a refusal.
307
308        ``ttl=None`` (the default) delegates to the platform's
309        ``default_instance_ttl_s`` setting.
310
311        Read the granted deadline off ``RenewResponse.expires_at``
312        rather than computing it — see
313        :func:`ctfy.core.instance_ttl.plan_renewal`. ``0.0`` there means
314        the instance has no deadline at all (an AWD match gamebox), so
315        there was nothing to extend.
316        """
317        params: dict[str, Any] = {}
318        if ttl is not None:
319            params["ttl"] = ttl
320        resp = self._http.request("POST", f"/instances/{instance_id}/renew", params=params)
321        _raise_for_status(resp)
322        return RenewResponse.model_validate(resp.json())
323
324    def report_issue(self, instance_id: str) -> SharedEnvReportResult:
325        """Tell the organisers that a *shared* environment looks broken.
326
327        The only action a player has on a shared box: it changes nothing,
328        the organisers decide whether to reset. Limited to one report per
329        team per challenge every few minutes (429 ``shared_report_rate_limited``
330        beyond that); 409 on a box that is yours alone -- reset that one
331        yourself.
332        """
333        resp = self._http.request("POST", f"/instances/{instance_id}/report-issue")
334        _raise_for_status(resp)
335        return SharedEnvReportResult.model_validate(resp.json())
336
337    def shell_session(self, instance_id: str, *, shell: str = "bash") -> PlayerShellTicket:
338        """Mint a single-use ticket for a shell into your own AWD+ box.
339
340        This wraps the *mint* only. Opening the WebSocket the ticket
341        names is the caller's job, because the SDK is a sync httpx
342        client and a shell is a long-lived bidirectional stream — the
343        same reason ``events()`` is not a plain request. ``ctfy patch
344        shell`` is the reference consumer.
345
346        No container argument: the platform resolves the target from the
347        challenge's ``patch.live.service``, and answers
348        ``shell_unsupported`` for a challenge that declares none.
349        """
350        resp = self._http.request(
351            "POST",
352            f"/instances/{instance_id}/shell/sessions",
353            json={"shell": shell},
354        )
355        _raise_for_status(resp)
356        return PlayerShellTicket.model_validate(resp.json())
357
358    def ssh_credential(self, instance_id: str) -> SshCredential:
359        """Mint a short-lived SSH certificate for your own AWD+ box.
360
361        The other half of ``shell_session``: same authorisation, same
362        target, a different protocol in front of it. A defender who
363        would rather use ``ssh`` (and every agent that already drives
364        one) gets a throwaway keypair plus a certificate, and presents
365        them to the bastion — which trades the authenticated subject
366        back for the very ticket ``shell_session`` returns.
367
368        The credential expires in minutes: it only has to cover
369        *connecting*, and the session it opens outlives it. Ask again
370        rather than caching one.
371        """
372        resp = self._http.request("POST", f"/instances/{instance_id}/ssh")
373        _raise_for_status(resp)
374        return SshCredential.model_validate(resp.json())
375
376    def list(
377        self,
378        challenge_id: str = "",
379        status: str = "",
380        q: str = "",
381        offset: int = 0,
382        limit: int = 50,
383    ) -> PagedList[InstanceInfo]:
384        """List all running instances."""
385        params: dict[str, Any] = {"offset": offset, "limit": limit}
386        if challenge_id:
387            params["challenge_id"] = challenge_id
388        if status:
389            params["status"] = status
390        if q:
391            params["q"] = q
392        resp = self._http.request("GET", "/instances", params=params)
393        _raise_for_status(resp)
394        return _extract_items(resp.json(), InstanceInfo)
395
396    def attachments(self, instance_id: str) -> AttachmentList:
397        """List per-instance (post-launch) attachments.
398
399        For challenges with ``attachments/<name>.tpl`` Jinja templates
400        the names + sizes here are the *rendered* per-team-unique
401        siblings; for ones with only static attachments the list is
402        the same as :meth:`ChallengesResource.attachments`.
403        """
404        resp = self._http.request("GET", f"/instances/{instance_id}/attachments")
405        _raise_for_status(resp)
406        return AttachmentList.model_validate(resp.json())
407
408    def download_attachment(self, instance_id: str, filename: str) -> bytes:
409        """Download one per-instance attachment as raw bytes.
410
411        For challenges with per-team Jinja templates this returns the
412        team-specific render; for static attachments it's the same
413        bytes as :meth:`ChallengesResource.download_attachment` would yield.
414        """
415        # A 302 to a short-lived presigned object-store URL (#3939).
416        resp = self._http.request(
417            "GET",
418            f"/instances/{instance_id}/attachments/{attachment_url_path(filename)}",
419            follow_redirects=True,
420        )
421        _raise_for_status(resp)
422        return resp.content
423
424    def vpn_config(self, instance_id: str) -> bytes:
425        """Download the per-instance VPN client config as raw bytes.
426
427        Only meaningful for challenges that declare
428        ``network_topology: engagement`` in metadata.yaml. The body is
429        the rendered profile the player or automated agent hands to
430        their client to land on the challenge's DMZ docker network —
431        an OpenVPN ``.ovpn`` or a WireGuard ``.conf``, per the
432        challenge's ``vpn_backend`` (read it off
433        ``InstanceInfo.vpn_backend`` to know which client to run). The
434        platform serves a 404 for simple-mode instances.
435
436        ⚠️ **On WireGuard the filename matters**, and this returns only
437        bytes. ``wg-quick`` takes the interface name from the file's
438        basename and the kernel caps that at 15 characters, so writing
439        these bytes to ``<instance-id>.conf`` produces a file
440        ``wg-quick`` refuses. The ``Content-Disposition`` on the HTTP
441        response carries a name that works; a caller saving to disk
442        should use it, or pick its own short one.
443
444        Raises a ``CTFyError`` (404) when the challenge isn't an
445        engagement-mode one, when the instance hasn't yet reached the
446        running state, or when the node's VPN container hasn't finished
447        its key bootstrap.
448        """
449        resp = self._http.request("GET", f"/instances/{instance_id}/vpn-config")
450        _raise_for_status(resp)
451        return resp.content
452
453    def tunnel(self, instance_id: str, *, mode: str = "auto", timeout: float = 30.0) -> Any:
454        """Open a userspace tunnel to this instance; yields a SOCKS5 address.
455
456        The piece that lets an **unprivileged** caller — an agent, a
457        script, a CI job — reach an engagement challenge::
458
459            with client.instances.tunnel(iid) as tun:
460                requests.get(f"http://{host}/", proxies=tun.proxies)
461
462        ⚠️ Before this, fetching :meth:`vpn_config` was the end of the
463        road for anyone who could not run ``wg-quick`` as root. That is
464        every agent: the MCP surface has no tunnel tool, so an agent
465        received a ``config_url`` it had no way to act on, and an
466        engagement challenge was simply unplayable for it.
467
468        Terminating WireGuard in userspace removes the privilege
469        requirement entirely — no ``/dev/net/tun``, no ``CAP_NET_ADMIN``,
470        no root. See :mod:`ctfy.sdk.tunnel` for which backends are
471        accepted and why none is vendored.
472
473        ``mode`` picks the transport:
474
475        ``interface``
476            A real WireGuard device via ``wg-quick``. ICMP, UDP and raw
477            sockets all work, so `ping` and `nmap` behave — needs
478            ``CAP_NET_ADMIN`` and mutates host routes and resolver.
479        ``socks``
480            The userspace tunnel, reachable as ``tun.proxies``. No
481            privileges and no host state touched; ⚠️ **TCP only**.
482        ``auto`` (default)
483            The first of those that this process can use.
484
485        ⚠️ Ask explicitly when it matters. A challenge that needs ICMP
486        will look *broken* under ``socks`` rather than unreachable, and a
487        laptop does not want its routing table rewritten by a test.
488        """
489        from ctfy.sdk.tunnel import open_tunnel, validate_mode
490
491        # Before the request, so a typo is not reported as a missing
492        # instance.
493        validate_mode(mode)
494        return open_tunnel(self.vpn_config(instance_id).decode(), mode=mode, timeout=timeout)
495
496    def openvpn_config(self, instance_id: str) -> bytes:
497        """Deprecated alias for :meth:`vpn_config`.
498
499        Kept because agents and scripts written against the
500        engagement-mode API call it by this name. It returns whatever
501        the challenge actually runs — which for a WireGuard challenge
502        is a ``.conf``, since what the instance ships is not something
503        the method name gets a vote on.
504        """
505        return self.vpn_config(instance_id)
506
507    def traffic(
508        self,
509        instance_id: str,
510        *,
511        competition_id: str = "",
512        cursor: str = "",
513        limit: int = 0,
514    ) -> dict[str, Any]:
515        """Traffic captured since *cursor*.
516
517        Answers ``{flows, cursor, truncated, capture}``.
518
519        The capture lives on the worker node; the platform proxies the
520        fetch. An absent *cursor* means the whole capture, bounded by
521        the server's page limits — so a caller that wants everything
522        polls until ``truncated`` is false, carrying each reply's
523        ``cursor`` into the next call.
524
525        ⚠️ **This has been answering ``{}`` for every caller.** The
526        route used to return a bare JSON *list* while this method was
527        annotated ``dict`` and coerced anything else to an empty one —
528        so an SDK user got "no capture" from a box with a full one, with
529        nothing raising. The envelope is what makes the annotation true.
530
531        Still returns an empty dict on a genuinely absent capture
532        (sidecar disabled, node offline, instance never ran) so callers
533        can persist conditionally without try/except.
534        """
535        params: dict[str, Any] = {"competition_id": competition_id} if competition_id else {}
536        if cursor:
537            params["cursor"] = cursor
538        # ⚠️ A caller with a *context window* wants far fewer than the
539        # server default of 500 full flows. Omitted means the default,
540        # so an existing caller is unchanged.
541        if limit > 0:
542            params["limit"] = limit
543        resp = self._http.request("GET", f"/instances/{instance_id}/traffic", params=params)
544        _raise_for_status(resp)
545        data = resp.json()
546        return data if isinstance(data, dict) else {}

Start / inspect / tear down challenge instances.

InstancesResource(http: ctfy.sdk.base.BaseHttpClient)
60    def __init__(self, http: BaseHttpClient) -> None:
61        self._http = http
def start( self, challenge_id: str, ttl: int | None = None, *, competition_id: str = '', timeout: int = 300, poll_interval: float = 2.0) -> ctfy.sdk._helpers.InstanceReadyResult:
 63    def start(
 64        self,
 65        challenge_id: str,
 66        ttl: int | None = None,
 67        *,
 68        competition_id: str = "",
 69        timeout: int = 300,
 70        poll_interval: float = 2.0,
 71    ) -> InstanceReadyResult:
 72        """Start instance and wait until ready.
 73
 74        Returns InstanceReadyResult with attack surface + sandbox network info.
 75        The .surface attribute provides backward compatibility.
 76
 77        **A shared challenge** (``InstanceInfo.shared`` / ``ChallengeInfo.shared``)
 78        is one environment for several teams: this call returns the box your
 79        group already shares (starting it if none is running), the flag is
 80        the same value for everyone on it, and you can neither ``stop``,
 81        ``renew`` nor ``reset`` it -- those answer 403, the organisers reset
 82        it. If it looks broken, :meth:`report_issue`. Your solves, wrong
 83        attempts and unlocked questions are still your own team's.
 84
 85        Args:
 86            challenge_id: Challenge ID (e.g., "XBOW-047").
 87            ttl: Per-instance TTL override in seconds. ``None`` (the
 88                default) delegates to the platform's
 89                ``default_instance_ttl_s`` setting (admin-tunable,
 90                currently 24h). Explicit values are clamped to the
 91                platform's ``max_instance_ttl_s``.
 92            competition_id: Which competition to spin the instance up
 93                under. Required when the calling user is on more than
 94                one team — agents tied to a single comp can leave it
 95                empty and the server picks the unambiguous team.
 96            timeout: Max seconds to wait for ready.
 97            poll_interval: Seconds between status polls.
 98
 99        ⚠️ **There is no ``proxy_output_dir`` here, and its absence is
100        the feature.** It used to be a field on the player's own start
101        request, passed through the platform untouched and landing on
102        ``output_path.mkdir(parents=True, exist_ok=True)`` followed by
103        ``output_path.chmod(0o777)`` on a worker node, as root. Where a
104        capture goes is the *node's* decision — it reads
105        ``proxy_output_host_root`` from its own config, which the
106        rendered compose already sets — so a caller naming a host path
107        on somebody else's worker was never answering a question that
108        was theirs to answer.
109        """
110        start = self.begin_start(challenge_id, ttl, competition_id=competition_id)
111        return _poll_instance_ready(
112            self._http._client, start.id, timeout=timeout, poll_interval=poll_interval
113        )

Start instance and wait until ready.

Returns InstanceReadyResult with attack surface + sandbox network info. The .surface attribute provides backward compatibility.

A shared challenge (InstanceInfo.shared / ChallengeInfo.shared) is one environment for several teams: this call returns the box your group already shares (starting it if none is running), the flag is the same value for everyone on it, and you can neither stop, renew nor reset it -- those answer 403, the organisers reset it. If it looks broken, report_issue(). Your solves, wrong attempts and unlocked questions are still your own team's.

Arguments:
  • challenge_id: Challenge ID (e.g., "XBOW-047").
  • ttl: Per-instance TTL override in seconds. None (the default) delegates to the platform's default_instance_ttl_s setting (admin-tunable, currently 24h). Explicit values are clamped to the platform's max_instance_ttl_s.
  • competition_id: Which competition to spin the instance up under. Required when the calling user is on more than one team — agents tied to a single comp can leave it empty and the server picks the unambiguous team.
  • timeout: Max seconds to wait for ready.
  • poll_interval: Seconds between status polls.

⚠️ There is no proxy_output_dir here, and its absence is the feature. It used to be a field on the player's own start request, passed through the platform untouched and landing on output_path.mkdir(parents=True, exist_ok=True) followed by output_path.chmod(0o777) on a worker node, as root. Where a capture goes is the node's decision — it reads proxy_output_host_root from its own config, which the rendered compose already sets — so a caller naming a host path on somebody else's worker was never answering a question that was theirs to answer.

def begin_start( self, challenge_id: str, ttl: int | None = None, *, competition_id: str = '') -> ctfy.server.models.StartResponse:
115    def begin_start(
116        self, challenge_id: str, ttl: int | None = None, *, competition_id: str = ""
117    ) -> StartResponse:
118        """``POST /instances`` alone: the platform's ``202``, without the wait.
119
120        :meth:`start` is this plus the readiness wait. The remote MCP's
121        ``start_instance`` uses the two halves apart (#3649), so its wait
122        sleeps on the event loop instead of on a thread; the
123        :class:`StartResponse` carries ``start_wait`` for a start in line.
124        """
125        body: dict[str, Any] = {
126            "challenge_id": challenge_id,
127            "competition_id": competition_id,
128        }
129        if ttl is not None:
130            body["ttl"] = ttl
131        resp = self._http.request("POST", "/instances", json=body)
132        _raise_for_status(resp)
133        return StartResponse.model_validate(resp.json())

POST /instances alone: the platform's 202, without the wait.

start() is this plus the readiness wait. The remote MCP's start_instance uses the two halves apart (#3649), so its wait sleeps on the event loop instead of on a thread; the StartResponse carries start_wait for a start in line.

def status_read(self, instance_id: str) -> httpx.Response:
135    def status_read(self, instance_id: str) -> httpx.Response:
136        """One raw ``GET /instances/{id}/status``, as the readiness wait reads it.
137
138        Unretried and unraised, exactly the read :meth:`start`'s wait makes:
139        :class:`~ctfy.sdk._helpers.ReadyWait` decides what a 404, a 5xx or a
140        transport error means. :meth:`status` is the typed read.
141        """
142        return self._http._client.get(f"/instances/{instance_id}/status")

One raw GET /instances/{id}/status, as the readiness wait reads it.

Unretried and unraised, exactly the read start()'s wait makes: ~ctfy.sdk._helpers.ReadyWait decides what a 404, a 5xx or a transport error means. status() is the typed read.

def get(self, instance_id: str) -> ctfy.server.models.InstanceInfo:
144    def get(self, instance_id: str) -> InstanceInfo:
145        """Get the full ``InstanceInfo`` for one running instance.
146
147        Carries the per-instance ``questions`` list with each question's
148        ``unlocked`` / ``answered_correctly`` / ``attempts_remaining``
149        state — the surface multi-milestone solvers iterate on. The
150        prompt is empty for still-locked questions so the route hint
151        doesn't leak before the prerequisite is solved.
152
153        See :meth:`status` for the lighter status-only payload (no
154        questions, no spec metadata) used by polling loops.
155        """
156        resp = self._http.request("GET", f"/instances/{instance_id}")
157        _raise_for_status(resp)
158        return InstanceInfo.model_validate(resp.json())

Get the full InstanceInfo for one running instance.

Carries the per-instance questions list with each question's unlocked / answered_correctly / attempts_remaining state — the surface multi-milestone solvers iterate on. The prompt is empty for still-locked questions so the route hint doesn't leak before the prerequisite is solved.

See status() for the lighter status-only payload (no questions, no spec metadata) used by polling loops.

def iter_pending_questions( self, instance_id: str) -> Iterator[ctfy.server.models.InstanceQuestionInfo]:
160    def iter_pending_questions(self, instance_id: str) -> Iterator[InstanceQuestionInfo]:
161        """Yield each currently-pending question on a running instance.
162
163        "Pending" = unlocked (the ``requires:`` chain is satisfied)
164        and not yet correctly answered by the calling team. After
165        every batch is exhausted, re-fetches ``InstanceInfo`` so
166        newly-unlocked questions (whose prerequisite was just solved
167        by the consumer) flow through on the next iteration.
168
169        Terminates on either:
170
171        * no pending questions left — the natural "challenge fully
172          solved" exit;
173        * **no progress** — the same set of pending question ids
174          comes back twice in a row, meaning the consumer's solver
175          isn't capturing anything. Stops silently rather than
176          infinite-looping; inspect the caller's last :meth:`get` to
177          see what's still stuck.
178
179        This is the ergonomic helper for the common multi-milestone
180        loop::
181
182            for q in client.instances.iter_pending_questions(instance_id):
183                ans = my_solver(q.prompt)
184                client.submissions.submit(instance_id, ans, question_id=q.id)
185
186        Args:
187            instance_id: The instance to walk.
188        """
189        previous_pending_ids: frozenset[str] | None = None
190        while True:
191            info = self.get(instance_id)
192            pending = [q for q in info.questions if q.unlocked and not q.answered_correctly]
193            if not pending:
194                return
195
196            pending_ids = frozenset(q.id for q in pending)
197            if pending_ids == previous_pending_ids:
198                # Solver made no progress against the last batch — stop
199                # rather than spin. The consumer can re-call this method
200                # later (after fixing their solver) to pick up where
201                # they left off.
202                return
203            previous_pending_ids = pending_ids
204
205            yield from pending

Yield each currently-pending question on a running instance.

"Pending" = unlocked (the requires: chain is satisfied) and not yet correctly answered by the calling team. After every batch is exhausted, re-fetches InstanceInfo so newly-unlocked questions (whose prerequisite was just solved by the consumer) flow through on the next iteration.

Terminates on either:

  • no pending questions left — the natural "challenge fully solved" exit;
  • no progress — the same set of pending question ids comes back twice in a row, meaning the consumer's solver isn't capturing anything. Stops silently rather than infinite-looping; inspect the caller's last get() to see what's still stuck.

This is the ergonomic helper for the common multi-milestone loop::

for q in client.instances.iter_pending_questions(instance_id):
    ans = my_solver(q.prompt)
    client.submissions.submit(instance_id, ans, question_id=q.id)
Arguments:
  • instance_id: The instance to walk.
def status( self, instance_id: str) -> ctfy.server.models.InstanceStatusResponse:
207    def status(self, instance_id: str) -> InstanceStatusResponse:
208        """Get instance status and attack surface."""
209        resp = self._http.request("GET", f"/instances/{instance_id}/status")
210        _raise_for_status(resp)
211        return InstanceStatusResponse.model_validate(resp.json())

Get instance status and attack surface.

def start_history(self, instance_id: str) -> ctfy.server.models.StartHistory:
213    def start_history(self, instance_id: str) -> StartHistory:
214        """The challenge's past starts on this start's footing (#3669): the
215        newest measured durations, ascending, and their p50 / p90 -- empty
216        below the minimum sample count, never a guess."""
217        resp = self._http.request("GET", f"/instances/{instance_id}/start-history")
218        _raise_for_status(resp)
219        return StartHistory.model_validate(resp.json())

The challenge's past starts on this start's footing (#3669): the newest measured durations, ascending, and their p50 / p90 -- empty below the minimum sample count, never a guess.

def stop( self, instance_id: str, *, wait: bool = False, timeout: float = 180.0, poll_interval: float = 1.0) -> ctfy.server.models.StopResponse:
221    def stop(
222        self,
223        instance_id: str,
224        *,
225        wait: bool = False,
226        timeout: float = 180.0,
227        poll_interval: float = 1.0,
228    ) -> StopResponse:
229        """Tear down ``instance_id``. Idempotent: a 404 from the server
230        means the instance is already gone (auto-stopped after solve,
231        TTL expiry, admin teardown) and is treated as success.
232
233        ⚠️ **The platform answers once the stop is handed off** (#3736):
234        ``status="stopping"``, and the box goes once its node confirms. A
235        ``stopping`` box still holds its team's slot, so a caller that
236        starts another next -- under a per-team cap of one, say -- passes
237        ``wait=True``: this then polls the instance until it is gone
238        (``status="stopped"``), raises :class:`InstanceStopFailed` if the
239        node refused the stop (the box is still running and listed, with
240        ``error_code="node_stop_failed"``), and ``TimeoutError`` after
241        *timeout* seconds still stopping. A second call on a stopping box
242        starts nothing and answers ``stopping`` again.
243        """
244        resp = self._http.request("DELETE", f"/instances/{instance_id}")
245        if resp.status_code == 404:
246            return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
247        _raise_for_status(resp)
248        answer = StopResponse.model_validate(resp.json())
249        if wait and answer.status == InstanceStatus.STOPPING:
250            return self.wait_stopped(instance_id, timeout=timeout, poll_interval=poll_interval)
251        return answer

Tear down instance_id. Idempotent: a 404 from the server means the instance is already gone (auto-stopped after solve, TTL expiry, admin teardown) and is treated as success.

⚠️ The platform answers once the stop is handed off (#3736): status="stopping", and the box goes once its node confirms. A stopping box still holds its team's slot, so a caller that starts another next -- under a per-team cap of one, say -- passes wait=True: this then polls the instance until it is gone (status="stopped"), raises InstanceStopFailed if the node refused the stop (the box is still running and listed, with error_code="node_stop_failed"), and TimeoutError after timeout seconds still stopping. A second call on a stopping box starts nothing and answers stopping again.

def wait_stopped( self, instance_id: str, *, timeout: float = 180.0, poll_interval: float = 1.0) -> ctfy.server.models.StopResponse:
253    def wait_stopped(
254        self, instance_id: str, *, timeout: float = 180.0, poll_interval: float = 1.0
255    ) -> StopResponse:
256        """Poll ``instance_id`` until its stop is done (#3736); see :meth:`stop`.
257
258        A transport error or a 5xx is no answer and is asked again; a ``404``
259        is the confirmation (the row is gone -- or, when its node was not
260        answering, out of the team's list and torn down when it returns).
261        """
262        deadline = time.monotonic() + timeout
263        while True:
264            try:
265                resp = self._http.request("GET", f"/instances/{instance_id}")
266            except httpx.TransportError:
267                resp = None
268            if resp is not None and resp.status_code == 404:
269                return StopResponse(id=instance_id, status=InstanceStatus.STOPPED)
270            if resp is not None and resp.status_code < 500:
271                _raise_for_status(resp)
272                info = InstanceInfo.model_validate(resp.json())
273                if info.status != InstanceStatus.STOPPING:
274                    raise InstanceStopFailed(instance_id, info.error_code or info.status.value)
275            if time.monotonic() >= deadline:
276                raise TimeoutError(f"instance {instance_id} still stopping after {timeout:.0f}s")
277            time.sleep(poll_interval)

Poll instance_id until its stop is done (#3736); see stop().

A transport error or a 5xx is no answer and is asked again; a 404 is the confirmation (the row is gone -- or, when its node was not answering, out of the team's list and torn down when it returns).

def reset( self, instance_id: str, ttl: int | None = None) -> ctfy.server.models.StartResponse:
279    def reset(self, instance_id: str, ttl: int | None = None) -> StartResponse:
280        """Swap ``instance_id`` for a freshly-built one, atomically.
281
282        Returns the **new** instance id — the old one is gone. Prefer
283        this over ``stop`` + ``start``: the team's slot is never
284        released between the two, so a full platform can still reset,
285        and every refusal (unknown challenge, no node with room) is
286        decided before the running environment is torn down.
287
288        Minted answers are new; solves, the ``requires:`` reveal chain
289        and the per-question wrong-attempt counters are keyed
290        ``(team, challenge)`` and carry over untouched.
291        """
292        params: dict[str, Any] = {}
293        if ttl is not None:
294            params["ttl"] = ttl
295        resp = self._http.request("POST", f"/instances/{instance_id}/reset", params=params)
296        _raise_for_status(resp)
297        return StartResponse.model_validate(resp.json())

Swap instance_id for a freshly-built one, atomically.

Returns the new instance id — the old one is gone. Prefer this over stop + start: the team's slot is never released between the two, so a full platform can still reset, and every refusal (unknown challenge, no node with room) is decided before the running environment is torn down.

Minted answers are new; solves, the requires: reveal chain and the per-question wrong-attempt counters are keyed (team, challenge) and carry over untouched.

def renew( self, instance_id: str, ttl: int | None = None) -> ctfy.server.models.RenewResponse:
299    def renew(self, instance_id: str, ttl: int | None = None) -> RenewResponse:
300        """Extend the TTL of a running instance.
301
302        ``ttl`` is an **increment**, not a new lifetime: it is added to
303        whatever time the box has left, and the resulting deadline is
304        capped at ``max_instance_ttl_s`` seconds from now. So a renewal
305        can never move a deadline backwards, and one on a box already
306        at the ceiling is a no-op rather than a refusal.
307
308        ``ttl=None`` (the default) delegates to the platform's
309        ``default_instance_ttl_s`` setting.
310
311        Read the granted deadline off ``RenewResponse.expires_at``
312        rather than computing it — see
313        :func:`ctfy.core.instance_ttl.plan_renewal`. ``0.0`` there means
314        the instance has no deadline at all (an AWD match gamebox), so
315        there was nothing to extend.
316        """
317        params: dict[str, Any] = {}
318        if ttl is not None:
319            params["ttl"] = ttl
320        resp = self._http.request("POST", f"/instances/{instance_id}/renew", params=params)
321        _raise_for_status(resp)
322        return RenewResponse.model_validate(resp.json())

Extend the TTL of a running instance.

ttl is an increment, not a new lifetime: it is added to whatever time the box has left, and the resulting deadline is capped at max_instance_ttl_s seconds from now. So a renewal can never move a deadline backwards, and one on a box already at the ceiling is a no-op rather than a refusal.

ttl=None (the default) delegates to the platform's default_instance_ttl_s setting.

Read the granted deadline off RenewResponse.expires_at rather than computing it — see ctfy.core.instance_ttl.plan_renewal(). 0.0 there means the instance has no deadline at all (an AWD match gamebox), so there was nothing to extend.

def report_issue( self, instance_id: str) -> ctfy.server.models.SharedEnvReportResult:
324    def report_issue(self, instance_id: str) -> SharedEnvReportResult:
325        """Tell the organisers that a *shared* environment looks broken.
326
327        The only action a player has on a shared box: it changes nothing,
328        the organisers decide whether to reset. Limited to one report per
329        team per challenge every few minutes (429 ``shared_report_rate_limited``
330        beyond that); 409 on a box that is yours alone -- reset that one
331        yourself.
332        """
333        resp = self._http.request("POST", f"/instances/{instance_id}/report-issue")
334        _raise_for_status(resp)
335        return SharedEnvReportResult.model_validate(resp.json())

Tell the organisers that a shared environment looks broken.

The only action a player has on a shared box: it changes nothing, the organisers decide whether to reset. Limited to one report per team per challenge every few minutes (429 shared_report_rate_limited beyond that); 409 on a box that is yours alone -- reset that one yourself.

def shell_session( self, instance_id: str, *, shell: str = 'bash') -> ctfy.server.models.PlayerShellTicket:
337    def shell_session(self, instance_id: str, *, shell: str = "bash") -> PlayerShellTicket:
338        """Mint a single-use ticket for a shell into your own AWD+ box.
339
340        This wraps the *mint* only. Opening the WebSocket the ticket
341        names is the caller's job, because the SDK is a sync httpx
342        client and a shell is a long-lived bidirectional stream — the
343        same reason ``events()`` is not a plain request. ``ctfy patch
344        shell`` is the reference consumer.
345
346        No container argument: the platform resolves the target from the
347        challenge's ``patch.live.service``, and answers
348        ``shell_unsupported`` for a challenge that declares none.
349        """
350        resp = self._http.request(
351            "POST",
352            f"/instances/{instance_id}/shell/sessions",
353            json={"shell": shell},
354        )
355        _raise_for_status(resp)
356        return PlayerShellTicket.model_validate(resp.json())

Mint a single-use ticket for a shell into your own AWD+ box.

This wraps the mint only. Opening the WebSocket the ticket names is the caller's job, because the SDK is a sync httpx client and a shell is a long-lived bidirectional stream — the same reason events() is not a plain request. ctfy patch shell is the reference consumer.

No container argument: the platform resolves the target from the challenge's patch.live.service, and answers shell_unsupported for a challenge that declares none.

def ssh_credential(self, instance_id: str) -> ctfy.server.models.SshCredential:
358    def ssh_credential(self, instance_id: str) -> SshCredential:
359        """Mint a short-lived SSH certificate for your own AWD+ box.
360
361        The other half of ``shell_session``: same authorisation, same
362        target, a different protocol in front of it. A defender who
363        would rather use ``ssh`` (and every agent that already drives
364        one) gets a throwaway keypair plus a certificate, and presents
365        them to the bastion — which trades the authenticated subject
366        back for the very ticket ``shell_session`` returns.
367
368        The credential expires in minutes: it only has to cover
369        *connecting*, and the session it opens outlives it. Ask again
370        rather than caching one.
371        """
372        resp = self._http.request("POST", f"/instances/{instance_id}/ssh")
373        _raise_for_status(resp)
374        return SshCredential.model_validate(resp.json())

Mint a short-lived SSH certificate for your own AWD+ box.

The other half of shell_session: same authorisation, same target, a different protocol in front of it. A defender who would rather use ssh (and every agent that already drives one) gets a throwaway keypair plus a certificate, and presents them to the bastion — which trades the authenticated subject back for the very ticket shell_session returns.

The credential expires in minutes: it only has to cover connecting, and the session it opens outlives it. Ask again rather than caching one.

def list( self, challenge_id: str = '', status: str = '', q: str = '', offset: int = 0, limit: int = 50) -> ctfy.sdk._helpers.PagedList[ctfy.server.models.InstanceInfo]:
376    def list(
377        self,
378        challenge_id: str = "",
379        status: str = "",
380        q: str = "",
381        offset: int = 0,
382        limit: int = 50,
383    ) -> PagedList[InstanceInfo]:
384        """List all running instances."""
385        params: dict[str, Any] = {"offset": offset, "limit": limit}
386        if challenge_id:
387            params["challenge_id"] = challenge_id
388        if status:
389            params["status"] = status
390        if q:
391            params["q"] = q
392        resp = self._http.request("GET", "/instances", params=params)
393        _raise_for_status(resp)
394        return _extract_items(resp.json(), InstanceInfo)

List all running instances.

def attachments(self, instance_id: str) -> ctfy.server.models.AttachmentList:
396    def attachments(self, instance_id: str) -> AttachmentList:
397        """List per-instance (post-launch) attachments.
398
399        For challenges with ``attachments/<name>.tpl`` Jinja templates
400        the names + sizes here are the *rendered* per-team-unique
401        siblings; for ones with only static attachments the list is
402        the same as :meth:`ChallengesResource.attachments`.
403        """
404        resp = self._http.request("GET", f"/instances/{instance_id}/attachments")
405        _raise_for_status(resp)
406        return AttachmentList.model_validate(resp.json())

List per-instance (post-launch) attachments.

For challenges with attachments/<name>.tpl Jinja templates the names + sizes here are the rendered per-team-unique siblings; for ones with only static attachments the list is the same as ChallengesResource.attachments().

def download_attachment(self, instance_id: str, filename: str) -> bytes:
408    def download_attachment(self, instance_id: str, filename: str) -> bytes:
409        """Download one per-instance attachment as raw bytes.
410
411        For challenges with per-team Jinja templates this returns the
412        team-specific render; for static attachments it's the same
413        bytes as :meth:`ChallengesResource.download_attachment` would yield.
414        """
415        # A 302 to a short-lived presigned object-store URL (#3939).
416        resp = self._http.request(
417            "GET",
418            f"/instances/{instance_id}/attachments/{attachment_url_path(filename)}",
419            follow_redirects=True,
420        )
421        _raise_for_status(resp)
422        return resp.content

Download one per-instance attachment as raw bytes.

For challenges with per-team Jinja templates this returns the team-specific render; for static attachments it's the same bytes as ChallengesResource.download_attachment() would yield.

def vpn_config(self, instance_id: str) -> bytes:
424    def vpn_config(self, instance_id: str) -> bytes:
425        """Download the per-instance VPN client config as raw bytes.
426
427        Only meaningful for challenges that declare
428        ``network_topology: engagement`` in metadata.yaml. The body is
429        the rendered profile the player or automated agent hands to
430        their client to land on the challenge's DMZ docker network —
431        an OpenVPN ``.ovpn`` or a WireGuard ``.conf``, per the
432        challenge's ``vpn_backend`` (read it off
433        ``InstanceInfo.vpn_backend`` to know which client to run). The
434        platform serves a 404 for simple-mode instances.
435
436        ⚠️ **On WireGuard the filename matters**, and this returns only
437        bytes. ``wg-quick`` takes the interface name from the file's
438        basename and the kernel caps that at 15 characters, so writing
439        these bytes to ``<instance-id>.conf`` produces a file
440        ``wg-quick`` refuses. The ``Content-Disposition`` on the HTTP
441        response carries a name that works; a caller saving to disk
442        should use it, or pick its own short one.
443
444        Raises a ``CTFyError`` (404) when the challenge isn't an
445        engagement-mode one, when the instance hasn't yet reached the
446        running state, or when the node's VPN container hasn't finished
447        its key bootstrap.
448        """
449        resp = self._http.request("GET", f"/instances/{instance_id}/vpn-config")
450        _raise_for_status(resp)
451        return resp.content

Download the per-instance VPN client config as raw bytes.

Only meaningful for challenges that declare network_topology: engagement in metadata.yaml. The body is the rendered profile the player or automated agent hands to their client to land on the challenge's DMZ docker network — an OpenVPN .ovpn or a WireGuard .conf, per the challenge's vpn_backend (read it off InstanceInfo.vpn_backend to know which client to run). The platform serves a 404 for simple-mode instances.

⚠️ On WireGuard the filename matters, and this returns only bytes. wg-quick takes the interface name from the file's basename and the kernel caps that at 15 characters, so writing these bytes to <instance-id>.conf produces a file wg-quick refuses. The Content-Disposition on the HTTP response carries a name that works; a caller saving to disk should use it, or pick its own short one.

Raises a CTFyError (404) when the challenge isn't an engagement-mode one, when the instance hasn't yet reached the running state, or when the node's VPN container hasn't finished its key bootstrap.

def tunnel( self, instance_id: str, *, mode: str = 'auto', timeout: float = 30.0) -> Any:
453    def tunnel(self, instance_id: str, *, mode: str = "auto", timeout: float = 30.0) -> Any:
454        """Open a userspace tunnel to this instance; yields a SOCKS5 address.
455
456        The piece that lets an **unprivileged** caller — an agent, a
457        script, a CI job — reach an engagement challenge::
458
459            with client.instances.tunnel(iid) as tun:
460                requests.get(f"http://{host}/", proxies=tun.proxies)
461
462        ⚠️ Before this, fetching :meth:`vpn_config` was the end of the
463        road for anyone who could not run ``wg-quick`` as root. That is
464        every agent: the MCP surface has no tunnel tool, so an agent
465        received a ``config_url`` it had no way to act on, and an
466        engagement challenge was simply unplayable for it.
467
468        Terminating WireGuard in userspace removes the privilege
469        requirement entirely — no ``/dev/net/tun``, no ``CAP_NET_ADMIN``,
470        no root. See :mod:`ctfy.sdk.tunnel` for which backends are
471        accepted and why none is vendored.
472
473        ``mode`` picks the transport:
474
475        ``interface``
476            A real WireGuard device via ``wg-quick``. ICMP, UDP and raw
477            sockets all work, so `ping` and `nmap` behave — needs
478            ``CAP_NET_ADMIN`` and mutates host routes and resolver.
479        ``socks``
480            The userspace tunnel, reachable as ``tun.proxies``. No
481            privileges and no host state touched; ⚠️ **TCP only**.
482        ``auto`` (default)
483            The first of those that this process can use.
484
485        ⚠️ Ask explicitly when it matters. A challenge that needs ICMP
486        will look *broken* under ``socks`` rather than unreachable, and a
487        laptop does not want its routing table rewritten by a test.
488        """
489        from ctfy.sdk.tunnel import open_tunnel, validate_mode
490
491        # Before the request, so a typo is not reported as a missing
492        # instance.
493        validate_mode(mode)
494        return open_tunnel(self.vpn_config(instance_id).decode(), mode=mode, timeout=timeout)

Open a userspace tunnel to this instance; yields a SOCKS5 address.

The piece that lets an unprivileged caller — an agent, a script, a CI job — reach an engagement challenge::

with client.instances.tunnel(iid) as tun:
    requests.get(f"http://{host}/", proxies=tun.proxies)

⚠️ Before this, fetching vpn_config() was the end of the road for anyone who could not run wg-quick as root. That is every agent: the MCP surface has no tunnel tool, so an agent received a config_url it had no way to act on, and an engagement challenge was simply unplayable for it.

Terminating WireGuard in userspace removes the privilege requirement entirely — no /dev/net/tun, no CAP_NET_ADMIN, no root. See ctfy.sdk.tunnel for which backends are accepted and why none is vendored.

mode picks the transport:

interface A real WireGuard device via wg-quick. ICMP, UDP and raw sockets all work, so ping and nmap behave — needs CAP_NET_ADMIN and mutates host routes and resolver. socks The userspace tunnel, reachable as tun.proxies. No privileges and no host state touched; ⚠️ TCP only. auto (default) The first of those that this process can use.

⚠️ Ask explicitly when it matters. A challenge that needs ICMP will look broken under socks rather than unreachable, and a laptop does not want its routing table rewritten by a test.

def openvpn_config(self, instance_id: str) -> bytes:
496    def openvpn_config(self, instance_id: str) -> bytes:
497        """Deprecated alias for :meth:`vpn_config`.
498
499        Kept because agents and scripts written against the
500        engagement-mode API call it by this name. It returns whatever
501        the challenge actually runs — which for a WireGuard challenge
502        is a ``.conf``, since what the instance ships is not something
503        the method name gets a vote on.
504        """
505        return self.vpn_config(instance_id)

Deprecated alias for vpn_config().

Kept because agents and scripts written against the engagement-mode API call it by this name. It returns whatever the challenge actually runs — which for a WireGuard challenge is a .conf, since what the instance ships is not something the method name gets a vote on.

def traffic( self, instance_id: str, *, competition_id: str = '', cursor: str = '', limit: int = 0) -> dict[str, typing.Any]:
507    def traffic(
508        self,
509        instance_id: str,
510        *,
511        competition_id: str = "",
512        cursor: str = "",
513        limit: int = 0,
514    ) -> dict[str, Any]:
515        """Traffic captured since *cursor*.
516
517        Answers ``{flows, cursor, truncated, capture}``.
518
519        The capture lives on the worker node; the platform proxies the
520        fetch. An absent *cursor* means the whole capture, bounded by
521        the server's page limits — so a caller that wants everything
522        polls until ``truncated`` is false, carrying each reply's
523        ``cursor`` into the next call.
524
525        ⚠️ **This has been answering ``{}`` for every caller.** The
526        route used to return a bare JSON *list* while this method was
527        annotated ``dict`` and coerced anything else to an empty one —
528        so an SDK user got "no capture" from a box with a full one, with
529        nothing raising. The envelope is what makes the annotation true.
530
531        Still returns an empty dict on a genuinely absent capture
532        (sidecar disabled, node offline, instance never ran) so callers
533        can persist conditionally without try/except.
534        """
535        params: dict[str, Any] = {"competition_id": competition_id} if competition_id else {}
536        if cursor:
537            params["cursor"] = cursor
538        # ⚠️ A caller with a *context window* wants far fewer than the
539        # server default of 500 full flows. Omitted means the default,
540        # so an existing caller is unchanged.
541        if limit > 0:
542            params["limit"] = limit
543        resp = self._http.request("GET", f"/instances/{instance_id}/traffic", params=params)
544        _raise_for_status(resp)
545        data = resp.json()
546        return data if isinstance(data, dict) else {}

Traffic captured since cursor.

Answers {flows, cursor, truncated, capture}.

The capture lives on the worker node; the platform proxies the fetch. An absent cursor means the whole capture, bounded by the server's page limits — so a caller that wants everything polls until truncated is false, carrying each reply's cursor into the next call.

⚠️ This has been answering {} for every caller. The route used to return a bare JSON list while this method was annotated dict and coerced anything else to an empty one — so an SDK user got "no capture" from a box with a full one, with nothing raising. The envelope is what makes the annotation true.

Still returns an empty dict on a genuinely absent capture (sidecar disabled, node offline, instance never ran) so callers can persist conditionally without try/except.