runpodkit 0.2.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.
runpodkit/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .client import BOOTING, RunPod, RunPodError, RunPodTimeoutError, pod_state, ssh_endpoint, to_v1
6
+
7
+ __all__ = [
8
+ "RunPod", "RunPodError", "RunPodTimeoutError", "pod_state", "ssh_endpoint", "to_v1",
9
+ "BOOTING", "__version__",
10
+ ]
runpodkit/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from .cli import main
4
+
5
+
6
+ raise SystemExit(main())
runpodkit/cli.py ADDED
@@ -0,0 +1,248 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import sys
8
+ from typing import Callable, Optional
9
+
10
+ from . import RunPod, RunPodError, RunPodTimeoutError, __version__, pod_state, ssh_endpoint
11
+
12
+
13
+ def _redact(text: str) -> str:
14
+ key = os.environ.get("RUNPOD_API_KEY")
15
+ # Real keys are long; redacting a short placeholder (e.g. "k") would mangle ordinary output.
16
+ return text.replace(key, "[REDACTED]") if key and len(key) >= 8 else text
17
+
18
+
19
+ def _error(message: object) -> None:
20
+ print("runpodkit: " + " ".join(_redact(str(message)).split()), file=sys.stderr)
21
+
22
+
23
+ class _Parser(argparse.ArgumentParser):
24
+ def error(self, message: str) -> None:
25
+ _error(message)
26
+ raise SystemExit(2)
27
+
28
+
29
+ def _emit_json(obj: object, with_env: bool) -> None:
30
+ def strip_env(pod: object) -> object:
31
+ if isinstance(pod, dict) and not with_env:
32
+ return {key: value for key, value in pod.items() if key != "env"}
33
+ return pod
34
+
35
+ clean = [strip_env(pod) for pod in obj] if isinstance(obj, list) else strip_env(obj)
36
+ text = json.dumps(clean, indent=2)
37
+ key = os.environ.get("RUNPOD_API_KEY")
38
+ if key:
39
+ text = text.replace(json.dumps(key)[1:-1], "[REDACTED]")
40
+ print(text)
41
+
42
+
43
+ def _read_pod(pod_id: str) -> object:
44
+ if pod_id != "-":
45
+ return RunPod().get_pod(pod_id)
46
+ try:
47
+ return json.load(sys.stdin)
48
+ except ValueError:
49
+ return None
50
+
51
+
52
+ def _cmd_list(args: argparse.Namespace) -> int:
53
+ pods = RunPod().list_pods()
54
+ if not args.all:
55
+ pods = [pod for pod in pods if pod_state(pod) != "TERMINATED"]
56
+ _emit_json(pods, args.with_env)
57
+ return 0
58
+
59
+
60
+ def _cmd_get(args: argparse.Namespace) -> int:
61
+ pod = RunPod().get_pod(args.id)
62
+ _emit_json(pod if pod is not None else {"detail": "pod not found"}, args.with_env)
63
+ return 3 if pod is None else 0
64
+
65
+
66
+ def _cmd_state(args: argparse.Namespace) -> int:
67
+ print(pod_state(_read_pod(args.id)))
68
+ return 0
69
+
70
+
71
+ def _cmd_ssh(args: argparse.Namespace) -> int:
72
+ endpoint = ssh_endpoint(_read_pod(args.id))
73
+ if endpoint is None:
74
+ return 1
75
+ print(_redact(f"{endpoint[0]} {endpoint[1]}"))
76
+ return 0
77
+
78
+
79
+ def _cmd_wait_ssh(args: argparse.Namespace) -> int:
80
+ try:
81
+ ip, port = RunPod().wait_ssh(args.id, timeout=args.timeout)
82
+ except RunPodTimeoutError as error:
83
+ _error(error)
84
+ return 3
85
+ print(_redact(f"{ip} {port}"))
86
+ return 0
87
+
88
+
89
+ def _cmd_wait_status(args: argparse.Namespace) -> int:
90
+ try:
91
+ pod = RunPod().wait_status(args.id, args.status, timeout=args.timeout)
92
+ except RunPodTimeoutError as error:
93
+ _error(error)
94
+ return 3
95
+ _emit_json(pod, args.with_env)
96
+ return 0
97
+
98
+
99
+ def _cmd_start(args: argparse.Namespace) -> int:
100
+ _emit_json(RunPod().start(args.id), args.with_env)
101
+ return 0
102
+
103
+
104
+ def _cmd_stop(args: argparse.Namespace) -> int:
105
+ _emit_json(RunPod().stop(args.id), args.with_env)
106
+ return 0
107
+
108
+
109
+ def _cmd_restart(args: argparse.Namespace) -> int:
110
+ _emit_json(RunPod().restart(args.id), args.with_env)
111
+ return 0
112
+
113
+
114
+ def _cmd_delete(args: argparse.Namespace) -> int:
115
+ try:
116
+ status = RunPod().terminate(args.id)
117
+ except RunPodError as error:
118
+ if error.status is not None:
119
+ print(error.status)
120
+ raise
121
+ print(status)
122
+ return 0
123
+
124
+
125
+ def _cmd_create(args: argparse.Namespace) -> int:
126
+ if args.body == "-":
127
+ body = json.load(sys.stdin)
128
+ else:
129
+ with open(args.body, encoding="utf-8") as source:
130
+ body = json.load(source)
131
+ if not isinstance(body, dict):
132
+ raise ValueError("create body must be a JSON object")
133
+ _emit_json(RunPod().create(body, gpu_ids=args.gpu), args.with_env)
134
+ return 0
135
+
136
+
137
+ def _cmd_volumes(args: argparse.Namespace) -> int:
138
+ _emit_json(RunPod().network_volumes(), with_env=True)
139
+ return 0
140
+
141
+
142
+ def _cmd_bash_lib(args: argparse.Namespace) -> int:
143
+ print(Path(__file__).resolve().parent / "lib" / "runpod.sh") # a path, never a secret
144
+ return 0
145
+
146
+
147
+ def _cmd_version(args: argparse.Namespace) -> int:
148
+ print("runpodkit " + __version__)
149
+ return 0
150
+
151
+
152
+ _COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
153
+ "list": _cmd_list,
154
+ "get": _cmd_get,
155
+ "state": _cmd_state,
156
+ "ssh": _cmd_ssh,
157
+ "wait-ssh": _cmd_wait_ssh,
158
+ "wait-status": _cmd_wait_status,
159
+ "start": _cmd_start,
160
+ "stop": _cmd_stop,
161
+ "restart": _cmd_restart,
162
+ "delete": _cmd_delete,
163
+ "create": _cmd_create,
164
+ "volumes": _cmd_volumes,
165
+ "bash-lib": _cmd_bash_lib,
166
+ "version": _cmd_version,
167
+ }
168
+
169
+
170
+ def _parser() -> argparse.ArgumentParser:
171
+ parser = _Parser(
172
+ prog="runpodkit",
173
+ description=("Manage RunPod pods using RUNPOD_API_KEY and RUNPOD_API_URL. "
174
+ "Exit codes: 0 ok, 1 error, 2 usage, 3 not found / timeout."),
175
+ )
176
+ parser.add_argument("--version", action="version", version=f"runpodkit {__version__}")
177
+ commands = parser.add_subparsers(dest="command", required=True)
178
+ help_by_command = {
179
+ "list": "list pods (TERMINATED hidden unless --all)",
180
+ "get": "print pod JSON by ID",
181
+ "state": "print the pod state word; ID or - for pod JSON on stdin",
182
+ "ssh": "print the SSH host and port; ID or - for pod JSON on stdin",
183
+ "wait-ssh": "wait for a reachable SSH endpoint and print its host and port",
184
+ "wait-status": "wait for a pod status and print pod JSON",
185
+ "start": "start a pod and print pod JSON",
186
+ "stop": "stop a pod and print pod JSON",
187
+ "restart": "restart a pod and print pod JSON",
188
+ "delete": "terminate a pod and print the HTTP status",
189
+ "create": "create a pod from a JSON body and print pod JSON",
190
+ "volumes": "list network volumes as JSON",
191
+ "bash-lib": "print the path to the Bash library",
192
+ "version": "print the runpodkit version",
193
+ }
194
+ for name in _COMMANDS:
195
+ command = commands.add_parser(name, help=help_by_command[name],
196
+ description=help_by_command[name])
197
+ if name in {"get", "state", "ssh", "wait-ssh", "wait-status",
198
+ "start", "stop", "restart", "delete"}:
199
+ command.add_argument("id", help="pod ID or - for pod JSON on stdin"
200
+ if name in {"state", "ssh"} else "pod ID")
201
+ if name == "list":
202
+ command.add_argument("--all", action="store_true", help="include TERMINATED pods")
203
+ if name in {"list", "get", "wait-status", "start", "stop", "restart", "create"}:
204
+ command.add_argument("--with-env", action="store_true",
205
+ help="keep the pod env (may contain secrets)")
206
+ if name == "wait-status":
207
+ command.add_argument("status", help="target pod status (case insensitive)")
208
+ if name in {"wait-ssh", "wait-status"}:
209
+ command.add_argument("--timeout", type=float,
210
+ default=320 if name == "wait-ssh" else 240,
211
+ help="maximum wait in seconds (default: %(default)s)")
212
+ if name == "create":
213
+ command.add_argument("--body", required=True, help="JSON body file or - for stdin")
214
+ command.add_argument("--gpu", action="extend", nargs="+",
215
+ help="GPU IDs to try in order; may be repeated")
216
+ return parser
217
+
218
+
219
+ def _silence_stdout() -> None:
220
+ sink = open(os.devnull, "w", encoding="utf-8")
221
+ try:
222
+ os.dup2(sink.fileno(), sys.stdout.fileno())
223
+ except (AttributeError, OSError, ValueError):
224
+ # In-process callers may supply a stream without a file descriptor.
225
+ sys.stdout = sink
226
+ else:
227
+ sink.close()
228
+
229
+
230
+ def main(argv: Optional[list[str]] = None) -> int:
231
+ try:
232
+ try:
233
+ args = _parser().parse_args(argv)
234
+ except SystemExit as error:
235
+ if isinstance(error.code, int):
236
+ return error.code
237
+ return 0 if error.code is None else 2
238
+ code = _COMMANDS[args.command](args)
239
+ sys.stdout.flush()
240
+ return code
241
+ except BrokenPipeError:
242
+ _silence_stdout()
243
+ return 1
244
+ except KeyboardInterrupt:
245
+ return 130
246
+ except (RunPodError, ValueError, OSError) as error:
247
+ _error(error)
248
+ return 1
runpodkit/client.py ADDED
@@ -0,0 +1,422 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import http.client
5
+ import json
6
+ import os
7
+ import socket
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from typing import Iterable, Optional, Union
13
+
14
+ from . import __version__
15
+
16
+
17
+ BOOTING = frozenset({
18
+ "PROVISIONING", "CREATED", "STARTING", "RESTARTING", "INITIALIZING",
19
+ })
20
+
21
+
22
+ class RunPodError(RuntimeError):
23
+ def __init__(self, message: str, status: Optional[int] = None,
24
+ body: str = "") -> None:
25
+ super().__init__(message)
26
+ self.status = status
27
+ self.body = body[:500]
28
+
29
+
30
+ class RunPodTimeoutError(RunPodError):
31
+ """Raised by wait_status/wait_ssh when the deadline passes; status is always None."""
32
+
33
+ def __init__(self, message: str) -> None:
34
+ super().__init__(message)
35
+
36
+
37
+ def pod_state(pod: object) -> str:
38
+ if not isinstance(pod, dict):
39
+ return "NOTFOUND"
40
+ status = pod.get("status")
41
+ if not isinstance(status, str) or not status:
42
+ return "NOTFOUND"
43
+ state = status.upper()
44
+ if state == "RUNNING" and pod.get("runtime") is None:
45
+ return "STARTING"
46
+ return state
47
+
48
+
49
+ def ssh_endpoint(pod: object) -> Optional[tuple[str, int]]:
50
+ if pod_state(pod) != "RUNNING":
51
+ return None
52
+ runtime = pod.get("runtime")
53
+ if not isinstance(runtime, dict):
54
+ return None
55
+ ports = runtime.get("ports")
56
+ if not isinstance(ports, list):
57
+ return None
58
+ for port in ports:
59
+ if not isinstance(port, dict):
60
+ continue
61
+ private, public, ip = port.get("private"), port.get("public"), port.get("ip")
62
+ if (type(private) is not int or private != 22 or port.get("type") != "tcp"
63
+ or not isinstance(ip, str) or not ip):
64
+ continue
65
+ if isinstance(public, str) and public.isdecimal():
66
+ try:
67
+ public = int(public)
68
+ except ValueError:
69
+ continue
70
+ if type(public) is int and public > 0:
71
+ return ip, public
72
+ return None
73
+
74
+
75
+ def to_v1(pod: dict) -> dict:
76
+ if not isinstance(pod, dict):
77
+ raise TypeError("to_v1 requires a pod dict")
78
+ result = copy.deepcopy(pod)
79
+ state = pod_state(pod)
80
+ endpoint = ssh_endpoint(pod)
81
+ result["desiredStatus"] = "RUNNING" if state in BOOTING or state == "RUNNING" else state
82
+ result["publicIp"] = endpoint[0] if endpoint else ""
83
+ result["portMappings"] = {"22": endpoint[1]} if endpoint else {}
84
+ return result
85
+
86
+
87
+ def _error_message(method: str, path: str, status: int, body: str,
88
+ reason: object = "") -> str:
89
+ prefix = f"{method} {path} → HTTP {status}"
90
+ try:
91
+ data = json.loads(body)
92
+ except (ValueError, TypeError):
93
+ data = None
94
+ if isinstance(data, dict) and isinstance(data.get("detail"), str):
95
+ title = data.get("title")
96
+ detail = data["detail"]
97
+ if isinstance(title, str) and title:
98
+ return f"{prefix}: {title}: {detail}"
99
+ return f"{prefix}: {detail}"
100
+ detail = " ".join((body or str(reason or "")).split())[:200]
101
+ return f"{prefix}: {detail}" if detail else prefix
102
+
103
+
104
+ def _is_transient(error: RunPodError) -> bool:
105
+ return error.status is None or error.status == 429 or error.status >= 500
106
+
107
+
108
+ def _positive_seconds(value: Union[int, float], name: str) -> None:
109
+ if (isinstance(value, bool) or not isinstance(value, (int, float))
110
+ or not 0 < value < float("inf")):
111
+ raise ValueError(f"{name} must be a finite number greater than zero")
112
+
113
+
114
+ def _pod_path(pod_id: str) -> str:
115
+ if not isinstance(pod_id, str) or not pod_id:
116
+ raise ValueError("pod_id must be a non-empty str for /pods/{id}")
117
+ return "/pods/" + urllib.parse.quote(pod_id, safe="")
118
+
119
+
120
+ def _tcp_accepts(ip: str, port: int, timeout: float) -> bool:
121
+ try:
122
+ connection = socket.create_connection((ip, port), timeout=timeout)
123
+ connection.close()
124
+ except OSError:
125
+ return False
126
+ return True
127
+
128
+
129
+ class RunPod:
130
+ def __init__(self, api_key: Optional[str] = None,
131
+ base_url: Optional[str] = None, timeout: float = 30) -> None:
132
+ key = api_key if api_key is not None else os.environ.get("RUNPOD_API_KEY")
133
+ if not key:
134
+ raise RunPodError(
135
+ "RUNPOD_API_KEY is not set (pass api_key= or export RUNPOD_API_KEY)"
136
+ )
137
+ if not isinstance(key, str):
138
+ raise TypeError("api_key must be a str")
139
+ _positive_seconds(timeout, "timeout")
140
+ url = base_url if base_url is not None else os.environ.get(
141
+ "RUNPOD_API_URL", "https://api.runpod.io/v2"
142
+ )
143
+ if not isinstance(url, str) or not url.rstrip("/"):
144
+ raise ValueError("base_url must be a non-empty str")
145
+ self._api_key = key
146
+ self.base_url = url.rstrip("/")
147
+ self.timeout = timeout
148
+
149
+ def __repr__(self) -> str:
150
+ return self._redact(f"RunPod(base_url={self.base_url!r}, timeout={self.timeout!r})")
151
+
152
+ def _redact(self, text: str) -> str:
153
+ return text.replace(self._api_key, "[REDACTED]")
154
+
155
+ def _shape_error(self, method: str, path: str, status: int,
156
+ data: object, expected: str) -> RunPodError:
157
+ return RunPodError(
158
+ self._redact(f"{method} {path} → HTTP {status}: expected {expected}"),
159
+ status=status, body=self._redact(repr(data)),
160
+ )
161
+
162
+ def _request(self, method: str, path: str,
163
+ body: Optional[dict] = None) -> tuple[int, object]:
164
+ try:
165
+ data = json.dumps(body).encode("utf-8") if body is not None else None
166
+ request = urllib.request.Request(
167
+ self.base_url + path, data=data, method=method,
168
+ headers={
169
+ "Authorization": "Bearer " + self._api_key,
170
+ "Content-Type": "application/json",
171
+ "Accept": "application/json",
172
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) runpodkit/" + __version__,
173
+ },
174
+ )
175
+ except (TypeError, ValueError, UnicodeError) as error:
176
+ raise ValueError(self._redact(
177
+ f"{method} {path}: invalid request ({type(error).__name__}: {error})"
178
+ )) from None
179
+ try:
180
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
181
+ status = getattr(response, "status", None)
182
+ if status is None:
183
+ status = response.getcode()
184
+ raw = response.read()
185
+ except urllib.error.HTTPError as error:
186
+ try:
187
+ text = error.read().decode("utf-8", errors="replace")
188
+ except Exception:
189
+ # An unreadable HTTP error still has a meaningful status/reason.
190
+ text = ""
191
+ finally:
192
+ error.close() # release the connection (Python 3.14+ warns on leaks)
193
+ raise RunPodError(
194
+ self._redact(_error_message(method, path, error.code, text, error.reason)),
195
+ status=error.code, body=self._redact(text),
196
+ ) from None
197
+ except (urllib.error.URLError, TimeoutError, ConnectionError,
198
+ OSError, http.client.HTTPException) as error:
199
+ raise RunPodError(self._redact(
200
+ f"{method} {path} → {type(error).__name__}: {error}"
201
+ )) from None
202
+ if not raw:
203
+ return status, {}
204
+ text = raw.decode("utf-8", errors="replace")
205
+ try:
206
+ return status, json.loads(text)
207
+ except ValueError:
208
+ raise RunPodError(self._redact(
209
+ f"{method} {path} → HTTP {status}: invalid JSON response"
210
+ ), status=status, body=self._redact(text)) from None
211
+
212
+ def list_pods(self) -> list[dict]:
213
+ pods = []
214
+ path = "/pods"
215
+ cursors = set()
216
+ page_number = 0
217
+ while True:
218
+ page_number += 1
219
+ status, page = self._request("GET", path)
220
+ if (not isinstance(page, dict) or not isinstance(page.get("pods"), list)
221
+ or any(not isinstance(pod, dict) for pod in page["pods"])):
222
+ raise self._shape_error("GET", path, status, page, "a dict with a pods list of dicts")
223
+ pods.extend(page["pods"])
224
+ if "pagination" not in page:
225
+ return pods
226
+ pagination = page["pagination"]
227
+ if (not isinstance(pagination, dict)
228
+ or ("hasNextPage" in pagination and type(pagination["hasNextPage"]) is not bool)):
229
+ raise self._shape_error("GET", path, status, page, "pagination with boolean hasNextPage")
230
+ if not pagination.get("hasNextPage", False):
231
+ return pods
232
+ cursor = pagination.get("nextCursor")
233
+ if not isinstance(cursor, str) or not cursor or cursor in cursors or page_number == 1000:
234
+ raise self._shape_error("GET", path, status, page,
235
+ "a new non-empty nextCursor within 1000 pages")
236
+ cursors.add(cursor)
237
+ path = "/pods?cursor=" + urllib.parse.quote(cursor, safe="")
238
+
239
+ def get_pod(self, pod_id: str) -> Optional[dict]:
240
+ path = _pod_path(pod_id)
241
+ try:
242
+ status, pod = self._request("GET", path)
243
+ except RunPodError as error:
244
+ if error.status == 404:
245
+ return None
246
+ raise
247
+ if not isinstance(pod, dict):
248
+ raise self._shape_error("GET", path, status, pod, "a pod dict")
249
+ return pod
250
+
251
+ def find_pod(self, name: str, include_terminated: bool = False,
252
+ exclude_ids: Iterable[str] = ()) -> Optional[dict]:
253
+ """First pod named `name` (live beats terminated), skipping `exclude_ids`."""
254
+ excluded = frozenset(exclude_ids)
255
+ terminated = None
256
+ for pod in self.list_pods():
257
+ if pod.get("name") != name or pod.get("id") in excluded:
258
+ continue
259
+ if pod_state(pod) != "TERMINATED":
260
+ return pod
261
+ if terminated is None:
262
+ terminated = pod
263
+ return terminated if include_terminated else None
264
+
265
+ def _action(self, pod_id: str, action: str) -> dict:
266
+ path = _pod_path(pod_id) + "/action"
267
+ status, pod = self._request("POST", path, {"action": action})
268
+ if not isinstance(pod, dict):
269
+ raise self._shape_error("POST", path, status, pod, "a pod dict")
270
+ return pod
271
+
272
+ def start(self, pod_id: str) -> dict:
273
+ return self._action(pod_id, "start")
274
+
275
+ def stop(self, pod_id: str) -> dict:
276
+ return self._action(pod_id, "stop")
277
+
278
+ def restart(self, pod_id: str) -> dict:
279
+ return self._action(pod_id, "restart")
280
+
281
+ def terminate(self, pod_id: str) -> int:
282
+ path = _pod_path(pod_id)
283
+ try:
284
+ status, _ = self._request("DELETE", path)
285
+ except RunPodError as error:
286
+ if error.status == 404:
287
+ return 404
288
+ raise
289
+ return status
290
+
291
+ def network_volumes(self) -> list[dict]:
292
+ status, data = self._request("GET", "/network-volumes")
293
+ if (not isinstance(data, dict) or not isinstance(data.get("networkVolumes"), list)
294
+ or any(not isinstance(volume, dict) for volume in data["networkVolumes"])):
295
+ raise self._shape_error("GET", "/network-volumes", status, data,
296
+ "a dict with a networkVolumes list of dicts")
297
+ return data["networkVolumes"]
298
+
299
+ def _recover_create(self, name: str, error: RunPodError,
300
+ preexisting: frozenset) -> dict:
301
+ try:
302
+ # only a pod that did NOT exist before this create() can be ours
303
+ existing = self.find_pod(name, exclude_ids=preexisting)
304
+ except Exception as lookup_error:
305
+ # The POST outcome is unknown AND we could not look: say so plainly, never retry.
306
+ raise RunPodError(
307
+ self._redact(
308
+ f"{error} — create outcome UNKNOWN (recovery lookup failed: {lookup_error}); "
309
+ f"a pod named {name!r} may exist and bill; check `runpodkit list` before retrying"
310
+ ),
311
+ status=error.status, body=error.body,
312
+ ) from lookup_error
313
+ if existing:
314
+ return existing
315
+ # Not visible (yet). The POST outcome is unknown, so never re-POST; say so.
316
+ raise RunPodError(
317
+ f"{error} — create outcome UNKNOWN: a pod named {name!r} may still "
318
+ f"appear and bill; check `runpodkit list` before retrying",
319
+ status=error.status, body=error.body,
320
+ ) from None
321
+
322
+ def create(self, body: dict, gpu_ids: Optional[list[str]] = None) -> dict:
323
+ if not isinstance(body, dict) or not isinstance(body.get("name"), str) or not body["name"]:
324
+ raise ValueError("POST /pods: body must be a dict with a non-empty str name")
325
+ if gpu_ids is not None:
326
+ if (not isinstance(gpu_ids, list) or not gpu_ids
327
+ or any(not isinstance(gpu, str) or not gpu for gpu in gpu_ids)):
328
+ raise ValueError("POST /pods: gpu_ids must be a non-empty list of non-empty strings")
329
+ if len(set(gpu_ids)) != len(gpu_ids):
330
+ raise ValueError("POST /pods: gpu_ids must not contain duplicates")
331
+ original = copy.deepcopy(body)
332
+ attempts = list(gpu_ids) if gpu_ids is not None else [None]
333
+ gpu = original.get("gpu")
334
+ count = gpu["count"] if isinstance(gpu, dict) and "count" in gpu else 1
335
+ # Snapshot same-name pods BEFORE the first POST, so the retry guard and
336
+ # the 5xx recovery below can only ever hand back a pod THIS call made —
337
+ # never an older husk with the same name (that would leave the new,
338
+ # billing pod untracked). A failed snapshot raises before any POST.
339
+ preexisting = frozenset(
340
+ pod.get("id") for pod in self.list_pods() if pod.get("name") == original["name"])
341
+ last_error: RunPodError
342
+ for index, gpu_id in enumerate(attempts):
343
+ if index:
344
+ existing = self.find_pod(original["name"], exclude_ids=preexisting)
345
+ if existing:
346
+ return existing
347
+ payload = copy.deepcopy(original)
348
+ if gpu_id is not None:
349
+ payload["gpu"] = {"id": gpu_id, "count": count}
350
+ try:
351
+ status, pod = self._request("POST", "/pods", payload)
352
+ except RunPodError as error:
353
+ if error.status in (401, 403, 429):
354
+ raise
355
+ if error.status is not None and 400 <= error.status < 500:
356
+ last_error = error
357
+ continue
358
+ # Even invalid JSON on a successful create can mean money was spent.
359
+ return self._recover_create(original["name"], error, preexisting)
360
+ if isinstance(pod, dict) and isinstance(pod.get("id"), str) and pod["id"]:
361
+ return pod
362
+ error = self._shape_error("POST", "/pods", status, pod,
363
+ "a pod dict with a non-empty str id")
364
+ return self._recover_create(original["name"], error, preexisting)
365
+ raise last_error
366
+
367
+ def _pause(self, deadline: float, poll: float, message: str) -> None:
368
+ remaining = deadline - time.monotonic()
369
+ if remaining <= 0:
370
+ raise RunPodTimeoutError(self._redact(message))
371
+ time.sleep(min(poll, remaining))
372
+
373
+ def wait_status(self, pod_id: str, want: str, timeout: float = 240,
374
+ poll: float = 6) -> dict:
375
+ _pod_path(pod_id)
376
+ _positive_seconds(timeout, "timeout")
377
+ _positive_seconds(poll, "poll")
378
+ if not isinstance(want, str) or not want:
379
+ raise ValueError("GET /pods/{id}: want must be a non-empty status str")
380
+ want = want.upper()
381
+ deadline = time.monotonic() + timeout
382
+ state, last_error = "NOTFOUND", None
383
+ while True:
384
+ try:
385
+ pod = self.get_pod(pod_id)
386
+ state = pod_state(pod)
387
+ if state == want:
388
+ return pod if pod is not None else {}
389
+ except RunPodError as error:
390
+ if not _is_transient(error):
391
+ raise
392
+ last_error = error
393
+ suffix = f"; last error: {last_error}" if last_error is not None else ""
394
+ self._pause(deadline, poll,
395
+ f"timed out after {timeout}s waiting for pod {pod_id} to reach {want} "
396
+ f"(last state {state}{suffix})")
397
+
398
+ def wait_ssh(self, pod_id: str, timeout: float = 320, poll: float = 6,
399
+ tcp_timeout: float = 5) -> tuple[str, int]:
400
+ _pod_path(pod_id)
401
+ _positive_seconds(timeout, "timeout")
402
+ _positive_seconds(poll, "poll")
403
+ _positive_seconds(tcp_timeout, "tcp_timeout")
404
+ deadline = time.monotonic() + timeout
405
+ state, last_endpoint, last_error = "NOTFOUND", None, None
406
+ while True:
407
+ try:
408
+ pod = self.get_pod(pod_id)
409
+ state = pod_state(pod)
410
+ endpoint = ssh_endpoint(pod)
411
+ if endpoint is not None:
412
+ last_endpoint = endpoint
413
+ if _tcp_accepts(endpoint[0], endpoint[1], tcp_timeout):
414
+ return endpoint
415
+ except RunPodError as error:
416
+ if not _is_transient(error):
417
+ raise
418
+ last_error = error
419
+ suffix = f"; last error: {last_error}" if last_error is not None else ""
420
+ self._pause(deadline, poll,
421
+ f"timed out after {timeout}s waiting for pod {pod_id} SSH "
422
+ f"(last state {state}; last endpoint {last_endpoint}{suffix})")
@@ -0,0 +1,89 @@
1
+ # Usage: . "$(runpodkit bash-lib)"
2
+ # rp_get ID: pod JSON; missing pod returns 0, other failures return 1.
3
+ # rp_state: stdin JSON to state (NOTFOUND on failure); always returns 0.
4
+ # rp_ssh: stdin JSON to "ip port" or nothing; always returns 0.
5
+ # rp_action ID start|stop|restart: pod JSON; returns the CLI status.
6
+ # rp_delete ID: HTTP code; returns the CLI status.
7
+ # rp_wait_ssh ID [TIMEOUT]: endpoint, default 320 s; failures return 1.
8
+ # Missing required arguments and invalid actions return 2 with stderr.
9
+ # The key comes from non-empty $RP, else $RUNPOD_API_KEY; CLI subshell environment only, never argv.
10
+ # RUNPODKIT_CLI overrides the CLI command (default runpodkit); shell functions are supported.
11
+ # A non-exported RUNPOD_API_URL is forwarded too.
12
+
13
+ # Keep exports and function-CLI side effects out of the sourcing shell.
14
+ _rpk_cli() (
15
+ local key="${RP:-${RUNPOD_API_KEY:-}}"
16
+ RUNPOD_API_KEY=$key
17
+ export RUNPOD_API_KEY
18
+ if [ -n "${RUNPOD_API_URL:-}" ]; then
19
+ export RUNPOD_API_URL
20
+ fi
21
+ "${RUNPODKIT_CLI:-runpodkit}" "$@"
22
+ )
23
+
24
+ # Preserve the old curl convention for a missing pod.
25
+ rp_get() {
26
+ local status=0
27
+ if [ -z "${1:-}" ]; then
28
+ printf '%s\n' 'rp_get: ID is required' >&2
29
+ return 2
30
+ fi
31
+ _rpk_cli get "$1" || status=$?
32
+ case "$status" in
33
+ 0|3) return 0 ;;
34
+ *) return 1 ;;
35
+ esac
36
+ }
37
+
38
+ # A broken or silent CLI still produces a usable state word.
39
+ rp_state() {
40
+ local state
41
+ if state=$(_rpk_cli state -) && [ -n "$state" ]; then
42
+ printf '%s\n' "$state"
43
+ else
44
+ printf '%s\n' NOTFOUND
45
+ fi
46
+ return 0
47
+ }
48
+
49
+ # An unavailable endpoint is normal for a stopped or booting pod.
50
+ rp_ssh() {
51
+ local endpoint
52
+ if endpoint=$(_rpk_cli ssh -) && [ -n "$endpoint" ]; then
53
+ printf '%s\n' "$endpoint"
54
+ fi
55
+ return 0
56
+ }
57
+
58
+ # Validate actions before calling the CLI.
59
+ rp_action() {
60
+ local id="${1:-}" action="${2:-}"
61
+ if [ -z "$id" ] || [ -z "$action" ]; then
62
+ printf '%s\n' 'rp_action: ID and action are required' >&2
63
+ return 2
64
+ fi
65
+ case "$action" in
66
+ start|stop|restart) _rpk_cli "$action" "$id" ;;
67
+ *) printf '%s\n' 'rp_action: action must be start, stop, or restart' >&2
68
+ return 2 ;;
69
+ esac
70
+ }
71
+
72
+ # Forward both the HTTP code and CLI status unchanged.
73
+ rp_delete() {
74
+ if [ -z "${1:-}" ]; then
75
+ printf '%s\n' 'rp_delete: ID is required' >&2
76
+ return 2
77
+ fi
78
+ _rpk_cli delete "$1"
79
+ }
80
+
81
+ # Normalize timeout and other CLI failures to the legacy return code.
82
+ rp_wait_ssh() {
83
+ if [ -z "${1:-}" ]; then
84
+ printf '%s\n' 'rp_wait_ssh: ID is required' >&2
85
+ return 2
86
+ fi
87
+ _rpk_cli wait-ssh "$1" --timeout "${2:-320}" || return 1
88
+ return 0
89
+ }
@@ -0,0 +1,380 @@
1
+ Metadata-Version: 2.4
2
+ Name: runpodkit
3
+ Version: 0.2.0
4
+ Summary: Dependency-free RunPod REST v2 pod control for Python, Bash and the command line
5
+ Author: Kevin Cherry
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kcherry497/runpod-kit
8
+ Project-URL: Issues, https://github.com/kcherry497/runpod-kit/issues
9
+ Project-URL: Changelog, https://github.com/kcherry497/runpod-kit/blob/main/CHANGELOG.md
10
+ Keywords: runpod,gpu,cloud,pods,cli
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Programming Language :: Unix Shell
25
+ Classifier: Topic :: System :: Systems Administration
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Dynamic: license-file
30
+
31
+ <p align="center">
32
+ <img src=".github/assets/banner.svg" alt="runpodkit: RunPod pod control for Python, Bash and the CLI" width="100%">
33
+ </p>
34
+
35
+ <p align="center">
36
+ <a href="https://github.com/kcherry497/runpod-kit/actions/workflows/ci.yml"><img src="https://github.com/kcherry497/runpod-kit/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
37
+ <a href="https://github.com/kcherry497/runpod-kit/releases"><img src="https://img.shields.io/github/v/release/kcherry497/runpod-kit?sort=semver" alt="Release"></a>
38
+ <img src="https://img.shields.io/badge/python-3.9%20%E2%80%93%203.15-3776AB?logo=python&logoColor=white" alt="Python 3.9 to 3.15">
39
+ <img src="https://img.shields.io/badge/bash-3.2%2B-4EAA25?logo=gnubash&logoColor=white" alt="Bash 3.2+">
40
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
41
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
42
+ </p>
43
+
44
+ <p align="center">
45
+ <a href="#quick-start">Quick start</a> ·
46
+ <a href="#install">Install</a> ·
47
+ <a href="#setting-your-api-key">API key</a> ·
48
+ <a href="#python-usage">Python</a> ·
49
+ <a href="#bash-usage">Bash</a> ·
50
+ <a href="#cli-reference">CLI</a> ·
51
+ <a href="#create-money-safety-rules">Money safety</a>
52
+ </p>
53
+
54
+ A small, dependency-free toolkit for controlling [RunPod](https://www.runpod.io/) GPU pods from Python, Bash scripts, and the command line: list, start, stop, restart, create, terminate, and wait for a reachable SSH endpoint.
55
+
56
+ - **Python**: standard library only, Python 3.9+.
57
+ - **Bash**: a sourceable library that works on Bash 3.2+, including the macOS system Bash.
58
+ - **CLI**: `runpodkit`, which the Bash library wraps.
59
+
60
+ It targets the RunPod REST v2 API (`https://api.runpod.io/v2`). The v1 API at `rest.runpod.io` is retired; `to_v1()` adds v1-shaped fields for code that still expects them.
61
+
62
+ ## Why another client?
63
+
64
+ Two things bit us in production. This toolkit handles both for you.
65
+
66
+ > [!WARNING]
67
+ > **Stale SSH endpoints after a start.** For roughly 25 seconds after a start, the API reports `RUNNING` with the *previous* run's SSH port, which refuses connections, and the port changes on every restart. `wait_ssh` re-reads the pod on every poll and only returns an endpoint that actually accepts TCP.
68
+
69
+ > [!CAUTION]
70
+ > **Double-billing on create.** A timeout or 5xx on create does not mean no pod was made. `create` never re-POSTs after an uncertain result. It recovers the pod it made by name, or tells you plainly that the outcome is unknown. See [create() money-safety rules](#create-money-safety-rules).
71
+
72
+ ## Quick start
73
+
74
+ ```bash
75
+ pipx install "git+https://github.com/kcherry497/runpod-kit.git@v0.2.0" # or pip inside a venv; see Install
76
+ export RUNPOD_API_KEY=... # or let an AI agent use it safely: see "Setting your API key"
77
+ ```
78
+
79
+ **Python**
80
+
81
+ ```python
82
+ from runpodkit import RunPod, pod_state
83
+
84
+ rp = RunPod() # reads RUNPOD_API_KEY
85
+ for pod in rp.list_pods():
86
+ print(pod["id"], pod["name"], pod_state(pod))
87
+
88
+ rp.start("POD_ID")
89
+ host, port = rp.wait_ssh("POD_ID") # only returns once TCP connects
90
+ print(f"ssh -p {port} root@{host}")
91
+ ```
92
+
93
+ **CLI**
94
+
95
+ ```console
96
+ $ runpodkit list | jq -r '.[] | "\(.id) \(.name) \(.status)"'
97
+ $ runpodkit start POD_ID >/dev/null && runpodkit wait-ssh POD_ID
98
+ 203.0.113.10 22088
99
+ $ runpodkit stop POD_ID >/dev/null
100
+ ```
101
+
102
+ **Bash**
103
+
104
+ ```bash
105
+ . "$(runpodkit bash-lib)"
106
+ rp_action "$POD_ID" start >/dev/null
107
+ read -r host port < <(rp_wait_ssh "$POD_ID" 320) && ssh -p "$port" "root@$host"
108
+ ```
109
+
110
+ ## Install
111
+
112
+ As a command-line tool, with [pipx](https://pipx.pypa.io/) (no dependencies):
113
+
114
+ ```bash
115
+ pipx install "git+https://github.com/kcherry497/runpod-kit.git@v0.2.0"
116
+ runpodkit --version
117
+ ```
118
+
119
+ As a library in your project, inside its virtual environment:
120
+
121
+ ```bash
122
+ python3 -m pip install "git+https://github.com/kcherry497/runpod-kit.git@v0.2.0"
123
+ ```
124
+
125
+ Plain `pip install` into a system Python is refused on Ubuntu 23.04+, Debian 12+ and Homebrew Python (PEP 668); use pipx, a venv, or `install.sh` below.
126
+
127
+ Or keep a clone and link it into one or more interpreters without pip:
128
+
129
+ ```bash
130
+ git clone https://github.com/kcherry497/runpod-kit.git
131
+ cd runpod-kit
132
+ ./install.sh python3 # user site + ~/.local/bin/runpodkit
133
+ # a root-owned venv (e.g. a service), with the launcher on cron's PATH:
134
+ sudo RUNPODKIT_BIN=/usr/local/bin ./install.sh /srv/myapp/venv/bin/python
135
+ ```
136
+
137
+ `install.sh` writes a `runpodkit.pth` into each interpreter's site-packages, pointing at the clone. It also writes a `runpodkit` launcher to `${RUNPODKIT_BIN:-~/.local/bin}`. It is idempotent and needs no pip or network. Don't run it under sudo for a *system* `python3`: that would write root's user site. The clone must be readable by every user that imports it.
138
+
139
+ Two things follow from the `.pth` approach, which make it handy when several programs on one host share the toolkit:
140
+
141
+ - **Updating is `git pull`** in the clone. Every importer and every bash script picks the new code up immediately.
142
+ - **Rollback** is `git checkout <tag>`.
143
+
144
+ ### Setting your API key
145
+
146
+ runpodkit reads the key from `RUNPOD_API_KEY` and nowhere else: there is no key flag, so it never lands in argv or shell history. Pick whichever way of supplying it fits.
147
+
148
+ **Option 1: an environment variable.** Simplest, for your own shell or a service unit:
149
+
150
+ ```bash
151
+ export RUNPOD_API_KEY=... # from the RunPod console (Settings → API Keys)
152
+ runpodkit list
153
+ ```
154
+
155
+ **Option 2: [cred-broker](https://github.com/kcherry497/cred-broker), when an AI coding agent drives runpodkit.** The key stays encrypted in `pass`, and the agent works with the name `runpod` only. `cred exec` decrypts the key into `RUNPOD_API_KEY` for that one command, filters it out of the command's output, and logs the call. Add an entry to `~/.config/cred-broker/manifest.yaml`:
156
+
157
+ ```yaml
158
+ runpod:
159
+ describes: RunPod API key (list/start/stop/create/terminate pods)
160
+ pass_path: agent/runpod
161
+ env: RUNPOD_API_KEY
162
+ risk: high
163
+ note: create starts billing; terminate deletes the pod and its disk.
164
+ ```
165
+
166
+ Store the key once, in your own terminal (`! cred set runpod` inside Claude Code), then wrap any runpodkit call:
167
+
168
+ ```bash
169
+ cred set runpod # prompts; the value never passes through the agent
170
+ cred exec runpod -- runpodkit list
171
+ cred exec runpod -- python3 my_pod_script.py # Python API: RunPod() picks the key up from the env
172
+ cred exec runpod -- bash -c '. "$(runpodkit bash-lib)"; rp_wait_ssh "$1" 320' _ "$POD_ID"
173
+ ```
174
+
175
+ A RunPod key can start billing pods, so give the agent a key of its own where you can, and mark it `risk: high` as above. See cred-broker's [threat model](https://github.com/kcherry497/cred-broker#threat-model) for what it does and does not protect against.
176
+
177
+ ### Where `runpodkit.pth` goes
178
+
179
+ `./install.sh [PYTHON ...]` defaults to `python3`. It checks that each interpreter is Python >= 3.9 and writes `runpodkit.pth` containing the absolute clone directory:
180
+
181
+ | Interpreter | Destination for `runpodkit.pth` |
182
+ | --- | --- |
183
+ | Venv | That venv's `sysconfig` purelib directory |
184
+ | System Python marked externally managed under PEP 668 | That interpreter's user site |
185
+ | Unmanaged system Python with an existing, writable purelib | Its purelib directory |
186
+ | Unmanaged system Python with missing or non-writable purelib | Its user site, with a diagnostic |
187
+
188
+ A non-writable venv purelib is an error. The installer checks imports from a neutral directory and warns if an interpreter does not resolve this clone, for example because its user site is disabled.
189
+
190
+ ### Vendored copy (no install)
191
+
192
+ To ship runpodkit inside another app, copy the `runpodkit/` package next to your scripts and point `RUNPODKIT_BUNDLE` at the directory containing it. Define the CLI as a shell function and source the library:
193
+
194
+ ```bash
195
+ RUNPODKIT_BUNDLE=/path/to/bundle
196
+ runpodkit() {
197
+ PYTHONPATH="${RUNPODKIT_BUNDLE}${PYTHONPATH:+:$PYTHONPATH}" python3 -m runpodkit "$@"
198
+ }
199
+ . "$(runpodkit bash-lib)"
200
+ ```
201
+
202
+ ## Python usage
203
+
204
+ ```python
205
+ from runpodkit import (
206
+ BOOTING, RunPod, RunPodError, RunPodTimeoutError,
207
+ pod_state, ssh_endpoint, to_v1,
208
+ )
209
+
210
+ rp = RunPod()
211
+ ```
212
+
213
+ `RunPod(api_key=None, base_url=None, timeout=30)` reads `RUNPOD_API_KEY` when no key argument is supplied, and `RUNPOD_API_URL` when no base URL argument is supplied. The URL defaults to `https://api.runpod.io/v2`, with trailing slashes removed. A missing or empty key raises `RunPodError`. The HTTP request timeout is in seconds.
214
+
215
+ | Method | Result |
216
+ | --- | --- |
217
+ | `rp.list_pods()` | List of pod dicts across all cursor pages, including terminated pods |
218
+ | `rp.get_pod(pod_id)` | Pod dict, or `None` on HTTP 404 |
219
+ | `rp.find_pod(name, include_terminated=False, exclude_ids=())` | First exact-name, non-terminated match in API order, skipping IDs in `exclude_ids`; otherwise `None`. With `include_terminated=True`, falls back to the first terminated match |
220
+ | `rp.start(pod_id)` | POSTs the `start` action; returns pod dict |
221
+ | `rp.stop(pod_id)` | POSTs the `stop` action; returns pod dict |
222
+ | `rp.restart(pod_id)` | POSTs the `restart` action; returns pod dict |
223
+ | `rp.terminate(pod_id)` | DELETE HTTP status, normally `204`; returns `404` when already missing |
224
+ | `rp.network_volumes()` | List of network-volume dicts |
225
+ | `rp.wait_status(pod_id, want, timeout=240, poll=6)` | Pod dict when normalized state matches `want`, case insensitive; `{}` for a missing pod when waiting for `NOTFOUND` |
226
+ | `rp.wait_ssh(pod_id, timeout=320, poll=6, tcp_timeout=5)` | `(host, port)` after a fresh GET yields an endpoint that accepts TCP |
227
+ | `rp.create(body, gpu_ids=None)` | Created or recovered pod dict. With a list such as `gpu_ids=["NVIDIA RTX A5000", "NVIDIA A40"]`, tries the GPU types in order under the rules below |
228
+
229
+ Wait durations are seconds. Timeouts, polling intervals, and TCP timeouts must be finite positive numbers. Both wait methods tolerate transport errors, HTTP 429, and HTTP 5xx while polling; other HTTP errors propagate. Deadline expiry raises `RunPodTimeoutError`. `wait_ssh` checks TCP reachability, not SSH authentication.
230
+
231
+ The helpers perform no network requests:
232
+
233
+ | Helper | Behavior |
234
+ | --- | --- |
235
+ | `pod_state(pod)` | Uppercases `status`; returns `NOTFOUND` for non-dicts or missing/invalid status; maps `RUNNING` with absent or null `runtime` to `STARTING` |
236
+ | `ssh_endpoint(pod)` | Returns `(host, int_port)` from the first valid private-22 TCP entry in a `RUNNING` pod's `runtime.ports`, otherwise `None`; does not probe TCP |
237
+ | `to_v1(pod)` | Deep-copies a pod dict and adds/replaces `desiredStatus`, `publicIp`, and `portMappings`; never mutates the input |
238
+ | `BOOTING` | Frozenset of `PROVISIONING`, `CREATED`, `STARTING`, `RESTARTING`, `INITIALIZING` |
239
+
240
+ `to_v1` sets `desiredStatus` to `RUNNING` for running or booting states, otherwise to `pod_state(pod)`. It sets `publicIp` to the SSH host or `""`, and `portMappings` to `{"22": port}` or `{}`. It requires a dict.
241
+
242
+ `RunPodError` is a `RuntimeError` with `.status` (HTTP code, or `None` for transport/local errors) and `.body` (response text or diagnostic body, truncated to 500 characters). `RunPodTimeoutError` subclasses it and always has `.status is None`. Input validation can raise `ValueError` or `TypeError`.
243
+
244
+ Start a pod, wait for its current endpoint, then connect using an existing SSH key:
245
+
246
+ ```python
247
+ import os
248
+ import subprocess
249
+ from runpodkit import RunPod
250
+
251
+ rp = RunPod() # RUNPOD_API_KEY is already supplied in the environment.
252
+ pod_id = os.environ["POD_ID"]
253
+ rp.start(pod_id)
254
+ host, port = rp.wait_ssh(pod_id)
255
+ subprocess.run(["ssh", "-p", str(port), f"root@{host}"], check=True)
256
+ ```
257
+
258
+ ## create() money-safety rules
259
+
260
+ 1. `body` must be a dict with a non-empty string `name`. If supplied, `gpu_ids` must be a non-empty list of distinct, non-empty strings. Invalid inputs raise `ValueError`. The body is deep-copied; the caller's object is never changed.
261
+ 2. Without `gpu_ids`, there is one attempt with the body unchanged. With GPU IDs, each attempt replaces `gpu` with `{"id": gpu_id, "count": count}`. Count comes from the original `gpu["count"]` when present in a dict, otherwise defaults to `1`.
262
+ 3. Before every attempt after the first, `find_pod(name)` checks for an existing non-terminated pod. If found, it is returned without another POST. If the lookup fails, its error propagates and no POST follows. No existing pod is ever *returned* before the first attempt; the only call before it is the ID snapshot described in rule 6.
263
+ 4. A successful POST must return a dict with a non-empty string `id`. A malformed success response, including invalid JSON, triggers recovery by name because a pod may already have been created; it never triggers another POST.
264
+ 5. Only HTTP 4xx errors other than `401`, `403`, and `429` allow fallback to the next GPU. Those three codes raise immediately without fallback or recovery lookup.
265
+ 6. A transport error, HTTP 5xx, or another uncertain POST result triggers `find_pod(name)`. A found pod is returned. If absent, a `RunPodError` preserving the original status/body reports `create outcome UNKNOWN` and warns that a pod may still appear and bill. If the recovery lookup itself fails, the error still reports `create outcome UNKNOWN` (keeping the original POST status/body, with the lookup error as its cause), because a pod may exist even though it could not be checked. Recovery never re-POSTs; check `runpodkit list` before manually retrying. Before its first POST, `create` snapshots the IDs of pods already carrying that name; the retry guard and the recovery only ever return a pod **not** in that snapshot, so an older same-name husk is never mistaken for the new (billing) pod. A failed snapshot raises before any POST.
266
+ 7. If every GPU attempt is refused by an eligible 4xx, the last refusal error is raised.
267
+
268
+ ## Bash usage
269
+
270
+ ```bash
271
+ set -uo pipefail
272
+ . "$(runpodkit bash-lib)"
273
+
274
+ # RUNPOD_API_KEY is already supplied in the environment.
275
+ info=$(rp_get "$POD_ID")
276
+ printf '%s\n' "$info" | rp_state
277
+ printf '%s\n' "$info" | rp_ssh
278
+ rp_action "$POD_ID" start
279
+ if endpoint=$(rp_wait_ssh "$POD_ID" 320); then
280
+ read -r host port <<< "$endpoint"
281
+ ssh -p "$port" "root@$host"
282
+ fi
283
+ ```
284
+
285
+ | Function | Standard output | Return code |
286
+ | --- | --- | --- |
287
+ | `rp_get ID` | Pod JSON; a missing pod prints a JSON object whose `detail` is `"pod not found"` | `0` for found or missing; `1` for other CLI failures; `2` for missing/empty ID |
288
+ | `rp_state` | Reads pod JSON from stdin; prints one state word, or `NOTFOUND` if the CLI fails or is silent | Always `0` |
289
+ | `rp_ssh` | Reads pod JSON from stdin; prints `ip port` and newline, or nothing if unavailable or the CLI fails | Always `0` |
290
+ | `rp_action ID start\|stop\|restart` | CLI pod JSON | CLI status unchanged; `2` for missing/empty arguments or an invalid action |
291
+ | `rp_delete ID` | HTTP status: normally `204`, `404` if missing, or another HTTP error code; nothing on transport failure | CLI status unchanged (`0` for deleted/missing, `1` for errors); `2` for missing/empty ID |
292
+ | `rp_wait_ssh ID [TIMEOUT]` | `ip port` and newline on success; default timeout `320` seconds | `0` on success; `1` on any CLI failure, including timeout; `2` for missing/empty ID |
293
+
294
+ Argument errors write a diagnostic to stderr. These wrappers preserve CLI stderr. Pod JSON uses the CLI's default `env` stripping.
295
+
296
+ Each invocation uses a non-empty `$RP` first, otherwise `$RUNPOD_API_KEY`, otherwise an empty key. The wrapper exports the selected key only inside a subshell for the CLI call, never in argv. A non-empty `RUNPOD_API_URL` shell variable is also exported there, even if it was not exported by the caller.
297
+
298
+ `RUNPODKIT_CLI` selects an alternate executable path or shell function name; it is one quoted command name, not a command string with arguments. Empty or unset means `runpodkit`. A function named `runpodkit`, including the vendored-copy definition above, works directly. Subshell execution isolates exports and function side effects from the caller.
299
+
300
+ The library is safe to source under `set -uo pipefail` and preserves shell options, traps, and `IFS`. It uses no `exit`. Under `set -e`, handle expected nonzero function returns with `if` or another shell conditional.
301
+
302
+ ## CLI reference
303
+
304
+ Use either `runpodkit` or `python3 -m runpodkit`. Every subcommand supports `--help`.
305
+
306
+ | Subcommand and arguments | Standard output | Command-specific exit codes |
307
+ | --- | --- | --- |
308
+ | `list [--all] [--with-env]` | JSON array; hides `TERMINATED` unless `--all` | `0` |
309
+ | `get ID [--with-env]` | Pod JSON; on 404, a JSON object whose `detail` is `"pod not found"` | `0` found; `3` missing |
310
+ | `state ID` or `state -` | State word; `NOTFOUND` for a missing pod or invalid/empty stdin JSON | `0`, including `NOTFOUND` |
311
+ | `ssh ID` or `ssh -` | `ip port` and newline, or nothing when unavailable | `0` endpoint; `1` unavailable |
312
+ | `wait-ssh ID [--timeout N]` | Reachable `ip port`; default `320` seconds | `0` ready; `3` timeout |
313
+ | `wait-status ID STATUS [--timeout N] [--with-env]` | Pod JSON; case-insensitive target, default `240` seconds | `0` matched; `3` timeout |
314
+ | `start ID [--with-env]` | Pod JSON from action response | `0` |
315
+ | `stop ID [--with-env]` | Pod JSON from action response | `0` |
316
+ | `restart ID [--with-env]` | Pod JSON from action response | `0` |
317
+ | `delete ID` | HTTP status, including `404` when already missing; prints other HTTP error codes too; no stdout on transport failure | `0` deleted/missing; `1` other errors |
318
+ | `create --body FILE [--gpu ID ...] [--with-env]` | Created or recovered pod JSON; `FILE` may be `-` for stdin | `0` |
319
+ | `volumes` | Network-volume JSON array | `0` |
320
+ | `bash-lib` | Absolute path to the Bash library | `0` |
321
+ | `version` | `runpodkit` followed by its version | `0` |
322
+
323
+ All commands can also return `1` for operational errors, `2` for usage errors, or `130` on keyboard interrupt. Exit `3` is reserved for `get` not found and wait timeouts. Broken stdout pipes return `1` quietly. Operational errors normally write one line prefixed `runpodkit:` to stderr; an unavailable `ssh` endpoint returns `1` silently.
324
+
325
+ The CLI reads the API key only from `RUNPOD_API_KEY`, with no key flag. `state -`, `ssh -`, `bash-lib`, and `version` need no key and make no network requests. Other commands use `RUNPOD_API_URL` if supplied.
326
+
327
+ JSON output is indented by two spaces with a trailing newline. By default, commands printing pod JSON remove each pod's top-level `env` field. `--with-env` keeps it and is supported only by `list`, `get`, `wait-status`, `start`, `stop`, `restart`, and `create`. `volumes` prints its response without this pod-field filtering. Python API results retain `env`.
328
+
329
+ `create` reads a JSON object from a file or stdin. Repeat `--gpu` or supply several IDs after one flag; quote GPU IDs containing spaces:
330
+
331
+ ```bash
332
+ runpodkit create --body pod.json --gpu "NVIDIA RTX A5000" "NVIDIA A40"
333
+ runpodkit create --body pod.json --gpu "NVIDIA RTX A5000" --gpu "NVIDIA A40"
334
+ ```
335
+
336
+ ## RunPod v2 behavior notes
337
+
338
+ These are recorded API observations; startup timing is not a guarantee.
339
+
340
+ - V2 `status` is the observed state. The v1-style `desiredStatus` added by `to_v1` is a compatibility field and maps booting states to `RUNNING`.
341
+ - `runtime` can be null while booting. `pod_state` treats `status: RUNNING` with null or missing runtime as `STARTING`.
342
+ - SSH comes from a `runtime.ports` entry with integer `private: 22`, `type: "tcp"`, a non-empty IP, and a positive public port. A decimal-string public port is accepted and converted to an integer. The private-19123 `http` entry is ignored. `ssh.direct` can be stale and is never used.
343
+ - **Stale runtime after start:** for about 25 seconds, the API has reported `RUNNING` with the previous run's SSH port, which refuses connections. The port changes on every restart. `wait_ssh` re-GETs the pod on every poll and TCP-probes that poll's endpoint; it does not cache the first `RUNNING` endpoint. `wait_status(..., "RUNNING")` alone does not establish SSH readiness.
344
+ - Wrong-state actions can return HTTP `409`; for example, stopping an `EXITED` pod. The client propagates the error instead of treating the action as successful.
345
+ - Create capacity refusals return HTTP `400`. This is eligible for the guarded GPU fallback described above.
346
+ - The minimum persistent volume is 10 GB.
347
+ - Cloudflare has rejected Python's default urllib User-Agent with HTTP `403` and `error code: 1010`. Every client request sends the browser-style `Mozilla/5.0 (X11; Linux x86_64) runpodkit/` User-Agent followed by the package version, along with Bearer authorization, JSON content type, and JSON accept headers.
348
+
349
+ ## Security
350
+
351
+ The CLI accepts the API key through the environment, and Bash passes it only through the child environment. The client sends it in the Authorization header. The key is never added to argv and is redacted from client-generated error messages, error bodies, and `repr(rp)`; the CLI also redacts it from output and diagnostics. Supply credentials through the environment rather than command-line arguments.
352
+
353
+ Pod `env` fields are stripped from CLI JSON by default because they may contain secrets. `--with-env` exposes them. Python API results and `to_v1` copies retain them; key redaction is not general redaction of every secret in a response.
354
+
355
+ Tests are offline: HTTP and TCP calls are mocked, with guards against unmocked client network access. Bash tests use local stubs or stdin parsing; installer tests use temporary directories and interpreters.
356
+
357
+ ## Running the tests
358
+
359
+ From the clone root:
360
+
361
+ ```bash
362
+ python3 -m unittest discover -s tests -v
363
+ ```
364
+
365
+ `tests/test_bash.py` and `tests/test_install.py` can run every shell scenario under several Bash executables. Supply colon-separated absolute paths:
366
+
367
+ ```bash
368
+ RUNPODKIT_TEST_BASHES=/path/to/bash3.2:/bin/bash \
369
+ python3 -m unittest discover -s tests -v
370
+ ```
371
+
372
+ Without this variable, the shell tests use `bash` from `PATH` and are skipped only if there is none. Configured paths must be absolute, existing executables; a wrong path is a test error, never a silent skip. The tests require no API key, pip, or network.
373
+
374
+ ## Contributing
375
+
376
+ Issues and pull requests are welcome. Keep the runtime standard-library only, keep Bash 3.2 compatibility, and add an offline test for any behavior change. CI runs the suite on Python 3.9 through 3.13, the shell tests under a source-built GNU Bash 3.2.57, and a separate real-macOS job.
377
+
378
+ ## License
379
+
380
+ MIT. See [LICENSE](LICENSE). Not affiliated with or endorsed by RunPod.
@@ -0,0 +1,11 @@
1
+ runpodkit/__init__.py,sha256=W9kI7BzQgCqZ9ZfWHIVbBF4opdUq26ezr2w9tzJ8cFc,294
2
+ runpodkit/__main__.py,sha256=lXMnihD9WPA7jSSAMRUz-52M7sjg7BPOQUuBHSfHjAQ,85
3
+ runpodkit/cli.py,sha256=qCkNdfDl2VmylHxSx7zWJXkfJr3zvKRrcpdVaGD1v7M,8294
4
+ runpodkit/client.py,sha256=2ND0keVNDZEC6MGGceNyC1jzNInAcMFanSqlVsJAn94,17915
5
+ runpodkit/lib/runpod.sh,sha256=pz8b2WuolBUxD02vESho5t8xKtTNuqyzkal9fP3g9KY,2713
6
+ runpodkit-0.2.0.dist-info/licenses/LICENSE,sha256=vGOU6bzfNbWhA-EgY207i7BYQbHHnyxH1oK3v8hiVk8,1069
7
+ runpodkit-0.2.0.dist-info/METADATA,sha256=uBl36wrrZTsuuasfCFzU3gMf96zdXvd6WQVpQYbyZEg,23777
8
+ runpodkit-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ runpodkit-0.2.0.dist-info/entry_points.txt,sha256=NsTYAHAjCEZj_bbJd9zMXYgzvrogo6Dh8YGKorsDNU4,49
10
+ runpodkit-0.2.0.dist-info/top_level.txt,sha256=TD3tO2dP7Lg4NIgVvROHrMmQzmK1YhK_xKwqXdCf8jg,10
11
+ runpodkit-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ runpodkit = runpodkit.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Cherry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ runpodkit