dynos-client 0.2.2__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {dynos_client-0.2.2 → dynos_client-0.2.5}/PKG-INFO +2 -2
  2. {dynos_client-0.2.2 → dynos_client-0.2.5}/pyproject.toml +2 -2
  3. dynos_client-0.2.5/src/dynos_client/_config.py +22 -0
  4. dynos_client-0.2.5/src/dynos_client/_credentials.py +38 -0
  5. dynos_client-0.2.5/src/dynos_client/_http_errors.py +31 -0
  6. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/action_context.py +20 -1
  7. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/auth_cli.py +4 -6
  8. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/belief.py +9 -70
  9. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/call.py +4 -9
  10. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/mission.py +13 -8
  11. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/remote_orchestrator.py +21 -24
  12. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/session_cli.py +10 -38
  13. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/session_manager.py +1 -1
  14. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/PKG-INFO +2 -2
  15. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/SOURCES.txt +3 -0
  16. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/requires.txt +1 -1
  17. {dynos_client-0.2.2 → dynos_client-0.2.5}/README.md +0 -0
  18. {dynos_client-0.2.2 → dynos_client-0.2.5}/setup.cfg +0 -0
  19. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/__init__.py +0 -0
  20. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/__main__.py +0 -0
  21. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/action.py +0 -0
  22. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/cli.py +0 -0
  23. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/domain.py +0 -0
  24. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/expr_parser.py +0 -0
  25. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/hash_cli.py +0 -0
  26. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/resolve_runnable.py +0 -0
  27. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client/servant.py +0 -0
  28. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/dependency_links.txt +0 -0
  29. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/entry_points.txt +0 -0
  30. {dynos_client-0.2.2 → dynos_client-0.2.5}/src/dynos_client.egg-info/top_level.txt +0 -0
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dynos-client
3
- Version: 0.2.2
3
+ Version: 0.2.5
4
4
  Summary: Client and CLI for orchestrating DYNOS backends remotely
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.8
7
7
  Description-Content-Type: text/markdown
8
- Requires-Dist: dynos-core>=0.2.2
8
+ Requires-Dist: dynos-core>=0.2.5
9
9
  Requires-Dist: requests
10
10
  Requires-Dist: typer
11
11
  Requires-Dist: bcrypt>=4.0
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "dynos-client"
7
- version = "0.2.2"
7
+ version = "0.2.5"
8
8
  description = "Client and CLI for orchestrating DYNOS backends remotely"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
11
11
  requires-python = ">=3.8"
12
- dependencies = ["dynos-core>=0.2.2", "requests", "typer", "bcrypt>=4.0", "rich"]
12
+ dependencies = ["dynos-core>=0.2.5", "requests", "typer", "bcrypt>=4.0", "rich"]
13
13
 
14
14
  [project.scripts]
15
15
  dynos = "dynos_client.cli:main"
@@ -0,0 +1,22 @@
1
+ """Single source for the on-disk DYNOS client config (token cache) location.
2
+
3
+ ``dynos login`` writes the bearer token + backend URL here; every reader (the
4
+ ``dynos session`` CLI, ``dynos call``, ``RemoteOrchestrator.from_config``) must
5
+ resolve the SAME path, or ``login`` writes a token a reader never finds and the
6
+ user silently appears logged out. One definition so the write path and every
7
+ read path cannot drift. Overridable via ``DYNOS_CONFIG_PATH`` (tests point it at
8
+ a temp file).
9
+ """
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ #: Env var that overrides the default config-file location.
15
+ CONFIG_PATH_ENV = "DYNOS_CONFIG_PATH"
16
+
17
+
18
+ def config_path() -> Path:
19
+ """Path to the client config file (``~/.dynos/config.json`` by default)."""
20
+ return Path(
21
+ os.environ.get(CONFIG_PATH_ENV, str(Path.home() / ".dynos" / "config.json"))
22
+ )
@@ -0,0 +1,38 @@
1
+ """Shared credential-file safety check.
2
+
3
+ One source of truth for the "refuse, don't chmod" invariant: a bearer token
4
+ stored in a world/group-readable file is a credential anyone with shell access
5
+ can read, so refuse to load it and point the operator at the fix rather than
6
+ silently changing their file permissions. Reused by every CLI that reads the
7
+ cached token so the security behavior cannot drift between copies.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from pathlib import Path
14
+
15
+ import typer
16
+ from rich.console import Console
17
+
18
+ _console = Console()
19
+
20
+
21
+ def refuse_if_world_or_group_readable(path: Path) -> None:
22
+ """Refuse to load a token from a file readable by group or world.
23
+
24
+ The bearer token in the config file is a credential. We do not silently
25
+ ``chmod``; the operator decides whether to fix the permissions or rotate
26
+ the credential. Skipped on platforms without POSIX file modes (Windows).
27
+ """
28
+ try:
29
+ mode = os.stat(str(path)).st_mode & 0o777
30
+ except OSError:
31
+ return # file vanished between the caller's check and stat(); caller handles
32
+ if mode & 0o077:
33
+ _console.print(
34
+ f"[red]Refusing to read {path}: mode is {oct(mode)} (group/world "
35
+ f"accessible). The token is a credential. Run "
36
+ f"`chmod 600 {path}` or rotate the token via `dynos login`.[/red]"
37
+ )
38
+ raise typer.Exit(1)
@@ -0,0 +1,31 @@
1
+ """Shared best-effort extraction of a short error detail from an HTTP response.
2
+
3
+ One source of truth for turning a 4xx/5xx ``requests.Response`` into a concise
4
+ human-readable string, reused by the remote orchestrator and the CLI command
5
+ groups so the robust JSON-``detail``/body/status fallback does not drift into
6
+ thinner hand-rolled copies.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING
12
+
13
+ if TYPE_CHECKING:
14
+ import requests
15
+
16
+
17
+ def resp_detail(resp: "requests.Response") -> str:
18
+ """Best-effort short detail string from an error response.
19
+
20
+ Tries the JSON ``detail`` field (FastAPI's convention), falls back to the
21
+ body text, then the status line. Truncated to keep error messages short.
22
+ """
23
+ try:
24
+ body = resp.json()
25
+ if isinstance(body, dict):
26
+ d = body.get("detail")
27
+ if isinstance(d, str):
28
+ return d
29
+ return str(body)[:200]
30
+ except (ValueError, TypeError):
31
+ return resp.text[:200] if resp.text else f"HTTP {resp.status_code}"
@@ -8,7 +8,7 @@ when dispatched via ``dynos connect``: a structured logger, the audit ID, and
8
8
  the transition name.
9
9
 
10
10
  If a user's ``@Action`` reaches for ``ctx.report_progress`` /
11
- ``ctx.check_cancelled`` / ``ctx.read_sensor`` / ``ctx.call_hardware`` from
11
+ ``ctx.check_cancelled`` / ``ctx.read_sensor`` / ``ctx.heartbeat`` from
12
12
  the servant side, an ``AttributeError`` is the right outcome; the action
13
13
  is using backend-only machinery that isn't available remotely.
14
14
  """
@@ -65,3 +65,22 @@ class ClientActionContext:
65
65
  default_factory=lambda: _ClientActionLogger(logging.getLogger("dynos.servant"))
66
66
  )
67
67
  orchestrator: Optional[Any] = None
68
+
69
+ def _require_orchestrator(self) -> Any:
70
+ if self.orchestrator is None:
71
+ raise RuntimeError(
72
+ f"ctx.create_object/list_objects for '{self.transition_name}' has no "
73
+ f"orchestrator: this servant context was built without one. Dispatch via "
74
+ f"RemoteOrchestrator.trigger_action (which wires it), do not reconstruct "
75
+ f"a client from ~/.dynos."
76
+ )
77
+ return self.orchestrator
78
+
79
+ def create_object(self, obj: Any) -> Any:
80
+ """Register a domain object on the backend this servant is connected to --
81
+ the audited object-management capability, portable with the in-process ctx."""
82
+ return self._require_orchestrator().create_object(obj)
83
+
84
+ def list_objects(self) -> Any:
85
+ """List the backend's domain objects (same records as the in-process ctx)."""
86
+ return self._require_orchestrator().list_objects()
@@ -16,6 +16,7 @@ import typer
16
16
  from rich.console import Console
17
17
  from rich.table import Table, box
18
18
 
19
+ from dynos_client._http_errors import resp_detail
19
20
  from dynos_client.call import DEFAULT_BACKEND, _normalize_backend_url
20
21
  from dynos_client.session_cli import _read_cache, _write_cache
21
22
 
@@ -59,12 +60,9 @@ def login(
59
60
  console.print(f"[red]Cannot reach {url}: {exc}[/red]")
60
61
  raise typer.Exit(1)
61
62
  if resp.status_code != 200:
62
- detail = resp.text
63
- try:
64
- detail = resp.json().get("detail", detail)
65
- except Exception:
66
- pass
67
- console.print(f"[red]Login failed ({resp.status_code}): {detail}[/red]")
63
+ console.print(
64
+ f"[red]Login failed ({resp.status_code}): {resp_detail(resp)}[/red]"
65
+ )
68
66
  raise typer.Exit(1)
69
67
  body = resp.json()
70
68
 
@@ -1,4 +1,4 @@
1
- """Client-side @Belief decorator and BeliefResult.
1
+ """Client-side @Belief decorator.
2
2
 
3
3
  The client analogue of the backend ``@Belief`` machinery, so a servant
4
4
  (``dynos connect``) can register belief callbacks the same way it registers
@@ -7,12 +7,19 @@ servant -- a belief callback RUNS on the servant: the backend asks the servant
7
7
  "what do you observe for fluent X?", the servant executes the callback against
8
8
  its own sensor/simulator, and returns the observed atoms.
9
9
 
10
+ ``BeliefResult`` is NOT redefined here: it lives once in :mod:`dynos_core`
11
+ (both the client and the backend return and consume the same class) and is
12
+ re-exported below so ``from dynos_client.belief import BeliefResult`` keeps
13
+ working.
14
+
10
15
  When the backend IS installed, its ``@Belief`` (dynos.databases.typed_action)
11
16
  takes precedence; ``get_belief_methods`` understands both shapes.
12
17
  """
13
18
 
14
19
  import inspect
15
- from typing import Any, FrozenSet, List, Optional, Tuple
20
+ from typing import Any, List, Optional, Tuple
21
+
22
+ from dynos_core import BeliefResult # noqa: F401 (re-exported)
16
23
 
17
24
 
18
25
  def _fluent_name(fluent: Any) -> Optional[str]:
@@ -28,74 +35,6 @@ def _fluent_name(fluent: Any) -> Optional[str]:
28
35
  return str(fluent).split("(")[0]
29
36
 
30
37
 
31
- class BeliefResult:
32
- """What a belief callback observed. Mirror of the backend BeliefResult.
33
-
34
- ``observed_state`` is a list of grounded fluent SYMBOLS (e.g. ``at(wp)``);
35
- they are serialized to their wire form at the servant boundary.
36
-
37
- Field order and ``acquired``'s signature match the backend BeliefResult so a
38
- servant class behaves identically whether it runs with the client or the
39
- backend ``BeliefResult`` (e.g. ``acquired(observed_state=[...])`` means the
40
- same thing on both). The compatibility test in
41
- ``tests/client/test_belief_result_compat.py`` guards against drift.
42
- """
43
-
44
- def __init__(
45
- self,
46
- success: bool = True,
47
- is_unchecked: bool = False,
48
- value: Any = None,
49
- observed_state: Optional[List[Any]] = None,
50
- message: str = "",
51
- exclusive_fluents: Optional[FrozenSet[str]] = None,
52
- ):
53
- self.success = success
54
- self.is_unchecked = is_unchecked
55
- self.value = value
56
- self.observed_state = observed_state or []
57
- self.message = message
58
- # Fluent names this result reports completely; the backend retracts
59
- # their other current groundings on apply (single-valued semantics).
60
- self.exclusive_fluents = exclusive_fluents or frozenset()
61
-
62
- @classmethod
63
- def acquired(
64
- cls,
65
- value: Any = None,
66
- observed_state: Optional[List[Any]] = None,
67
- ) -> "BeliefResult":
68
- """A successful observation. Prefer ``observed_state`` with the fluent
69
- SYMBOLS actually observed, e.g.
70
- ``BeliefResult.acquired(observed_state=[at(wp)])``. ``value`` is optional
71
- supplementary metadata (kept for backend parity). The positional order
72
- is ``(value, observed_state)`` -- matching the backend -- so pass
73
- ``observed_state`` by keyword."""
74
- return cls(success=True, value=value, observed_state=observed_state or [])
75
-
76
- @classmethod
77
- def sole(cls, atom: Any) -> "BeliefResult":
78
- """Report *atom* as the fluent's one true grounding: set it true and
79
- retract every other current grounding of the same fluent. The
80
- single-valued form (matches the backend); a multi-valued fluent uses
81
- ``acquired`` with all the symbols observed."""
82
- return cls(
83
- success=True,
84
- observed_state=[atom],
85
- exclusive_fluents=frozenset({_fluent_name(atom)}),
86
- )
87
-
88
- @classmethod
89
- def unchecked(cls) -> "BeliefResult":
90
- """Did not observe this fluent this cycle; preserve the last known value."""
91
- return cls(success=True, is_unchecked=True)
92
-
93
- @classmethod
94
- def failed(cls, message: str = "") -> "BeliefResult":
95
- """Observation failed (e.g. sensor error); gates the step."""
96
- return cls(success=False, message=message)
97
-
98
-
99
38
  def Belief(
100
39
  fluent: Any = None,
101
40
  object: Any = None,
@@ -18,6 +18,8 @@ from typing import List, Optional
18
18
 
19
19
  import typer
20
20
 
21
+ from dynos_client._config import config_path
22
+ from dynos_client._http_errors import resp_detail
21
23
  from dynos_client.expr_parser import parse_call_expr
22
24
  from dynos_client.remote_orchestrator import RemoteOrchestrator
23
25
 
@@ -50,11 +52,8 @@ def _load_cached_auth():
50
52
  uses these to default session-mode commands to the cached values.
51
53
  """
52
54
  import json
53
- import os
54
55
 
55
- path = Path(
56
- os.environ.get("DYNOS_CONFIG_PATH", str(Path.home() / ".dynos" / "config.json"))
57
- )
56
+ path = config_path()
58
57
  if not path.exists():
59
58
  return None, None, None
60
59
  try:
@@ -139,11 +138,7 @@ def _handle_error(e: Exception, to: str = "") -> None:
139
138
  )
140
139
  elif isinstance(e, requests.HTTPError):
141
140
  status = getattr(e.response, "status_code", "?")
142
- detail = ""
143
- try:
144
- detail = e.response.json().get("detail", e.response.text)
145
- except Exception:
146
- detail = getattr(e.response, "text", str(e))
141
+ detail = resp_detail(e.response) if e.response is not None else str(e)
147
142
  typer.echo(f"Backend returned HTTP {status}: {detail}", err=True)
148
143
  else:
149
144
  typer.echo(f"Error: {e}", err=True)
@@ -8,6 +8,7 @@ This is the canonical implementation. The backend's `dynos.api.mission`
8
8
  re-exports from here.
9
9
 
10
10
  Block type guide:
11
+
11
12
  - `AnyActionBlock(transition)`: preferred for typed Python missions.
12
13
  Binds to a `Transition` (e.g. `sentry.trackline`).
13
14
  - `ActionBlock(action)`: for an anonymous `@Action` callback. A string
@@ -22,6 +23,7 @@ from typing import Any, Dict, List, Optional
22
23
 
23
24
  from dynos_core.atom import GroundAtom
24
25
  from dynos_core.transition import TransitionParams
26
+ from dynos_core.wire_types import BLOCK_ACTION, BLOCK_ORDER, BLOCK_PLAN
25
27
 
26
28
  __all__ = [
27
29
  "AnyActionBlock",
@@ -98,7 +100,7 @@ class AnyActionBlock:
98
100
  return f"AnyActionBlock(action={self.action!r}, params={self.params!r})"
99
101
 
100
102
  def to_dict(self) -> Dict[str, Any]:
101
- d: Dict[str, Any] = {"type": "action", "action": self.action}
103
+ d: Dict[str, Any] = {"type": BLOCK_ACTION, "action": self.action}
102
104
  if self.params is not None:
103
105
  d["params"] = self.params
104
106
  return d
@@ -169,7 +171,7 @@ class ActionBlock:
169
171
  return f"ActionBlock(action={self.action!r}, params={self.params!r})"
170
172
 
171
173
  def to_dict(self) -> Dict[str, Any]:
172
- d: Dict[str, Any] = {"type": "action", "action": self.action}
174
+ d: Dict[str, Any] = {"type": BLOCK_ACTION, "action": self.action}
173
175
  if self.params is not None:
174
176
  d["params"] = self.params
175
177
  return d
@@ -218,7 +220,7 @@ class PlanBlock:
218
220
  self.goal = list(goal)
219
221
 
220
222
  def to_dict(self) -> Dict[str, Any]:
221
- return {"type": "plan", "goal": [str(g) for g in self.goal]}
223
+ return {"type": BLOCK_PLAN, "goal": [str(g) for g in self.goal]}
222
224
 
223
225
  @classmethod
224
226
  def from_dict(cls, d: Dict[str, Any]) -> "PlanBlock":
@@ -254,7 +256,7 @@ class OrderBlock:
254
256
 
255
257
  def to_dict(self) -> Dict[str, Any]:
256
258
  return {
257
- "type": "order",
259
+ "type": BLOCK_ORDER,
258
260
  "name": self.name,
259
261
  "children": [
260
262
  c.to_dict() if hasattr(c, "to_dict") else c for c in self.children
@@ -278,14 +280,17 @@ class OrderBlock:
278
280
  def block_from_dict(d: Dict[str, Any]):
279
281
  """Dispatch a raw dict to the correct Block type."""
280
282
  block_type = d.get("type")
281
- if block_type == "action":
283
+ if block_type == BLOCK_ACTION:
282
284
  return ActionBlock.from_dict(d)
283
- elif block_type == "plan":
285
+ elif block_type == BLOCK_PLAN:
284
286
  return PlanBlock.from_dict(d)
285
- elif block_type == "order":
287
+ elif block_type == BLOCK_ORDER:
286
288
  return OrderBlock.from_dict(d)
287
289
  else:
288
- raise ValueError(f"Unknown block type: {block_type!r}")
290
+ raise ValueError(
291
+ f"Unknown block type: {block_type!r}. Valid types: "
292
+ f"{BLOCK_ACTION!r}, {BLOCK_PLAN!r}, {BLOCK_ORDER!r}"
293
+ )
289
294
 
290
295
 
291
296
  @dataclass
@@ -19,17 +19,25 @@ No ROS or backend dependency.
19
19
 
20
20
  from __future__ import annotations
21
21
 
22
- import os
23
22
  import sys
24
- from pathlib import Path
25
23
  from typing import Any, Dict, List, Optional, Union
26
24
  from urllib.parse import urlsplit
27
25
 
28
26
  import requests
29
27
 
30
28
  from dynos_core.atom import GroundAtom
29
+ from dynos_core.config import declare
31
30
  from dynos_core.transition import PrimitiveAction
32
31
 
32
+ _ALLOW_HTTP = declare(
33
+ "security.allow_http", bool, False, env="DYNOS_ALLOW_HTTP",
34
+ doc="allow non-loopback http:// base URLs (bearer token would transit "
35
+ "cleartext); prefer https://",
36
+ )
37
+
38
+ from dynos_client._config import config_path
39
+ from dynos_client._http_errors import resp_detail
40
+
33
41
 
34
42
  NEAR_EXPIRY_THRESHOLD_S = 3600
35
43
 
@@ -73,7 +81,7 @@ def _validate_base_url(base_url: str) -> str:
73
81
  f"RemoteOrchestrator base_url must include a host: {base_url!r}"
74
82
  )
75
83
  if parts.scheme == "http":
76
- if not _is_loopback(parts.hostname) and os.environ.get("DYNOS_ALLOW_HTTP") != "1":
84
+ if not _is_loopback(parts.hostname) and not _ALLOW_HTTP.get():
77
85
  raise ValueError(
78
86
  f"RemoteOrchestrator refuses non-loopback http:// URLs "
79
87
  f"(bearer token would transit cleartext over the network). "
@@ -83,23 +91,6 @@ def _validate_base_url(base_url: str) -> str:
83
91
  return base_url.rstrip("/")
84
92
 
85
93
 
86
- def _resp_detail(resp: "requests.Response") -> str:
87
- """Best-effort short detail string from an error response.
88
-
89
- Tries the JSON ``detail`` field (FastAPI's convention), falls back to
90
- the body text. Truncated to keep error messages short.
91
- """
92
- try:
93
- body = resp.json()
94
- if isinstance(body, dict):
95
- d = body.get("detail")
96
- if isinstance(d, str):
97
- return d
98
- return str(body)[:200]
99
- except (ValueError, TypeError):
100
- return resp.text[:200] if resp.text else f"HTTP {resp.status_code}"
101
-
102
-
103
94
  class RemoteAuthExpired(RuntimeError):
104
95
  """Raised when the backend rejects a token with HTTP 401.
105
96
 
@@ -191,7 +182,7 @@ class RemoteOrchestrator:
191
182
  token is non-fatal; the returned orchestrator runs in direct mode,
192
183
  matching what the user gets today.
193
184
  """
194
- path = Path(os.environ.get("DYNOS_CONFIG_PATH", str(Path.home() / ".dynos" / "config.json")))
185
+ path = config_path()
195
186
  if not path.exists():
196
187
  raise RuntimeError(
197
188
  f"No dynos config at {path}. Run `dynos login --to <url>` first."
@@ -247,7 +238,7 @@ class RemoteOrchestrator:
247
238
  )
248
239
  if resp.status_code == 403:
249
240
  # Could be session-cap, role gate, or ownership.
250
- detail = _resp_detail(resp)
241
+ detail = resp_detail(resp)
251
242
  raise RuntimeError(
252
243
  f"Gateway at {url} rejected the session-create request with "
253
244
  f"403 Forbidden ({detail}). This usually means you've hit "
@@ -256,7 +247,7 @@ class RemoteOrchestrator:
256
247
  if resp.status_code >= 500:
257
248
  raise RuntimeError(
258
249
  f"Gateway at {url} returned {resp.status_code} on "
259
- f"session-create. Server-side error: {_resp_detail(resp)[:200]}"
250
+ f"session-create. Server-side error: {resp_detail(resp)[:200]}"
260
251
  )
261
252
  resp.raise_for_status()
262
253
  data = resp.json()
@@ -346,7 +337,7 @@ class RemoteOrchestrator:
346
337
  # raise an HTTPError carrying only the status reason line
347
338
  # ("Internal Server Error"), discarding the actionable message
348
339
  # the server actually sent.
349
- raise RemoteRequestError(r.status_code, _resp_detail(r), path)
340
+ raise RemoteRequestError(r.status_code, resp_detail(r), path)
350
341
  return r
351
342
 
352
343
  def _get(self, path: str, *, raw: bool = False) -> Any:
@@ -900,6 +891,12 @@ class RemoteOrchestrator:
900
891
  def reset_backend(self) -> Dict[str, Any]:
901
892
  return self._post("/reset")
902
893
 
894
+ def abort(self) -> Dict[str, Any]:
895
+ """Stop the current mission drive: preempt the running action and let the
896
+ in-flight execute return the steps so far, leaving the backend alive (unlike
897
+ reset_backend, which clears state out from under a still-running mission)."""
898
+ return self._post("/abort")
899
+
903
900
  def update_object(self, name: str, **kwargs: Any) -> Dict[str, Any]:
904
901
  return self._put(f"/objects/{name}", kwargs)
905
902
 
@@ -10,7 +10,6 @@ from __future__ import annotations
10
10
  import json
11
11
  import os
12
12
  import sys
13
- from pathlib import Path
14
13
  from typing import Any, Dict, List, Optional
15
14
  from urllib.parse import urlsplit
16
15
 
@@ -19,48 +18,23 @@ import typer
19
18
  from rich.console import Console
20
19
  from rich.table import Table, box
21
20
 
21
+ from dynos_client._config import config_path
22
+ from dynos_client._credentials import refuse_if_world_or_group_readable
23
+ from dynos_client._http_errors import resp_detail
24
+
22
25
  console = Console()
23
26
  session_app = typer.Typer(help="Manage per-user sessions on a DYNOS gateway.")
24
27
 
25
- _CACHE_ENV = "DYNOS_CONFIG_PATH"
26
-
27
-
28
28
  # ---------------- cached-config helpers ----------------
29
29
 
30
- def _cache_path() -> Path:
31
- return Path(
32
- os.environ.get(_CACHE_ENV, str(Path.home() / ".dynos" / "config.json"))
33
- )
34
-
35
-
36
- def _refuse_if_world_or_group_readable(path: Path) -> None:
37
- """Refuse to load a token from a file readable by other users.
38
-
39
- The bearer token in this file is a credential. We do not silently
40
- chmod; that's the operator's call. If the perms are wrong, exit
41
- with a clear remediation hint.
42
- """
43
- try:
44
- mode = os.stat(str(path)).st_mode & 0o777
45
- except OSError:
46
- return # vanished between caller's check and stat(); caller handles
47
- if mode & 0o077:
48
- console.print(
49
- f"[red]Refusing to read {path}: mode is {oct(mode)} "
50
- f"(group/world accessible). The token is a credential. "
51
- f"Run `chmod 600 {path}` or rotate it via `dynos login`."
52
- f"[/red]"
53
- )
54
- raise typer.Exit(1)
55
-
56
30
 
57
31
  def _read_cache() -> Dict[str, Any]:
58
- path = _cache_path()
32
+ path = config_path()
59
33
  try:
60
34
  text = path.read_text()
61
35
  except FileNotFoundError:
62
36
  return {}
63
- _refuse_if_world_or_group_readable(path)
37
+ refuse_if_world_or_group_readable(path)
64
38
  try:
65
39
  return json.loads(text)
66
40
  except json.JSONDecodeError as exc:
@@ -76,7 +50,7 @@ def _read_cache() -> Dict[str, Any]:
76
50
 
77
51
 
78
52
  def _write_cache(data: Dict[str, Any]) -> None:
79
- path = _cache_path()
53
+ path = config_path()
80
54
  path.parent.mkdir(parents=True, exist_ok=True)
81
55
  # Bearer token is in this file; do not let the umask leave it world-readable.
82
56
  # We do NOT chmod after the fact; modifying file modes silently is not
@@ -126,11 +100,9 @@ def _auth_headers(token: str) -> Dict[str, str]:
126
100
 
127
101
  def _handle_response(resp: requests.Response) -> Any:
128
102
  if resp.status_code >= 400:
129
- try:
130
- detail = resp.json().get("detail", resp.text)
131
- except Exception:
132
- detail = resp.text
133
- console.print(f"[red]Gateway error ({resp.status_code}): {detail}[/red]")
103
+ console.print(
104
+ f"[red]Gateway error ({resp.status_code}): {resp_detail(resp)}[/red]"
105
+ )
134
106
  raise typer.Exit(1)
135
107
  if resp.status_code == 204 or not resp.content:
136
108
  return None
@@ -74,7 +74,7 @@ class SessionRecord:
74
74
 
75
75
  @property
76
76
  def expires_at_epoch(self) -> float:
77
- """Derived expiry: ``last_active_at + timeout_s`` as unix seconds."""
77
+ """Expiry in unix seconds, computed as ``last_active_at + timeout_s``."""
78
78
  last = datetime.fromisoformat(self.last_active_at)
79
79
  return last.timestamp() + self.timeout_s
80
80
 
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dynos-client
3
- Version: 0.2.2
3
+ Version: 0.2.5
4
4
  Summary: Client and CLI for orchestrating DYNOS backends remotely
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.8
7
7
  Description-Content-Type: text/markdown
8
- Requires-Dist: dynos-core>=0.2.2
8
+ Requires-Dist: dynos-core>=0.2.5
9
9
  Requires-Dist: requests
10
10
  Requires-Dist: typer
11
11
  Requires-Dist: bcrypt>=4.0
@@ -2,6 +2,9 @@ README.md
2
2
  pyproject.toml
3
3
  src/dynos_client/__init__.py
4
4
  src/dynos_client/__main__.py
5
+ src/dynos_client/_config.py
6
+ src/dynos_client/_credentials.py
7
+ src/dynos_client/_http_errors.py
5
8
  src/dynos_client/action.py
6
9
  src/dynos_client/action_context.py
7
10
  src/dynos_client/auth_cli.py
@@ -1,4 +1,4 @@
1
- dynos-core>=0.2.2
1
+ dynos-core>=0.2.5
2
2
  requests
3
3
  typer
4
4
  bcrypt>=4.0
File without changes
File without changes