cloudsprite 0.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,116 @@
1
+ """Work context: which engineering activity (and attempt) a request or run serves.
2
+
3
+ Contract: the header
4
+ ``X-CloudSprite-Work-Context: activity=<uuid>[;attempt=<uuid>]`` on any request;
5
+ a ``work_context`` body field on ``reportScriptRun`` wins over the header. The
6
+ server ignores an invalid or unrelated header and rejects an invalid body.
7
+
8
+ The context lives in a :class:`contextvars.ContextVar`, so it is isolated per
9
+ thread and per asyncio task. ``CLOUDSPRITE_ACTIVITY`` supplies a process-wide
10
+ default when no ``with`` block is active.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextvars
16
+ import os
17
+ import uuid
18
+ import warnings
19
+ from collections.abc import Iterator
20
+ from contextlib import contextmanager
21
+ from dataclasses import dataclass
22
+ from typing import Any
23
+
24
+ from cloudsprite._exceptions import ValidationError
25
+
26
+ HEADER_NAME = "X-CloudSprite-Work-Context"
27
+ ENV_ACTIVITY = "CLOUDSPRITE_ACTIVITY"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class WorkContext:
32
+ """An activity id plus an optional attempt id (both canonical lowercase UUIDs)."""
33
+
34
+ activity_id: str
35
+ attempt_id: str | None = None
36
+
37
+ def header_value(self) -> str:
38
+ """The ``X-CloudSprite-Work-Context`` header value."""
39
+ value = f"activity={self.activity_id}"
40
+ if self.attempt_id:
41
+ value += f";attempt={self.attempt_id}"
42
+ return value
43
+
44
+ def body(self) -> dict[str, str]:
45
+ """The ``work_context`` request-body object."""
46
+ out = {"activity_id": self.activity_id}
47
+ if self.attempt_id:
48
+ out["attempt_id"] = self.attempt_id
49
+ return out
50
+
51
+
52
+ _env_warned: set[str] = set()
53
+
54
+
55
+ def _as_uuid(value: Any, name: str) -> str:
56
+ """Canonical UUID string from a str, UUID, or an object with ``.id``."""
57
+ raw = getattr(value, "id", value)
58
+ try:
59
+ return str(uuid.UUID(str(raw).strip()))
60
+ except (ValueError, AttributeError, TypeError):
61
+ raise ValidationError(
62
+ f"work_context {name} must be a UUID (or an object with a UUID .id); got {raw!r}"
63
+ ) from None
64
+
65
+
66
+ def env_context() -> WorkContext | None:
67
+ """The process-wide default from ``CLOUDSPRITE_ACTIVITY`` (None when unset or invalid)."""
68
+ raw = os.environ.get(ENV_ACTIVITY, "").strip()
69
+ if not raw:
70
+ return None
71
+ try:
72
+ return WorkContext(str(uuid.UUID(raw)))
73
+ except ValueError:
74
+ if raw not in _env_warned:
75
+ _env_warned.add(raw)
76
+ warnings.warn(f"cloudsprite: {ENV_ACTIVITY} is not a UUID; ignoring it", stacklevel=4)
77
+ return None
78
+
79
+
80
+ def under_run_token() -> bool:
81
+ """True in a server run (``CS_RUN_TOKEN``): the API takes the context from the run token."""
82
+ return bool(os.environ.get("CS_RUN_TOKEN", "").strip())
83
+
84
+
85
+ class WorkScope:
86
+ """Per-client work context, isolated per thread and per asyncio task (a ContextVar).
87
+
88
+ One scope per ``Client`` so a context set for one client (or tenant) never rides on
89
+ another client's requests.
90
+ """
91
+
92
+ def __init__(self) -> None:
93
+ self._var: contextvars.ContextVar[WorkContext | None] = contextvars.ContextVar(
94
+ "cloudsprite_work_context", default=None
95
+ )
96
+
97
+ def explicit(self) -> WorkContext | None:
98
+ """The innermost ``with`` block's context only (no environment default)."""
99
+ return self._var.get()
100
+
101
+ def current(self) -> WorkContext | None:
102
+ """The innermost ``with`` block's context, else ``CLOUDSPRITE_ACTIVITY``."""
103
+ return self._var.get() or env_context()
104
+
105
+ @contextmanager
106
+ def use(self, activity: Any, attempt: Any = None) -> Iterator[WorkContext]:
107
+ """Enter a work context for the block; see ``Client.work_context``."""
108
+ ctx = WorkContext(
109
+ _as_uuid(activity, "activity"),
110
+ _as_uuid(attempt, "attempt") if attempt is not None else None,
111
+ )
112
+ token = self._var.set(ctx)
113
+ try:
114
+ yield ctx
115
+ finally:
116
+ self._var.reset(token)
cloudsprite/_ws.py ADDED
@@ -0,0 +1,577 @@
1
+ """WebSocket operations for instrument capture, control, state, and orb commands.
2
+
3
+ This module is internal — users interact via Instrument.capture() /
4
+ Instrument.state() / Instrument.control() and Orb.reload_instruments().
5
+ All operations are synchronous from the caller's perspective (block until
6
+ complete).
7
+
8
+ Supports execution from both sync contexts (scripts, CLI) and existing
9
+ async contexts (Jupyter, IPython) via automatic event loop detection.
10
+
11
+ Beta for 1.0: capture / state / control / reload_instruments may change
12
+ shape before 1.1.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ import uuid
20
+ from collections.abc import Coroutine
21
+ from typing import TYPE_CHECKING, Any, TypeVar
22
+
23
+ from cloudsprite._exceptions import ValidationError, validate_id
24
+
25
+ if TYPE_CHECKING:
26
+ from cloudsprite._client import HTTPClient
27
+
28
+ _T = TypeVar("_T")
29
+
30
+ _WS_IMPORT_HINT = "aiohttp is required for WebSocket operations. Install it with: pip install cloudsprite[ws]"
31
+
32
+
33
+ def _resolve_team_slug(http: "HTTPClient", team_slug: str | None = None) -> str:
34
+ """Resolve team slug from explicit arg or the owning Client.
35
+
36
+ Raises:
37
+ ValidationError: If no team is set.
38
+ """
39
+ if team_slug:
40
+ return team_slug
41
+ owner = http.owner()
42
+ slug = owner.team_slug if owner is not None else None
43
+ if not slug:
44
+ raise ValidationError(
45
+ "No team set. Call cs.set_team('your-team') or pass team=... to "
46
+ "Client(...) before using WebSocket operations (capture, state, "
47
+ "control, reload_instruments)."
48
+ )
49
+ return slug
50
+
51
+
52
+ def _list_payload(payload: Any) -> list[Any]:
53
+ """Normalize list-or-paginated API payloads to a plain list."""
54
+ if isinstance(payload, list):
55
+ return payload
56
+ if isinstance(payload, dict):
57
+ results = payload.get("results")
58
+ if isinstance(results, list):
59
+ return results
60
+ return []
61
+
62
+
63
+ def _resolve_org_slug(
64
+ http: "HTTPClient",
65
+ team_slug: str,
66
+ org_slug: str | None = None,
67
+ ) -> str:
68
+ """Resolve the org (tenant) slug required for org-scoped WS URLs.
69
+
70
+ Order: explicit arg → owning Client.org_slug → per-team cache → scan
71
+ ``/api/tenants/`` + ``/api/teams/`` for a unique match.
72
+ """
73
+ if org_slug:
74
+ return org_slug
75
+
76
+ owner = http.owner()
77
+ if owner is not None:
78
+ if owner.org_slug:
79
+ return owner.org_slug
80
+ cached = owner._team_org_cache.get(team_slug)
81
+ if cached:
82
+ return cached
83
+
84
+ tenants = _list_payload(http.get("/api/tenants/"))
85
+ matches: list[str] = []
86
+ for tenant in tenants:
87
+ if not isinstance(tenant, dict):
88
+ continue
89
+ tid = tenant.get("id")
90
+ slug = tenant.get("slug")
91
+ if not isinstance(tid, str) or not isinstance(slug, str):
92
+ continue
93
+ teams = _list_payload(http.get("/api/teams/", headers={"X-Tenant-ID": tid}))
94
+ if any(isinstance(t, dict) and t.get("slug") == team_slug for t in teams):
95
+ matches.append(slug)
96
+
97
+ if len(matches) == 1:
98
+ resolved = matches[0]
99
+ if owner is not None:
100
+ owner._team_org_cache[team_slug] = resolved
101
+ return resolved
102
+ if len(matches) > 1:
103
+ raise ValidationError(
104
+ f"Team {team_slug!r} exists in multiple orgs ({', '.join(matches)}). "
105
+ "Pass org=... to Client(...) or call cs.set_org('your-org') before "
106
+ "WebSocket operations."
107
+ )
108
+ raise ValidationError(
109
+ f"Could not find org for team {team_slug!r}. "
110
+ "Pass org=... to Client(...) or call cs.set_org('your-org') before "
111
+ "WebSocket operations."
112
+ )
113
+
114
+
115
+ def _prepare_ws_connection(
116
+ client: "HTTPClient",
117
+ team_slug: str,
118
+ org_slug: str | None = None,
119
+ ) -> tuple[str, dict[str, str]]:
120
+ """Obtain a WS token and return ``(url, headers)`` for the handshake.
121
+
122
+ Performs a network POST to mint a short-lived WebSocket token. Callers
123
+ MUST pass ``headers`` to ``ws_connect`` — the token is never placed in the
124
+ URL (query strings land in proxy and access logs by default).
125
+
126
+ The URL is org-scoped: ``/ws/client-comms/<org_slug>/<team_slug>/``.
127
+ """
128
+ # Validate path segments before URL interpolation (prevents path injection)
129
+ validate_id(team_slug, "team_slug")
130
+ resolved_org = _resolve_org_slug(client, team_slug, org_slug)
131
+ validate_id(resolved_org, "org_slug")
132
+
133
+ base = client._config.base_url
134
+ host = base.replace("https://", "").replace("http://", "")
135
+ proto = "wss" if "https" in base else "ws"
136
+
137
+ ws_data = client.post("/api/auth/websocket-token")
138
+ token = ws_data["access"]
139
+
140
+ url = f"{proto}://{host}/ws/client-comms/{resolved_org}/{team_slug}/"
141
+ headers = {"Authorization": f"Bearer {token}"}
142
+ return url, headers
143
+
144
+
145
+ def _timeout_ms(timeout: float) -> int:
146
+ """Convert a seconds timeout to a non-negative millisecond budget."""
147
+ return max(0, int(timeout * 1000))
148
+
149
+
150
+ def _build_get_instrument_state_message(
151
+ *,
152
+ instrument_id: str,
153
+ team_slug: str,
154
+ timeout: float,
155
+ sections: list[str] | None = None,
156
+ target_orb_id: str = "",
157
+ ) -> dict[str, Any]:
158
+ """Build the outbound ``get_instrument_state`` WebSocket payload."""
159
+ message: dict[str, Any] = {
160
+ "type": "get_instrument_state",
161
+ "command_id": str(uuid.uuid4()),
162
+ "instrument_id": instrument_id,
163
+ "timeout_ms": _timeout_ms(timeout),
164
+ "respond_to_user_channel": f"team_{team_slug}",
165
+ "target_orb_id": target_orb_id,
166
+ "requestor": "cloudsprite-sdk",
167
+ }
168
+ if sections is not None:
169
+ message["sections"] = list(sections)
170
+ return message
171
+
172
+
173
+ def _build_instrument_control_message(
174
+ *,
175
+ instrument_id: str,
176
+ team_slug: str,
177
+ method: str,
178
+ timeout: float,
179
+ args: dict[str, Any] | None = None,
180
+ target_orb_id: str = "",
181
+ ) -> dict[str, Any]:
182
+ """Build the outbound ``instrument_control`` WebSocket payload."""
183
+ return {
184
+ "type": "instrument_control",
185
+ "command_id": str(uuid.uuid4()),
186
+ "instrument_id": instrument_id,
187
+ "method": method,
188
+ "args": dict(args or {}),
189
+ "timeout_ms": _timeout_ms(timeout),
190
+ "respond_to_user_channel": f"team_{team_slug}",
191
+ "target_orb_id": target_orb_id,
192
+ "requestor": "cloudsprite-sdk",
193
+ }
194
+
195
+
196
+ async def _ws_roundtrip(
197
+ client: "HTTPClient",
198
+ message: dict[str, Any],
199
+ response_type: str,
200
+ timeout: float,
201
+ team_slug: str | None = None,
202
+ org_slug: str | None = None,
203
+ *,
204
+ await_group_join: bool = True,
205
+ ) -> dict[str, Any]:
206
+ """Connect, optionally wait for channel-group membership, send, await reply."""
207
+ try:
208
+ import aiohttp
209
+ except ImportError as exc:
210
+ raise ImportError(_WS_IMPORT_HINT) from exc
211
+
212
+ resolved_team = _resolve_team_slug(client, team_slug)
213
+ ws_url, headers = _prepare_ws_connection(client, resolved_team, org_slug=org_slug)
214
+
215
+ async with aiohttp.ClientSession() as session:
216
+ async with session.ws_connect(ws_url, headers=headers) as ws:
217
+ # Wait for the backend to finish adding this connection to the
218
+ # _responses channel group. Without this, the response can be sent
219
+ # to _responses before we're a member of that group.
220
+ # 1s is conservative but reliable across production environments.
221
+ if await_group_join:
222
+ await asyncio.sleep(1.0)
223
+ await ws.send_json(message)
224
+ try:
225
+ async with asyncio.timeout(timeout):
226
+ async for raw_msg in ws:
227
+ if raw_msg.type == aiohttp.WSMsgType.TEXT:
228
+ data = json.loads(raw_msg.data)
229
+ if isinstance(data, dict) and data.get("type") == response_type:
230
+ return data
231
+ elif raw_msg.type in (aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSED):
232
+ return {"success": False, "error": "ws_closed_unexpectedly"}
233
+ except asyncio.TimeoutError:
234
+ return {"success": False, "error": f"timeout after {timeout}s"}
235
+
236
+ return {"success": False, "error": "ws_closed"}
237
+
238
+
239
+ async def _async_capture_all(
240
+ client: "HTTPClient",
241
+ instrument_id: str,
242
+ dataset_id: str,
243
+ timeout: float = 60.0,
244
+ team_slug: str | None = None,
245
+ org_slug: str | None = None,
246
+ **kwargs: Any,
247
+ ) -> dict[str, Any]:
248
+ """Send capture_all via WebSocket and wait for response.
249
+
250
+ Args:
251
+ client: Authenticated HTTPClient instance.
252
+ instrument_id: UUID of the instrument to capture from.
253
+ dataset_id: UUID of the dataset to store results.
254
+ timeout: Maximum seconds to wait for capture completion.
255
+ team_slug: Optional team slug; defaults to the owning Client's team.
256
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
257
+ or a unique match for ``team_slug``.
258
+ **kwargs: Additional capture parameters (simulation_mode, noise_level,
259
+ sim_scenario, num_points, channel, target_orb_id).
260
+
261
+ Returns:
262
+ Response dict with 'success', 'completed', 'total', and optional
263
+ 'error' fields.
264
+ """
265
+ resolved_team = _resolve_team_slug(client, team_slug)
266
+ message: dict[str, Any] = {
267
+ "type": "capture_all",
268
+ "command_id": str(uuid.uuid4()),
269
+ "instrument_id": instrument_id,
270
+ "dataset_id": dataset_id,
271
+ "data": {
272
+ "channel": kwargs.get("channel", 1),
273
+ "simulation_mode": kwargs.get("simulation_mode", False),
274
+ },
275
+ "respond_to_user_channel": f"team_{resolved_team}",
276
+ "target_orb_id": kwargs.get("target_orb_id", ""),
277
+ "requestor": "cloudsprite-sdk",
278
+ }
279
+
280
+ for key in ("noise_level", "sim_scenario", "num_points"):
281
+ if key in kwargs:
282
+ message["data"][key] = kwargs[key]
283
+
284
+ return await _ws_roundtrip(
285
+ client,
286
+ message,
287
+ "capture_all_response",
288
+ timeout,
289
+ team_slug=resolved_team,
290
+ org_slug=org_slug,
291
+ await_group_join=True,
292
+ )
293
+
294
+
295
+ async def _async_get_instrument_state(
296
+ client: "HTTPClient",
297
+ instrument_id: str,
298
+ sections: list[str] | None = None,
299
+ timeout: float = 15.0,
300
+ team_slug: str | None = None,
301
+ org_slug: str | None = None,
302
+ **kwargs: Any,
303
+ ) -> dict[str, Any]:
304
+ """Send get_instrument_state via WebSocket and wait for instrument_state."""
305
+ resolved_team = _resolve_team_slug(client, team_slug)
306
+ message = _build_get_instrument_state_message(
307
+ instrument_id=instrument_id,
308
+ team_slug=resolved_team,
309
+ timeout=timeout,
310
+ sections=sections,
311
+ target_orb_id=str(kwargs.get("target_orb_id", "") or ""),
312
+ )
313
+ return await _ws_roundtrip(
314
+ client,
315
+ message,
316
+ "instrument_state",
317
+ timeout,
318
+ team_slug=resolved_team,
319
+ org_slug=org_slug,
320
+ await_group_join=True,
321
+ )
322
+
323
+
324
+ async def _async_instrument_control(
325
+ client: "HTTPClient",
326
+ instrument_id: str,
327
+ method: str,
328
+ timeout: float = 15.0,
329
+ team_slug: str | None = None,
330
+ org_slug: str | None = None,
331
+ **args: Any,
332
+ ) -> dict[str, Any]:
333
+ """Send instrument_control via WebSocket and wait for the response."""
334
+ resolved_team = _resolve_team_slug(client, team_slug)
335
+ target_orb_id = str(args.pop("target_orb_id", "") or "")
336
+ message = _build_instrument_control_message(
337
+ instrument_id=instrument_id,
338
+ team_slug=resolved_team,
339
+ method=method,
340
+ timeout=timeout,
341
+ args=args,
342
+ target_orb_id=target_orb_id,
343
+ )
344
+ return await _ws_roundtrip(
345
+ client,
346
+ message,
347
+ "instrument_control_response",
348
+ timeout,
349
+ team_slug=resolved_team,
350
+ org_slug=org_slug,
351
+ await_group_join=True,
352
+ )
353
+
354
+
355
+ async def _async_reload_instruments(
356
+ client: HTTPClient,
357
+ timeout: float = 15.0,
358
+ team_slug: str | None = None,
359
+ org_slug: str | None = None,
360
+ ) -> dict[str, Any]:
361
+ """Send reload_instruments via WebSocket and wait for response.
362
+
363
+ Args:
364
+ client: Authenticated HTTPClient instance.
365
+ timeout: Maximum seconds to wait for acknowledgment.
366
+ team_slug: Optional team slug; defaults to the owning Client's team.
367
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
368
+ or a unique match for ``team_slug``.
369
+
370
+ Returns:
371
+ Response dict with 'success' and 'instrument_count' fields.
372
+ """
373
+ resolved_team = _resolve_team_slug(client, team_slug)
374
+ message = {
375
+ "type": "reload_instruments",
376
+ "channel": f"team_{resolved_team}",
377
+ }
378
+ return await _ws_roundtrip(
379
+ client,
380
+ message,
381
+ "reload_instruments_response",
382
+ timeout,
383
+ team_slug=resolved_team,
384
+ org_slug=org_slug,
385
+ await_group_join=False,
386
+ )
387
+
388
+
389
+ def _run_async(coro: Coroutine[Any, Any, _T]) -> _T:
390
+ """Run an async coroutine from sync code, handling existing event loops.
391
+
392
+ Supports:
393
+ - Normal scripts (no running loop) → asyncio.run()
394
+ - Jupyter/IPython (loop already running) → thread pool fallback
395
+ """
396
+ try:
397
+ asyncio.get_running_loop()
398
+ except RuntimeError:
399
+ # No running loop — standard path
400
+ return asyncio.run(coro)
401
+
402
+ # Already inside an event loop (Jupyter, IPython, etc.)
403
+ import concurrent.futures
404
+
405
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
406
+ future = pool.submit(asyncio.run, coro)
407
+ return future.result()
408
+
409
+
410
+ def capture_all(
411
+ client: HTTPClient,
412
+ instrument_id: str,
413
+ dataset_id: str,
414
+ timeout: float = 60.0,
415
+ team_slug: str | None = None,
416
+ org_slug: str | None = None,
417
+ **kwargs: Any,
418
+ ) -> dict[str, Any]:
419
+ """Trigger a capture on an instrument and wait for completion.
420
+
421
+ This is a synchronous call that blocks until the capture completes,
422
+ times out, or encounters an error. Works in both regular scripts
423
+ and Jupyter notebooks.
424
+
425
+ **Beta** for 1.0 — may change shape before 1.1.
426
+
427
+ Args:
428
+ client: Authenticated HTTPClient instance.
429
+ instrument_id: UUID of the instrument to capture from.
430
+ dataset_id: UUID of the target dataset.
431
+ timeout: Maximum wait time in seconds (default: 60).
432
+ team_slug: Optional team slug; defaults to the owning Client's team.
433
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
434
+ or a unique match for ``team_slug``.
435
+ **kwargs: Capture options — simulation_mode (bool), noise_level (float),
436
+ sim_scenario (str), channel (int), target_orb_id (str).
437
+
438
+ Returns:
439
+ dict with keys:
440
+ success (bool): Whether capture completed successfully.
441
+ completed (int): Number of sub-commands that succeeded.
442
+ total (int): Total sub-commands attempted.
443
+ error (str, optional): Error description if failed.
444
+
445
+ Raises:
446
+ ValidationError: If no team is set, or org cannot be resolved uniquely.
447
+
448
+ Example:
449
+ >>> result = scope.capture(dataset_id=ds.id, timeout=30)
450
+ >>> if result["success"]:
451
+ ... print(f"Captured {result['completed']} channels")
452
+ """
453
+ return _run_async(
454
+ _async_capture_all(
455
+ client,
456
+ instrument_id,
457
+ dataset_id,
458
+ timeout,
459
+ team_slug=team_slug,
460
+ org_slug=org_slug,
461
+ **kwargs,
462
+ )
463
+ )
464
+
465
+
466
+ def get_instrument_state(
467
+ client: HTTPClient,
468
+ instrument_id: str,
469
+ sections: list[str] | None = None,
470
+ timeout: float = 15.0,
471
+ team_slug: str | None = None,
472
+ org_slug: str | None = None,
473
+ **kwargs: Any,
474
+ ) -> dict[str, Any]:
475
+ """Fetch live instrument state sections via WebSocket.
476
+
477
+ **Beta** for 1.0 — may change shape before 1.1.
478
+
479
+ Args:
480
+ client: Authenticated HTTPClient instance.
481
+ instrument_id: UUID of the instrument to query.
482
+ sections: Optional list of state section names to return.
483
+ timeout: Maximum wait time in seconds (default: 15).
484
+ team_slug: Optional team slug; defaults to the owning Client's team.
485
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
486
+ or a unique match for ``team_slug``.
487
+ **kwargs: Optional ``target_orb_id`` to pin a specific orb.
488
+
489
+ Returns:
490
+ Response dict with ``success``, optional ``state``, and optional ``error``.
491
+ """
492
+ return _run_async(
493
+ _async_get_instrument_state(
494
+ client,
495
+ instrument_id,
496
+ sections=sections,
497
+ timeout=timeout,
498
+ team_slug=team_slug,
499
+ org_slug=org_slug,
500
+ **kwargs,
501
+ )
502
+ )
503
+
504
+
505
+ def instrument_control(
506
+ client: HTTPClient,
507
+ instrument_id: str,
508
+ method: str,
509
+ timeout: float = 15.0,
510
+ team_slug: str | None = None,
511
+ org_slug: str | None = None,
512
+ **args: Any,
513
+ ) -> dict[str, Any]:
514
+ """Invoke a driver control method via WebSocket.
515
+
516
+ **Beta** for 1.0 — may change shape before 1.1.
517
+
518
+ Args:
519
+ client: Authenticated HTTPClient instance.
520
+ instrument_id: UUID of the instrument to control.
521
+ method: Driver control method name (e.g. ``set_timebase``).
522
+ timeout: Maximum wait time in seconds (default: 15).
523
+ team_slug: Optional team slug; defaults to the owning Client's team.
524
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
525
+ or a unique match for ``team_slug``.
526
+ **args: Control arguments. ``target_orb_id`` is a top-level WS field;
527
+ all other kwargs are sent in the WS ``args`` object.
528
+
529
+ Returns:
530
+ Response dict with ``success``, optional ``result``, and optional ``error``.
531
+ """
532
+ return _run_async(
533
+ _async_instrument_control(
534
+ client,
535
+ instrument_id,
536
+ method,
537
+ timeout=timeout,
538
+ team_slug=team_slug,
539
+ org_slug=org_slug,
540
+ **args,
541
+ )
542
+ )
543
+
544
+
545
+ def reload_instruments(
546
+ client: HTTPClient,
547
+ timeout: float = 15.0,
548
+ team_slug: str | None = None,
549
+ org_slug: str | None = None,
550
+ ) -> dict[str, Any]:
551
+ """Ask the orb to reload its instrument list from the backend.
552
+
553
+ Use after adding or removing instrument associations in the web UI
554
+ to hot-reload without restarting the orb.
555
+
556
+ **Beta** for 1.0 — may change shape before 1.1.
557
+
558
+ Args:
559
+ client: Authenticated HTTPClient instance.
560
+ timeout: Maximum wait time in seconds (default: 15).
561
+ team_slug: Optional team slug; defaults to the owning Client's team.
562
+ org_slug: Optional org (tenant) slug; defaults to the owning Client's org
563
+ or a unique match for ``team_slug``.
564
+
565
+ Returns:
566
+ dict with keys:
567
+ success (bool): Whether reload completed.
568
+ instrument_count (int): Number of instruments now managed.
569
+
570
+ Raises:
571
+ ValidationError: If no team is set, or org cannot be resolved uniquely.
572
+
573
+ Example:
574
+ >>> orb.reload_instruments()
575
+ {'success': True, 'instrument_count': 3}
576
+ """
577
+ return _run_async(_async_reload_instruments(client, timeout, team_slug=team_slug, org_slug=org_slug))