mimiry 0.2.0__tar.gz → 0.2.2__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. mimiry-0.2.2/PKG-INFO +130 -0
  2. mimiry-0.2.2/README.md +109 -0
  3. {mimiry-0.2.0 → mimiry-0.2.2}/pyproject.toml +9 -3
  4. {mimiry-0.2.0 → mimiry-0.2.2}/setup.cfg +0 -0
  5. mimiry-0.2.2/src/Mimiry.egg-info/PKG-INFO +130 -0
  6. {mimiry-0.2.0/src/mimiry.egg-info → mimiry-0.2.2/src/Mimiry.egg-info}/SOURCES.txt +8 -6
  7. {mimiry-0.2.0/src/mimiry.egg-info → mimiry-0.2.2/src/Mimiry.egg-info}/dependency_links.txt +0 -0
  8. {mimiry-0.2.0/src/mimiry.egg-info → mimiry-0.2.2/src/Mimiry.egg-info}/entry_points.txt +0 -0
  9. {mimiry-0.2.0/src/mimiry.egg-info → mimiry-0.2.2/src/Mimiry.egg-info}/requires.txt +0 -0
  10. {mimiry-0.2.0/src/mimiry.egg-info → mimiry-0.2.2/src/Mimiry.egg-info}/top_level.txt +0 -0
  11. mimiry-0.2.2/src/mimiry/_config.py +177 -0
  12. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_setup.py +19 -16
  13. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_ssh.py +2 -2
  14. mimiry-0.2.2/tests/test_config.py +105 -0
  15. mimiry-0.2.2/tests/test_setup.py +264 -0
  16. mimiry-0.2.0/PKG-INFO +0 -149
  17. mimiry-0.2.0/README.md +0 -131
  18. mimiry-0.2.0/src/mimiry/_config.py +0 -58
  19. mimiry-0.2.0/src/mimiry.egg-info/PKG-INFO +0 -149
  20. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/__init__.py +0 -0
  21. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/__main__.py +0 -0
  22. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_auth.py +0 -0
  23. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_cli.py +0 -0
  24. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_client.py +0 -0
  25. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_serialization.py +0 -0
  26. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/_session.py +0 -0
  27. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/exceptions.py +0 -0
  28. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/function.py +0 -0
  29. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/image.py +0 -0
  30. {mimiry-0.2.0 → mimiry-0.2.2}/src/mimiry/run.py +0 -0
mimiry-0.2.2/PKG-INFO ADDED
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: Mimiry
3
+ Version: 0.2.2
4
+ Summary: Python SDK for serverless compute
5
+ Author-email: Oliver <oliversorensen39@gmail.com>
6
+ License: Proprietary
7
+ Project-URL: Homepage, https://mimiry.com
8
+ Project-URL: Repository, https://github.com/OTSorensen/mimiry-python-sdk
9
+ Project-URL: Issues, https://github.com/OTSorensen/mimiry-python-sdk/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: cloudpickle>=3.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Requires-Dist: ruff>=0.5; extra == "dev"
21
+
22
+ # mimiry — Python SDK for Mimiry GPU compute
23
+
24
+ **Status:** alpha — early access
25
+ **Backend:** softlaunch.mimiry.com (beta)
26
+
27
+ Python-native interface for running serverless cloud GPU jobs on Mimiry, with full control over locality and providers.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install mimiry
33
+ ```
34
+
35
+ Or, for local development from a clone of this repo (editable install):
36
+
37
+ ```bash
38
+ pip install -e .
39
+ ```
40
+
41
+ ## Auth
42
+
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
+
45
+ ```bash
46
+ mimiry setup # alias: mimiry init
47
+ ```
48
+
49
+ This is a one-time step — you're set going forward.
50
+
51
+ To configure auth manually instead, point the SDK at your private key:
52
+
53
+ ```bash
54
+ export MIMIRY_SSH_KEY=~/.ssh/mimiry
55
+ ```
56
+
57
+ Or pass `ssh_key_path=` explicitly to `mimiry.configure()`.
58
+
59
+ ## GPU types and providers
60
+
61
+ Mimiry sources GPUs from both local datacenters and cloud providers across Europe and the US, spanning entry-level cards up to the latest high-end accelerators. You control locality and hardware requirements, as well as which providers to use.
62
+
63
+ Always check what's currently available before selecting hardware:
64
+
65
+ ```bash
66
+ mimiry availability
67
+ ```
68
+
69
+ To filter to a single GPU family, add `--gpu-family <FAMILY>`.
70
+
71
+ ## Python version
72
+
73
+ Your local Python `major.minor` must match the Python inside your container
74
+ image. The SDK ships your function to the GPU with `cloudpickle`, which can't
75
+ move code objects across Python versions — e.g. a function pickled on 3.12
76
+ won't load on 3.10.
77
+
78
+ You don't need to think about this with the default image: it ships Python
79
+ 3.12, matching recent Ubuntu / Debian / Fedora. It only matters if you set
80
+ `image=` yourself — pick one whose `python3` matches your local interpreter.
81
+ Confirm with `python3 --version` locally and inside the image; a mismatch
82
+ shows up as a failure to deserialize your function.
83
+
84
+ ## Quickstart — one-shot function
85
+
86
+ ```python
87
+ import mimiry
88
+
89
+ @mimiry.function(
90
+ # Uses default hardware; run `mimiry availability` to choose a GPU/provider.
91
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
92
+ )
93
+ def gpu_info():
94
+ import subprocess
95
+ return subprocess.check_output(
96
+ ["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv"],
97
+ text=True,
98
+ )
99
+
100
+ print(gpu_info.remote())
101
+ ```
102
+
103
+ ## Quickstart — raw bash command
104
+
105
+ ```python
106
+ import mimiry
107
+
108
+ result = mimiry.run(
109
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
110
+ command="nvidia-smi",
111
+ )
112
+ print(result.logs)
113
+ ```
114
+
115
+ ## What works in this version
116
+
117
+ - `@mimiry.function(gpu=..., image=...)` decorator
118
+ - `.remote(*args, **kwargs)` — sync call, returns the function's return value
119
+ - `.map(iterable)` — runs the function over an iterable, sequentially
120
+ - `Image.from_registry(uri).pip_install(...).apt_install(...)` — basic image customisation (installs at container start; no real Dockerfile build)
121
+ - `mimiry.run(image, gpu, command)` — raw bash entrypoint
122
+ - SSH-JWT auth via existing key
123
+
124
+ ## Examples
125
+
126
+ See `examples/`:
127
+
128
+ - `01_hello.py` — minimal `nvidia-smi` on a GPU
129
+ - `02_cuda_probe.py` — probe the GPU (driver, CUDA, device count) and return a structured Python dict
130
+ - `03_bash_command.py` — run an arbitrary shell command with `mimiry.run()`
mimiry-0.2.2/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # mimiry — Python SDK for Mimiry GPU compute
2
+
3
+ **Status:** alpha — early access
4
+ **Backend:** softlaunch.mimiry.com (beta)
5
+
6
+ Python-native interface for running serverless cloud GPU jobs on Mimiry, with full control over locality and providers.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install mimiry
12
+ ```
13
+
14
+ Or, for local development from a clone of this repo (editable install):
15
+
16
+ ```bash
17
+ pip install -e .
18
+ ```
19
+
20
+ ## Auth
21
+
22
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
23
+
24
+ ```bash
25
+ mimiry setup # alias: mimiry init
26
+ ```
27
+
28
+ This is a one-time step — you're set going forward.
29
+
30
+ To configure auth manually instead, point the SDK at your private key:
31
+
32
+ ```bash
33
+ export MIMIRY_SSH_KEY=~/.ssh/mimiry
34
+ ```
35
+
36
+ Or pass `ssh_key_path=` explicitly to `mimiry.configure()`.
37
+
38
+ ## GPU types and providers
39
+
40
+ Mimiry sources GPUs from both local datacenters and cloud providers across Europe and the US, spanning entry-level cards up to the latest high-end accelerators. You control locality and hardware requirements, as well as which providers to use.
41
+
42
+ Always check what's currently available before selecting hardware:
43
+
44
+ ```bash
45
+ mimiry availability
46
+ ```
47
+
48
+ To filter to a single GPU family, add `--gpu-family <FAMILY>`.
49
+
50
+ ## Python version
51
+
52
+ Your local Python `major.minor` must match the Python inside your container
53
+ image. The SDK ships your function to the GPU with `cloudpickle`, which can't
54
+ move code objects across Python versions — e.g. a function pickled on 3.12
55
+ won't load on 3.10.
56
+
57
+ You don't need to think about this with the default image: it ships Python
58
+ 3.12, matching recent Ubuntu / Debian / Fedora. It only matters if you set
59
+ `image=` yourself — pick one whose `python3` matches your local interpreter.
60
+ Confirm with `python3 --version` locally and inside the image; a mismatch
61
+ shows up as a failure to deserialize your function.
62
+
63
+ ## Quickstart — one-shot function
64
+
65
+ ```python
66
+ import mimiry
67
+
68
+ @mimiry.function(
69
+ # Uses default hardware; run `mimiry availability` to choose a GPU/provider.
70
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
71
+ )
72
+ def gpu_info():
73
+ import subprocess
74
+ return subprocess.check_output(
75
+ ["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv"],
76
+ text=True,
77
+ )
78
+
79
+ print(gpu_info.remote())
80
+ ```
81
+
82
+ ## Quickstart — raw bash command
83
+
84
+ ```python
85
+ import mimiry
86
+
87
+ result = mimiry.run(
88
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
89
+ command="nvidia-smi",
90
+ )
91
+ print(result.logs)
92
+ ```
93
+
94
+ ## What works in this version
95
+
96
+ - `@mimiry.function(gpu=..., image=...)` decorator
97
+ - `.remote(*args, **kwargs)` — sync call, returns the function's return value
98
+ - `.map(iterable)` — runs the function over an iterable, sequentially
99
+ - `Image.from_registry(uri).pip_install(...).apt_install(...)` — basic image customisation (installs at container start; no real Dockerfile build)
100
+ - `mimiry.run(image, gpu, command)` — raw bash entrypoint
101
+ - SSH-JWT auth via existing key
102
+
103
+ ## Examples
104
+
105
+ See `examples/`:
106
+
107
+ - `01_hello.py` — minimal `nvidia-smi` on a GPU
108
+ - `02_cuda_probe.py` — probe the GPU (driver, CUDA, device count) and return a structured Python dict
109
+ - `03_bash_command.py` — run an arbitrary shell command with `mimiry.run()`
@@ -3,9 +3,9 @@ requires = ["setuptools>=68", "wheel"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
- name = "mimiry"
7
- version = "0.2.0"
8
- description = "Python SDK for Mimiry GPU compute (softlaunch). v1 wraps the existing /api/compute/v1/sessions API."
6
+ name = "Mimiry"
7
+ version = "0.2.2"
8
+ description = "Python SDK for serverless compute"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
11
11
  license = { text = "Proprietary" }
@@ -16,6 +16,7 @@ classifiers = [
16
16
  "Programming Language :: Python :: 3.11",
17
17
  "Programming Language :: Python :: 3.12",
18
18
  ]
19
+
19
20
  dependencies = [
20
21
  "httpx>=0.27",
21
22
  "cloudpickle>=3.0",
@@ -27,6 +28,11 @@ dev = [
27
28
  "ruff>=0.5",
28
29
  ]
29
30
 
31
+ [project.urls]
32
+ Homepage = "https://mimiry.com"
33
+ Repository = "https://github.com/OTSorensen/mimiry-python-sdk"
34
+ Issues = "https://github.com/OTSorensen/mimiry-python-sdk/issues"
35
+
30
36
  [project.scripts]
31
37
  mimiry = "mimiry._cli:main"
32
38
 
File without changes
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: Mimiry
3
+ Version: 0.2.2
4
+ Summary: Python SDK for serverless compute
5
+ Author-email: Oliver <oliversorensen39@gmail.com>
6
+ License: Proprietary
7
+ Project-URL: Homepage, https://mimiry.com
8
+ Project-URL: Repository, https://github.com/OTSorensen/mimiry-python-sdk
9
+ Project-URL: Issues, https://github.com/OTSorensen/mimiry-python-sdk/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: cloudpickle>=3.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Requires-Dist: ruff>=0.5; extra == "dev"
21
+
22
+ # mimiry — Python SDK for Mimiry GPU compute
23
+
24
+ **Status:** alpha — early access
25
+ **Backend:** softlaunch.mimiry.com (beta)
26
+
27
+ Python-native interface for running serverless cloud GPU jobs on Mimiry, with full control over locality and providers.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install mimiry
33
+ ```
34
+
35
+ Or, for local development from a clone of this repo (editable install):
36
+
37
+ ```bash
38
+ pip install -e .
39
+ ```
40
+
41
+ ## Auth
42
+
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
+
45
+ ```bash
46
+ mimiry setup # alias: mimiry init
47
+ ```
48
+
49
+ This is a one-time step — you're set going forward.
50
+
51
+ To configure auth manually instead, point the SDK at your private key:
52
+
53
+ ```bash
54
+ export MIMIRY_SSH_KEY=~/.ssh/mimiry
55
+ ```
56
+
57
+ Or pass `ssh_key_path=` explicitly to `mimiry.configure()`.
58
+
59
+ ## GPU types and providers
60
+
61
+ Mimiry sources GPUs from both local datacenters and cloud providers across Europe and the US, spanning entry-level cards up to the latest high-end accelerators. You control locality and hardware requirements, as well as which providers to use.
62
+
63
+ Always check what's currently available before selecting hardware:
64
+
65
+ ```bash
66
+ mimiry availability
67
+ ```
68
+
69
+ To filter to a single GPU family, add `--gpu-family <FAMILY>`.
70
+
71
+ ## Python version
72
+
73
+ Your local Python `major.minor` must match the Python inside your container
74
+ image. The SDK ships your function to the GPU with `cloudpickle`, which can't
75
+ move code objects across Python versions — e.g. a function pickled on 3.12
76
+ won't load on 3.10.
77
+
78
+ You don't need to think about this with the default image: it ships Python
79
+ 3.12, matching recent Ubuntu / Debian / Fedora. It only matters if you set
80
+ `image=` yourself — pick one whose `python3` matches your local interpreter.
81
+ Confirm with `python3 --version` locally and inside the image; a mismatch
82
+ shows up as a failure to deserialize your function.
83
+
84
+ ## Quickstart — one-shot function
85
+
86
+ ```python
87
+ import mimiry
88
+
89
+ @mimiry.function(
90
+ # Uses default hardware; run `mimiry availability` to choose a GPU/provider.
91
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
92
+ )
93
+ def gpu_info():
94
+ import subprocess
95
+ return subprocess.check_output(
96
+ ["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv"],
97
+ text=True,
98
+ )
99
+
100
+ print(gpu_info.remote())
101
+ ```
102
+
103
+ ## Quickstart — raw bash command
104
+
105
+ ```python
106
+ import mimiry
107
+
108
+ result = mimiry.run(
109
+ image="nvcr.io/nvidia/cuda:12.6.2-runtime-ubuntu24.04",
110
+ command="nvidia-smi",
111
+ )
112
+ print(result.logs)
113
+ ```
114
+
115
+ ## What works in this version
116
+
117
+ - `@mimiry.function(gpu=..., image=...)` decorator
118
+ - `.remote(*args, **kwargs)` — sync call, returns the function's return value
119
+ - `.map(iterable)` — runs the function over an iterable, sequentially
120
+ - `Image.from_registry(uri).pip_install(...).apt_install(...)` — basic image customisation (installs at container start; no real Dockerfile build)
121
+ - `mimiry.run(image, gpu, command)` — raw bash entrypoint
122
+ - SSH-JWT auth via existing key
123
+
124
+ ## Examples
125
+
126
+ See `examples/`:
127
+
128
+ - `01_hello.py` — minimal `nvidia-smi` on a GPU
129
+ - `02_cuda_probe.py` — probe the GPU (driver, CUDA, device count) and return a structured Python dict
130
+ - `03_bash_command.py` — run an arbitrary shell command with `mimiry.run()`
@@ -1,5 +1,11 @@
1
1
  README.md
2
2
  pyproject.toml
3
+ src/Mimiry.egg-info/PKG-INFO
4
+ src/Mimiry.egg-info/SOURCES.txt
5
+ src/Mimiry.egg-info/dependency_links.txt
6
+ src/Mimiry.egg-info/entry_points.txt
7
+ src/Mimiry.egg-info/requires.txt
8
+ src/Mimiry.egg-info/top_level.txt
3
9
  src/mimiry/__init__.py
4
10
  src/mimiry/__main__.py
5
11
  src/mimiry/_auth.py
@@ -14,9 +20,5 @@ src/mimiry/exceptions.py
14
20
  src/mimiry/function.py
15
21
  src/mimiry/image.py
16
22
  src/mimiry/run.py
17
- src/mimiry.egg-info/PKG-INFO
18
- src/mimiry.egg-info/SOURCES.txt
19
- src/mimiry.egg-info/dependency_links.txt
20
- src/mimiry.egg-info/entry_points.txt
21
- src/mimiry.egg-info/requires.txt
22
- src/mimiry.egg-info/top_level.txt
23
+ tests/test_config.py
24
+ tests/test_setup.py
@@ -0,0 +1,177 @@
1
+ """Process-global SDK configuration. Holds auth + API base URL.
2
+
3
+ Key-path resolution precedence (highest first):
4
+
5
+ 1. an explicit ``mimiry.configure(ssh_key_path=...)`` call or the ``--ssh-key``
6
+ CLI flag
7
+ 2. the ``MIMIRY_SSH_KEY`` environment variable
8
+ 3. the on-disk config file written by ``mimiry setup``
9
+ (``$XDG_CONFIG_HOME/mimiry/config.toml``, default ``~/.config/mimiry/config.toml``)
10
+
11
+ The config file stores **only the path** to the SSH key — never the key
12
+ material itself, and never a token. That keeps the file low-sensitivity: the
13
+ real secret stays in ``~/.ssh/mimiry`` behind its own ``0600`` perms. We still
14
+ write the config ``0600`` and refuse to read it if it's group/other-writable,
15
+ since a writable config would be a key-redirection injection vector.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import stat
22
+ import tempfile
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ DEFAULT_API_BASE = "https://softlaunch.mimiry.com"
27
+ DEFAULT_TIMEOUT_SECONDS = 1800 # 30 min — must accommodate ~2 min cold start + work
28
+
29
+ # Group/other WRITABLE bits. We reject a config carrying these on read: an
30
+ # attacker who can write the file could repoint the SDK at a key they control.
31
+ # Readability is *not* checked — the file holds only a path, which isn't secret.
32
+ _INSECURE_WRITE_BITS = stat.S_IWGRP | stat.S_IWOTH # 0o022
33
+
34
+
35
+ @dataclass
36
+ class Config:
37
+ ssh_key_path: Path | None = None
38
+ api_base: str = DEFAULT_API_BASE
39
+ timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
40
+ poll_interval_seconds: float = 5.0
41
+ # Tighter than state polling — the marker-emission → auto_terminate window is
42
+ # only the wrapper's tail sleep (~20s), so we need ~2s cadence to catch it reliably.
43
+ log_poll_interval_seconds: float = 2.0
44
+ extras: dict = field(default_factory=dict)
45
+
46
+
47
+ _config = Config()
48
+
49
+
50
+ # ────────────────────────── on-disk config file ──────────────────────────
51
+
52
+
53
+ def config_path() -> Path:
54
+ """Path to the persisted config file (honours ``$XDG_CONFIG_HOME``)."""
55
+ base = os.environ.get("XDG_CONFIG_HOME")
56
+ root = Path(base).expanduser() if base else Path.home() / ".config"
57
+ return root / "mimiry" / "config.toml"
58
+
59
+
60
+ def save_key_path(ssh_key_path: str | Path, path: Path | None = None) -> Path:
61
+ """Persist the SSH key *path* (never key material) to a ``0600`` config file.
62
+
63
+ The write is atomic — content goes to a temp file in the same directory and
64
+ is ``os.replace``-d into place — so a crash mid-write can't leave a
65
+ truncated config behind. The containing directory is created ``0700``.
66
+ """
67
+ cfg_path = path or config_path()
68
+ cfg_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
69
+
70
+ key_str = str(Path(ssh_key_path).expanduser())
71
+ # TOML-escape backslashes/quotes (defensive — WSL paths are POSIX, but a
72
+ # Windows-style path could carry backslashes).
73
+ escaped = key_str.replace("\\", "\\\\").replace('"', '\\"')
74
+ body = (
75
+ "# Mimiry SDK config — written by `mimiry setup`.\n"
76
+ "# Holds only the path to your SSH key, never the key itself.\n"
77
+ f'ssh_key_path = "{escaped}"\n'
78
+ )
79
+
80
+ fd, tmp_name = tempfile.mkstemp(dir=str(cfg_path.parent), prefix=".config-", suffix=".tmp")
81
+ tmp = Path(tmp_name)
82
+ try:
83
+ os.fchmod(fd, 0o600)
84
+ with os.fdopen(fd, "w") as fh:
85
+ fh.write(body)
86
+ fh.flush()
87
+ os.fsync(fh.fileno())
88
+ os.replace(tmp, cfg_path) # atomic on POSIX
89
+ except BaseException:
90
+ tmp.unlink(missing_ok=True)
91
+ raise
92
+ return cfg_path
93
+
94
+
95
+ def read_key_path(path: Path | None = None) -> Path | None:
96
+ """Return the key path stored in the config file, or ``None`` if absent.
97
+
98
+ Raises ``PermissionError`` if the file is group/other-writable, since a
99
+ writable config is a key-redirection injection vector.
100
+ """
101
+ cfg_path = path or config_path()
102
+ try:
103
+ st = cfg_path.stat()
104
+ except FileNotFoundError:
105
+ return None
106
+ if st.st_mode & _INSECURE_WRITE_BITS:
107
+ raise PermissionError(
108
+ f"{cfg_path} is writable by group/other ({oct(stat.S_IMODE(st.st_mode))}); "
109
+ f"refusing to trust it. Fix with: chmod 600 {cfg_path}"
110
+ )
111
+ value = _load_toml(cfg_path.read_text()).get("ssh_key_path")
112
+ return Path(value).expanduser() if value else None
113
+
114
+
115
+ def _load_toml(text: str) -> dict:
116
+ """Parse the config file, preferring stdlib ``tomllib`` (Python 3.11+)."""
117
+ try:
118
+ import tomllib
119
+ except ModuleNotFoundError: # Python 3.10 — no stdlib TOML parser
120
+ return _parse_simple_toml(text)
121
+ return tomllib.loads(text)
122
+
123
+
124
+ def _parse_simple_toml(text: str) -> dict:
125
+ """Minimal fallback for Python 3.10: top-level ``key = "value"`` scalars only.
126
+
127
+ Sufficient for our schema (a single string key). Not a general TOML parser.
128
+ """
129
+ result: dict[str, str] = {}
130
+ for raw in text.splitlines():
131
+ line = raw.split("#", 1)[0].strip()
132
+ if not line or "=" not in line:
133
+ continue
134
+ key, _, value = line.partition("=")
135
+ value = value.strip()
136
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
137
+ value = value[1:-1].replace('\\"', '"').replace("\\\\", "\\")
138
+ result[key.strip()] = value
139
+ return result
140
+
141
+
142
+ # ────────────────────────── public configuration API ──────────────────────────
143
+
144
+
145
+ def configure(
146
+ ssh_key_path: str | Path | None = None,
147
+ api_base: str | None = None,
148
+ timeout_seconds: int | None = None,
149
+ poll_interval_seconds: float | None = None,
150
+ ) -> Config:
151
+ """Set SDK-wide configuration. Any argument left as ``None`` is unchanged."""
152
+ if ssh_key_path is not None:
153
+ _config.ssh_key_path = Path(ssh_key_path).expanduser()
154
+ if api_base is not None:
155
+ _config.api_base = api_base.rstrip("/")
156
+ if timeout_seconds is not None:
157
+ _config.timeout_seconds = timeout_seconds
158
+ if poll_interval_seconds is not None:
159
+ _config.poll_interval_seconds = poll_interval_seconds
160
+ return _config
161
+
162
+
163
+ def get_config() -> Config:
164
+ """Return the active configuration, resolving the key path on first read.
165
+
166
+ Precedence: an explicit ``configure()`` call (already on ``_config``) wins;
167
+ otherwise ``MIMIRY_SSH_KEY``; otherwise the on-disk config file.
168
+ """
169
+ if _config.ssh_key_path is None:
170
+ env_key = os.environ.get("MIMIRY_SSH_KEY")
171
+ if env_key:
172
+ _config.ssh_key_path = Path(env_key).expanduser()
173
+ else:
174
+ _config.ssh_key_path = read_key_path() # may stay None
175
+ if "MIMIRY_API_BASE" in os.environ:
176
+ _config.api_base = os.environ["MIMIRY_API_BASE"].rstrip("/")
177
+ return _config