armnet-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. armnet_client-0.1.0/.gitignore +217 -0
  2. armnet_client-0.1.0/PKG-INFO +59 -0
  3. armnet_client-0.1.0/README.md +35 -0
  4. armnet_client-0.1.0/pyproject.toml +60 -0
  5. armnet_client-0.1.0/src/armnet_client/__init__.py +85 -0
  6. armnet_client-0.1.0/src/armnet_client/_config.py +41 -0
  7. armnet_client-0.1.0/src/armnet_client/_credential_cache.py +94 -0
  8. armnet_client-0.1.0/src/armnet_client/cli.py +236 -0
  9. armnet_client-0.1.0/src/armnet_client/client.py +237 -0
  10. armnet_client-0.1.0/src/armnet_client/execute.py +300 -0
  11. armnet_client-0.1.0/src/armnet_client/groot_eval.py +186 -0
  12. armnet_client-0.1.0/src/armnet_client/image.py +449 -0
  13. armnet_client-0.1.0/src/armnet_client/lerobot_eval.py +186 -0
  14. armnet_client-0.1.0/src/armnet_client/lerobot_record.py +286 -0
  15. armnet_client-0.1.0/src/armnet_client/lerobot_teleop.py +234 -0
  16. armnet_client-0.1.0/src/armnet_client/lerobot_train.py +375 -0
  17. armnet_client-0.1.0/src/armnet_client/local.py +171 -0
  18. armnet_client-0.1.0/src/armnet_client/local_container.py +659 -0
  19. armnet_client-0.1.0/src/armnet_client/openpi_eval.py +217 -0
  20. armnet_client-0.1.0/src/armnet_client/policy_eval.py +143 -0
  21. armnet_client-0.1.0/src/armnet_client/rerun_stream.py +207 -0
  22. armnet_client-0.1.0/src/armnet_client/runtime_groot_eval/Dockerfile +57 -0
  23. armnet_client-0.1.0/src/armnet_client/runtime_groot_eval/groot_eval_runtime.py +855 -0
  24. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_eval/Dockerfile +58 -0
  25. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_eval/diffusion_resolution_patch.py +126 -0
  26. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_eval/install_molmoact2_plugin.py +287 -0
  27. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_eval/lerobot_eval_runtime.py +608 -0
  28. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_record/Dockerfile +31 -0
  29. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_record/lerobot_record_runtime.py +632 -0
  30. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_teleop/Dockerfile +31 -0
  31. armnet_client-0.1.0/src/armnet_client/runtime_lerobot_teleop/lerobot_teleop_runtime.py +206 -0
  32. armnet_client-0.1.0/src/armnet_client/runtime_openpi_eval/Dockerfile +73 -0
  33. armnet_client-0.1.0/src/armnet_client/runtime_openpi_eval/openpi_eval_runtime.py +714 -0
  34. armnet_client-0.1.0/src/armnet_client/teleop_stream.py +363 -0
  35. armnet_client-0.1.0/src/armnet_client/volume.py +197 -0
  36. armnet_client-0.1.0/tests/test_bimanual_lerobot.py +353 -0
  37. armnet_client-0.1.0/tests/test_cli_jobs.py +109 -0
  38. armnet_client-0.1.0/tests/test_execute_queue.py +62 -0
  39. armnet_client-0.1.0/tests/test_groot_eval.py +167 -0
  40. armnet_client-0.1.0/tests/test_policy_eval.py +118 -0
  41. armnet_client-0.1.0/tests/test_wait_interrupt_stop.py +31 -0
@@ -0,0 +1,217 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .nox/
42
+ .coverage
43
+ .coverage.*
44
+ .cache
45
+ nosetests.xml
46
+ coverage.xml
47
+ *.cover
48
+ *.py,cover
49
+ .hypothesis/
50
+ .pytest_cache/
51
+ cover/
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+ db.sqlite3-journal
62
+
63
+ # Flask stuff:
64
+ .webassets-cache
65
+
66
+ # Scrapy stuff:
67
+ .scrapy
68
+
69
+ # Sphinx documentation
70
+ docs/_build/
71
+
72
+ # PyBuilder
73
+ .pybuilder/
74
+ target/
75
+
76
+ # Jupyter Notebook
77
+ .ipynb_checkpoints
78
+
79
+ # IPython
80
+ profile_default/
81
+ ipython_config.py
82
+
83
+ # pyenv
84
+ # For a library or package, you might want to ignore these files since the code is
85
+ # intended to run in multiple environments; otherwise, check them in:
86
+ # .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # poetry
96
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
97
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
98
+ # commonly ignored for libraries.
99
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
100
+ #poetry.lock
101
+
102
+ # pdm
103
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
104
+ #pdm.lock
105
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
106
+ # in version control.
107
+ # https://pdm.fming.dev/#use-with-ide
108
+ .pdm.toml
109
+
110
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
111
+ __pypackages__/
112
+
113
+ # Celery stuff
114
+ celerybeat-schedule
115
+ celerybeat.pid
116
+
117
+ # SageMath parsed files
118
+ *.sage.py
119
+
120
+ # Environments
121
+ .env
122
+ .venv
123
+ venv/
124
+ ENV/
125
+ env.bak/
126
+ venv.bak/
127
+
128
+ # Spyder project settings
129
+ .spyderproject
130
+ .spyproject
131
+
132
+ # Rope project settings
133
+ .ropeproject
134
+
135
+ # mkdocs documentation
136
+ /site
137
+ armnet/site/
138
+
139
+ # mypy
140
+ .mypy_cache/
141
+ .dmypy.json
142
+ dmypy.json
143
+
144
+ # Pyre type checker
145
+ .pyre/
146
+
147
+ # pytype static type analyzer
148
+ .pytype/
149
+
150
+ # Cython debug symbols
151
+ cython_debug/
152
+
153
+ # PyCharm
154
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
155
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
156
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
157
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
158
+ #.idea/
159
+ .vscode
160
+ .DS_Store
161
+ .cursor/debug.log
162
+ .idea
163
+
164
+ # robot data and assets
165
+ data/
166
+ datadump
167
+ checkpoints_act
168
+ wandb
169
+
170
+
171
+ # model checkpoints
172
+
173
+ # ROS and real robots
174
+ logfile.asc
175
+ armnet/robot_cell.json
176
+
177
+ # cpp
178
+ devel
179
+
180
+ Log/
181
+ annotations
182
+ unsloth_compiled_cache/
183
+ node_modules
184
+
185
+ # Terraform
186
+ .terraform/
187
+ .terraform.lock.hcl
188
+ terraform.tfstate
189
+ terraform.tfstate.backup
190
+
191
+ # experimental
192
+ experimental/*/images/*.png
193
+ *.p12
194
+ build_log.txt
195
+ outputs
196
+ **/.gradio/
197
+
198
+ # outputs
199
+ **/*.mp4
200
+ **/*.parquet
201
+ activation_cache/
202
+ sae_checkpoints/
203
+ sae_dataset_on_the_fly/
204
+ safety_violation_analysis/
205
+ **/feature_analysis_results/
206
+ datasets/
207
+
208
+ missiontracker/examples/models/*openpi*
209
+ missiontracker/examples/models/fiper_models
210
+ pilot_checkpoints
211
+ checkpoints/
212
+ assets/*pi0*
213
+ # Apptainer/Singularity images (built locally, multi-GB)
214
+ *.sif
215
+
216
+ # Git worktrees
217
+ .worktrees/
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: armnet-client
3
+ Version: 0.1.0
4
+ Summary: armnet client SDK — submit jobs to the platform from dev machines and CI.
5
+ Project-URL: Homepage, https://armnet.dev
6
+ Project-URL: Documentation, https://safe-robotics.github.io/alpha-robotics/packages/client/
7
+ Author: Ville Kuosmanen
8
+ License: Apache-2.0
9
+ Requires-Python: <3.13,>=3.12
10
+ Requires-Dist: armnet-core>=0.1.0
11
+ Requires-Dist: armnet-runtime>=0.1.0
12
+ Requires-Dist: httpx<1,>=0.27
13
+ Requires-Dist: pydantic<3,>=2.6
14
+ Requires-Dist: pynput<2,>=1.8
15
+ Requires-Dist: python-dotenv<2,>=1.0
16
+ Requires-Dist: websocket-client<2,>=1.8
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == 'dev'
19
+ Provides-Extra: teleop
20
+ Requires-Dist: lerobot[feetech,smolvla]==0.5.1; extra == 'teleop'
21
+ Provides-Extra: viz
22
+ Requires-Dist: rerun-sdk<1,>=0.20; extra == 'viz'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # armnet-client
26
+
27
+ The job-submission SDK for the [Armnet](https://armnet.dev) managed arm farm.
28
+ Install it on a developer machine, a CI runner, or any service that submits jobs
29
+ to the platform — it builds and pushes container images, submits jobs, streams
30
+ logs, and manages secrets and volumes. (Code that runs *inside* your container
31
+ uses [`armnet-runtime`](https://pypi.org/project/armnet-runtime/) instead.)
32
+
33
+ ```python
34
+ from armnet_client import Image, execute
35
+
36
+ image = Image.build(dockerfile="Dockerfile", context_dir=".", name="my-runner").push()
37
+
38
+ result = execute(
39
+ image=image,
40
+ embodiment="lerobot/so-101",
41
+ task="assemble_block_tower",
42
+ args={"seed": 0, "n_episodes": 20},
43
+ timeout_seconds=600,
44
+ )
45
+ print(result.return_value)
46
+ ```
47
+
48
+ It also installs the `armnet` CLI (identity, secrets, volumes) plus policy
49
+ evaluation, teleoperation, and dataset-recording commands.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install armnet-client
55
+ ```
56
+
57
+ ## Documentation
58
+
59
+ Full guides and API reference: **<https://safe-robotics.github.io/alpha-robotics/packages/client/>**
@@ -0,0 +1,35 @@
1
+ # armnet-client
2
+
3
+ The job-submission SDK for the [Armnet](https://armnet.dev) managed arm farm.
4
+ Install it on a developer machine, a CI runner, or any service that submits jobs
5
+ to the platform — it builds and pushes container images, submits jobs, streams
6
+ logs, and manages secrets and volumes. (Code that runs *inside* your container
7
+ uses [`armnet-runtime`](https://pypi.org/project/armnet-runtime/) instead.)
8
+
9
+ ```python
10
+ from armnet_client import Image, execute
11
+
12
+ image = Image.build(dockerfile="Dockerfile", context_dir=".", name="my-runner").push()
13
+
14
+ result = execute(
15
+ image=image,
16
+ embodiment="lerobot/so-101",
17
+ task="assemble_block_tower",
18
+ args={"seed": 0, "n_episodes": 20},
19
+ timeout_seconds=600,
20
+ )
21
+ print(result.return_value)
22
+ ```
23
+
24
+ It also installs the `armnet` CLI (identity, secrets, volumes) plus policy
25
+ evaluation, teleoperation, and dataset-recording commands.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install armnet-client
31
+ ```
32
+
33
+ ## Documentation
34
+
35
+ Full guides and API reference: **<https://safe-robotics.github.io/alpha-robotics/packages/client/>**
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "armnet-client"
7
+ version = "0.1.0"
8
+ description = "armnet client SDK \u2014 submit jobs to the platform from dev machines and CI."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12,<3.13"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Ville Kuosmanen" }]
13
+
14
+ dependencies = [
15
+ "armnet-core>=0.1.0",
16
+ "armnet-runtime>=0.1.0",
17
+ "pydantic>=2.6,<3",
18
+ "httpx>=0.27,<1",
19
+ "websocket-client>=1.8,<2",
20
+ "python-dotenv>=1.0,<2",
21
+ "pynput>=1.8,<2",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://armnet.dev"
26
+ Documentation = "https://safe-robotics.github.io/alpha-robotics/packages/client/"
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "pytest>=8",
31
+ ]
32
+ # Live visualization: replays a job's ctx.log_rerun_data(...) stream into a
33
+ # Rerun viewer (execute(..., use_rerun=True) / init_rerun()).
34
+ viz = [
35
+ "rerun-sdk>=0.20,<1",
36
+ ]
37
+ # Remote teleoperation: drive a remote cell's robot from a locally-attached
38
+ # LeRobot leader arm (stream_job_teleop / TeleoperatorConfig).
39
+ teleop = [
40
+ # smolvla extra pulls num2words + transformers (needed to load/eval SmolVLA policies);
41
+ # feetech provides the Feetech motor bus driver for teleop/record.
42
+ "lerobot[feetech,smolvla]==0.5.1",
43
+ ]
44
+
45
+ [project.scripts]
46
+ armnet = "armnet_client.cli:main"
47
+ armnet-lerobot-eval = "armnet_client.lerobot_eval:main"
48
+ armnet-policy-eval = "armnet_client.policy_eval:main"
49
+ armnet-lerobot-record = "armnet_client.lerobot_record:main"
50
+ armnet-lerobot-teleop = "armnet_client.lerobot_teleop:main"
51
+ armnet-lerobot-train = "armnet_client.lerobot_train:main"
52
+ armnet-openpi-eval = "armnet_client.openpi_eval:main"
53
+
54
+ [tool.uv.sources]
55
+ armnet-core = { workspace = true }
56
+ armnet-runtime = { workspace = true }
57
+
58
+ [tool.hatch.build.targets.wheel]
59
+ packages = ["src/armnet_client"]
60
+ force-include = { "src/armnet_client/runtime_lerobot_eval/Dockerfile" = "armnet_client/runtime_lerobot_eval/Dockerfile", "src/armnet_client/runtime_lerobot_record/Dockerfile" = "armnet_client/runtime_lerobot_record/Dockerfile", "src/armnet_client/runtime_lerobot_teleop/Dockerfile" = "armnet_client/runtime_lerobot_teleop/Dockerfile", "src/armnet_client/runtime_openpi_eval/Dockerfile" = "armnet_client/runtime_openpi_eval/Dockerfile", "src/armnet_client/runtime_groot_eval/Dockerfile" = "armnet_client/runtime_groot_eval/Dockerfile" }
@@ -0,0 +1,85 @@
1
+ """armnet client SDK \u2014 submit jobs to the platform.
2
+
3
+ Top-level surface:
4
+
5
+ - :func:`execute` \u2014 submit one job, block until done.
6
+ - :func:`execute_many` \u2014 submit many in parallel, stream results.
7
+ - :func:`execute_local` \u2014 run a `@main` script in the current Python
8
+ process; bypasses Docker, NATS, and the orchestrator.
9
+ - :class:`Image` \u2014 build a Docker image with content-hash caching.
10
+ - :class:`OrchestratorClient` \u2014 lower-level HTTP wrapper.
11
+
12
+ Wire types are re-exported from :mod:`armnet_core` for ergonomics.
13
+ """
14
+
15
+ from armnet_core import (
16
+ CellRuntimeStatus,
17
+ CellStatus,
18
+ CellStatusSummary,
19
+ Embodiment,
20
+ Job,
21
+ JobResult,
22
+ JobSpec,
23
+ JobStatus,
24
+ RegistryCredentials,
25
+ RemoteExecutionError,
26
+ SecretCreateRequest,
27
+ SecretInfo,
28
+ SecretList,
29
+ Task,
30
+ TerminalStatus,
31
+ WhoAmI,
32
+ )
33
+
34
+ from armnet_client.client import OrchestratorClient, OrchestratorError
35
+ from armnet_client.execute import execute, execute_many
36
+ from armnet_client.image import (
37
+ Image,
38
+ ImageBuildError,
39
+ ImagePushError,
40
+ RegistryCredentialsUnavailableError,
41
+ )
42
+ from armnet_client.local import execute_local
43
+ from armnet_client.local_container import LocalContext, execute_local_container
44
+ from armnet_client.rerun_stream import init_rerun
45
+ from armnet_client.teleop_stream import (
46
+ TeleoperatorConfig,
47
+ start_recording_key_listener,
48
+ stream_job_teleop,
49
+ )
50
+
51
+ __all__ = [
52
+ "Embodiment",
53
+ "CellRuntimeStatus",
54
+ "CellStatus",
55
+ "CellStatusSummary",
56
+ "Image",
57
+ "ImageBuildError",
58
+ "ImagePushError",
59
+ "Job",
60
+ "JobResult",
61
+ "JobSpec",
62
+ "JobStatus",
63
+ "LocalContext",
64
+ "OrchestratorClient",
65
+ "OrchestratorError",
66
+ "RegistryCredentials",
67
+ "RegistryCredentialsUnavailableError",
68
+ "RemoteExecutionError",
69
+ "SecretCreateRequest",
70
+ "SecretInfo",
71
+ "SecretList",
72
+ "Task",
73
+ "TeleoperatorConfig",
74
+ "TerminalStatus",
75
+ "WhoAmI",
76
+ "execute",
77
+ "execute_local",
78
+ "execute_local_container",
79
+ "execute_many",
80
+ "init_rerun",
81
+ "start_recording_key_listener",
82
+ "stream_job_teleop",
83
+ ]
84
+
85
+ __version__ = "0.1.0"
@@ -0,0 +1,41 @@
1
+ """SDK configuration.
2
+
3
+ The orchestrator URL the client SDK targets is hard-coded into the SDK
4
+ build; customers do not pass it explicitly. A single env-var override is
5
+ provided for development and CI.
6
+
7
+ For the SDK as it lives in this repo (M0.5 / pre-release) the default
8
+ points at ``http://localhost:8000`` so that example scripts work
9
+ out-of-the-box when paired with a locally-running orchestrator. When we
10
+ publish to PyPI we'll replace the constant with the real Cloud Run URL
11
+ (or, more likely, inject it at build time).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+
18
+ from armnet_core import API_KEY_ENV
19
+
20
+ # TODO(armnet M1+): replace with the real orchestrator URL before
21
+ # publishing the SDK to PyPI. Consider sourcing from a build-time constant
22
+ # baked in by hatch (env var read at build, written into a generated
23
+ # module).
24
+ DEFAULT_ORCHESTRATOR_URL = "https://armnet-orchestrator-240868335442.europe-west2.run.app"
25
+
26
+ DEBUG_OVERRIDE_ENV = "DEBUG_ARMNET_ORCHESTRATOR_URI"
27
+
28
+
29
+ def orchestrator_url() -> str:
30
+ """Resolve the orchestrator base URL.
31
+
32
+ Returns the env-var override if set, otherwise the SDK default.
33
+ """
34
+
35
+ return os.environ.get(DEBUG_OVERRIDE_ENV) or DEFAULT_ORCHESTRATOR_URL
36
+
37
+
38
+ def api_key() -> str | None:
39
+ """Resolve the API key used for authenticated orchestrator requests."""
40
+
41
+ return os.environ.get(API_KEY_ENV)
@@ -0,0 +1,94 @@
1
+ """On-disk cache for image-registry credentials.
2
+
3
+ The orchestrator mints OAuth2 access tokens that are valid for ~1 hour.
4
+ Re-fetching one on every ``Image.push()`` call would be wasteful (extra
5
+ round-trip; rate limits when iterating quickly). This module caches the
6
+ last fetched :class:`RegistryCredentials` at
7
+ ``~/.cache/remoterobo/registry-credentials.json`` (or
8
+ ``$XDG_CACHE_HOME/armnet/...``) with mode 0600 since the token is
9
+ sensitive.
10
+
11
+ Keep the cache simple and process-safe-by-pessimism: every reader
12
+ re-validates expiry, so the worst race (two writers clobbering each
13
+ other) just means an extra fetch.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ from datetime import datetime, timedelta, timezone
21
+ from pathlib import Path
22
+ from typing import Optional
23
+
24
+ from armnet_core import RegistryCredentials
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ # Refresh credentials when this close to expiring.
29
+ _REFRESH_MARGIN = timedelta(minutes=5)
30
+
31
+
32
+ def _cache_dir() -> Path:
33
+ base = os.environ.get("XDG_CACHE_HOME")
34
+ return Path(base) / "armnet" if base else Path.home() / ".cache" / "armnet"
35
+
36
+
37
+ def _cache_path() -> Path:
38
+ return _cache_dir() / "registry-credentials.json"
39
+
40
+
41
+ def load() -> Optional[RegistryCredentials]:
42
+ """Return the cached credentials, or ``None`` if missing / malformed /
43
+ expiring within :data:`_REFRESH_MARGIN`.
44
+
45
+ Never raises \u2014 a corrupt cache file is treated as a cache miss.
46
+ """
47
+
48
+ path = _cache_path()
49
+ if not path.exists():
50
+ return None
51
+
52
+ try:
53
+ creds = RegistryCredentials.model_validate_json(path.read_text())
54
+ except Exception as exc: # noqa: BLE001
55
+ logger.debug("ignoring malformed credential cache at %s: %s", path, exc)
56
+ return None
57
+
58
+ expires_at = creds.expires_at
59
+ if expires_at.tzinfo is None:
60
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
61
+ if expires_at - datetime.now(timezone.utc) < _REFRESH_MARGIN:
62
+ return None
63
+
64
+ return creds
65
+
66
+
67
+ def save(creds: RegistryCredentials) -> None:
68
+ """Persist ``creds`` to the cache file with 0600 permissions.
69
+
70
+ Best-effort \u2014 on systems where ``chmod`` doesn't apply (Windows) the
71
+ permission step is silently skipped. We write to a temp file in the
72
+ same directory and rename so partial writes can't corrupt the cache.
73
+ """
74
+
75
+ path = _cache_path()
76
+ path.parent.mkdir(parents=True, exist_ok=True)
77
+
78
+ tmp = path.with_suffix(path.suffix + ".tmp")
79
+ tmp.write_text(creds.model_dump_json())
80
+ try:
81
+ tmp.chmod(0o600)
82
+ except OSError:
83
+ pass
84
+ tmp.replace(path)
85
+
86
+
87
+ def clear() -> None:
88
+ """Remove the cache file. No-op if it doesn't exist."""
89
+
90
+ path = _cache_path()
91
+ try:
92
+ path.unlink()
93
+ except FileNotFoundError:
94
+ pass