maximem-synap-cli 0.3.5__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.
synap/cli/api.py ADDED
@@ -0,0 +1,402 @@
1
+ """Thin HTTP client over the Synap Management API plane."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional, Tuple
6
+
7
+ import httpx
8
+
9
+ from synap.cli import __version__
10
+
11
+ MANAGEMENT_PREFIX = "/api/v1/management"
12
+ USER_AGENT = f"maximem-synap-cli/{__version__}"
13
+
14
+
15
+ # Typed process exit codes (the agent-onboarding contract). 1 is the generic
16
+ # fallback for anything that has not been classified.
17
+ EXIT_OK = 0
18
+ EXIT_GENERIC = 1
19
+ EXIT_USAGE = 2
20
+ EXIT_AUTH = 3
21
+ EXIT_NOT_FOUND = 4
22
+ EXIT_PERMISSION = 5
23
+ EXIT_CONFLICT = 6
24
+ EXIT_TIMEOUT = 7
25
+ EXIT_SERVER = 8
26
+ EXIT_REVOCATION_PENDING = 9
27
+
28
+ _STATUS_TO_ERROR = {
29
+ 400: ("bad_request", EXIT_USAGE),
30
+ 401: ("not_authenticated", EXIT_AUTH),
31
+ 403: ("permission_denied", EXIT_PERMISSION),
32
+ 404: ("not_found", EXIT_NOT_FOUND),
33
+ # Not enough credits (and similar). No dedicated exit code in the contract, so
34
+ # 1; the distinct `code` plus `details` are what the agent keys off.
35
+ 402: ("insufficient_credits", EXIT_GENERIC),
36
+ 409: ("conflict", EXIT_CONFLICT),
37
+ 422: ("invalid_request", EXIT_USAGE),
38
+ }
39
+
40
+
41
+ def classify_status(status_code: Optional[int]) -> Tuple[str, int]:
42
+ """Map an HTTP status to a (snake_case code, exit code) pair."""
43
+ if status_code is None:
44
+ return "error", EXIT_GENERIC
45
+ if status_code in _STATUS_TO_ERROR:
46
+ return _STATUS_TO_ERROR[status_code]
47
+ if status_code >= 500 or status_code == 429:
48
+ return "server_error", EXIT_SERVER
49
+ return "error", EXIT_GENERIC
50
+
51
+
52
+ class CliError(Exception):
53
+ """A user-facing CLI error with an exit-worthy message.
54
+
55
+ ``detail`` is the server's structured error body (the ``detail`` of a
56
+ FastAPI error, or the whole JSON body), when there was one. Commands read it
57
+ to turn a machine-readable ``reason`` into guidance; ``message`` stays the
58
+ generic rendering for everyone else.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ message: str,
64
+ *,
65
+ status_code: Optional[int] = None,
66
+ detail: Any = None,
67
+ code: Optional[str] = None,
68
+ exit_code: Optional[int] = None,
69
+ hint: Optional[str] = None,
70
+ ):
71
+ super().__init__(message)
72
+ self.message = message
73
+ self.status_code = status_code
74
+ self.detail = detail
75
+ # Typed classification. Explicit values win; otherwise derive from the
76
+ # HTTP status; otherwise generic (1).
77
+ derived_code, derived_exit = classify_status(status_code)
78
+ self.code = code or derived_code
79
+ self.exit_code = exit_code if exit_code is not None else derived_exit
80
+ self.hint = hint
81
+
82
+ def to_json(self) -> Dict[str, Any]:
83
+ """The machine-readable error shape printed on stderr in JSON mode."""
84
+ err: Dict[str, Any] = {
85
+ "code": self.code,
86
+ "message": self.message,
87
+ "exit_code": self.exit_code,
88
+ "hint": self.hint,
89
+ }
90
+ # The server's structured error body (e.g. the credits needed vs. the
91
+ # balance on a 402) so an agent can explain the concrete numbers.
92
+ if isinstance(self.detail, (dict, list)):
93
+ err["details"] = self.detail
94
+ return {"error": err}
95
+
96
+
97
+ # Human labels for the statuses the Management plane actually returns, so errors
98
+ # read like guidance instead of leaking a raw "HTTP 404: ...".
99
+ _STATUS_LABEL = {
100
+ 400: "Bad request",
101
+ 403: "Permission denied",
102
+ 402: "Payment required",
103
+ 404: "Not found",
104
+ 409: "Conflict",
105
+ 429: "Rate limited",
106
+ 422: "Invalid request",
107
+ }
108
+
109
+
110
+ def _detail_message(detail: Any) -> str:
111
+ """Flatten a FastAPI/JSON error ``detail`` into a one-line message."""
112
+ if detail is None:
113
+ return ""
114
+ if isinstance(detail, str):
115
+ return detail
116
+ if isinstance(detail, dict):
117
+ return str(detail.get("message") or detail.get("detail") or detail)
118
+ if isinstance(detail, list):
119
+ # FastAPI validation errors: [{"loc": [...], "msg": "...", ...}]
120
+ parts = []
121
+ for item in detail:
122
+ if isinstance(item, dict):
123
+ loc = [
124
+ str(x) for x in (item.get("loc") or [])
125
+ if x not in ("body", "query", "path")
126
+ ]
127
+ field = ".".join(loc)
128
+ msg = item.get("msg", "invalid value")
129
+ parts.append(f"{field}: {msg}" if field else msg)
130
+ else:
131
+ parts.append(str(item))
132
+ return "; ".join(parts)
133
+ return str(detail)
134
+
135
+
136
+ def _error_detail(resp: httpx.Response) -> Any:
137
+ """The structured error body of a non-2xx response, or None."""
138
+ try:
139
+ body = resp.json()
140
+ except Exception:
141
+ return None
142
+ return body.get("detail", body) if isinstance(body, dict) else body
143
+
144
+
145
+ def _explain(resp: httpx.Response) -> str:
146
+ """Turn a non-2xx response into a readable, guidance-shaped message."""
147
+ try:
148
+ body = resp.json()
149
+ except Exception:
150
+ return f"HTTP {resp.status_code}: {resp.text[:300]}"
151
+
152
+ detail = body.get("detail", body) if isinstance(body, dict) else body
153
+
154
+ # Structured scope error carries the missing scope name.
155
+ if isinstance(detail, dict) and detail.get("error") == "missing_scope":
156
+ return (
157
+ f"Permission denied — this key is missing the "
158
+ f"'{detail.get('required')}' scope."
159
+ )
160
+
161
+ if resp.status_code == 401:
162
+ return (
163
+ "Not authenticated — your CLI key is missing, invalid, or expired."
164
+ )
165
+
166
+ msg = _detail_message(detail)
167
+ label = _STATUS_LABEL.get(resp.status_code)
168
+ if label:
169
+ return f"{label}: {msg}" if msg else label
170
+ return f"HTTP {resp.status_code}: {msg}" if msg else f"HTTP {resp.status_code}"
171
+
172
+
173
+ _ENV_KEY_HINT = (
174
+ "SYNAP_API_KEY is set in this environment and overrides the CLI's stored login. "
175
+ "If it holds a runtime key (for example you sourced the project .env), the "
176
+ "management API rejects it: unset SYNAP_API_KEY for CLI calls, or run the CLI "
177
+ "as `env -u SYNAP_API_KEY maximem-synap ...`."
178
+ )
179
+
180
+
181
+ def _rate_limit_hint(resp: httpx.Response) -> str:
182
+ """The server's wait advice for a 429, from its body or Retry-After."""
183
+ detail = _error_detail(resp)
184
+ if isinstance(detail, dict) and isinstance(detail.get("hint"), str) and detail["hint"]:
185
+ return detail["hint"]
186
+ retry = None
187
+ try:
188
+ retry = (getattr(resp, "headers", None) or {}).get("Retry-After")
189
+ except Exception:
190
+ retry = None
191
+ if retry and str(retry).strip().isdigit():
192
+ return f"Wait {int(str(retry).strip())} seconds, then run the same command again."
193
+ return "Wait a minute, then run the same command again."
194
+
195
+
196
+ _INSTANCE_LIMIT_HINT = (
197
+ "Stop. Tell the human this workspace hit its instance limit (the server message says the "
198
+ "limit and the count) and ask whether to reuse an existing instance or contact support to "
199
+ "raise the limit. Do not retry, do not delete instances to make room, and do not use another "
200
+ "key or workspace to get around it."
201
+ )
202
+
203
+
204
+ def _build_conflict(detail: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
205
+ """(code, hint) for the build-supervision 409s; the body passes through as details."""
206
+ kind = detail.get("error")
207
+ if kind == "instance_build_failed":
208
+ hint = detail.get("hint") or (
209
+ f"Run: maximem-synap instances rebuild {detail.get('instance_id', '<instance_id>')}")
210
+ return kind, hint
211
+ if kind == "idempotency_key_reuse":
212
+ return kind, ("This --idempotency-key was already used for a different create request. "
213
+ "Drop the flag (the CLI derives a key from the request) or use a new key.")
214
+ if kind == "instance_name_taken":
215
+ existing = detail.get("existing_instance_id") or "<instance_id>"
216
+ return kind, (
217
+ f"Use the existing instance: maximem-synap instances get {existing}. "
218
+ "Or pick a different --name. Ask the human which they want; do not guess."
219
+ )
220
+ if kind == "instance_limit_reached":
221
+ return kind, _INSTANCE_LIMIT_HINT
222
+ if kind == "instance_not_ready":
223
+ wait = detail.get("retry_after_seconds")
224
+ left = f" (attempt {detail['attempt']} of 3)" if detail.get("attempt") else ""
225
+ return kind, (
226
+ f"The memory architecture is still being built{left}. Wait "
227
+ f"{wait if wait is not None else 30} seconds, tell the human how long, then "
228
+ "check again with `maximem-synap instances wait <instance_id>`. Do not retry in a loop."
229
+ )
230
+ return None, None
231
+
232
+
233
+ class ApiClient:
234
+ """Management-plane client bound to a base URL and (optionally) an API key."""
235
+
236
+ def __init__(
237
+ self,
238
+ api_base: str,
239
+ api_key: Optional[str] = None,
240
+ *,
241
+ timeout: float = 30.0,
242
+ verbose: bool = False,
243
+ key_from_env: bool = False,
244
+ ):
245
+ self.api_base = api_base.rstrip("/")
246
+ self.api_key = api_key
247
+ self.timeout = timeout
248
+ self.verbose = verbose
249
+ # True when the key came from the SYNAP_API_KEY env var (which overrides
250
+ # the stored profile). Only used to explain a 401/403.
251
+ self.key_from_env = key_from_env
252
+ # Response headers of the most recent successful request (for callers
253
+ # that need one, e.g. Idempotent-Replay).
254
+ self.last_response_headers: Dict[str, str] = {}
255
+
256
+ def _headers(self, auth: bool) -> Dict[str, str]:
257
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
258
+ if auth:
259
+ if not self.api_key:
260
+ raise CliError(
261
+ "Not logged in.",
262
+ code="not_authenticated", exit_code=EXIT_AUTH,
263
+ hint="If the key expired or is gone, ask the human for a fresh onboarding code, then run `maximem-synap auth login --code <code>`.",
264
+ )
265
+ headers["Authorization"] = f"Bearer {self.api_key}"
266
+ return headers
267
+
268
+ def request(
269
+ self,
270
+ method: str,
271
+ path: str,
272
+ *,
273
+ auth: bool = True,
274
+ json: Optional[Any] = None,
275
+ params: Optional[Dict[str, Any]] = None,
276
+ prefix: str = MANAGEMENT_PREFIX,
277
+ headers: Optional[Dict[str, str]] = None,
278
+ retry_once_on_network_error: bool = False,
279
+ ) -> Any:
280
+ """``retry_once_on_network_error`` is ONLY for requests that are safe to
281
+ repeat (carry an idempotency key): one automatic retry after a timeout,
282
+ connect failure or connection reset."""
283
+ url = f"{self.api_base}{prefix}{path}"
284
+ if self.verbose:
285
+ import sys
286
+ print(f" → {method} {url}", file=sys.stderr)
287
+ all_headers = {**self._headers(auth), **(headers or {})}
288
+ attempts = 2 if retry_once_on_network_error else 1
289
+ for attempt in range(attempts):
290
+ try:
291
+ resp = httpx.request(
292
+ method,
293
+ url,
294
+ headers=all_headers,
295
+ json=json,
296
+ params=params,
297
+ timeout=self.timeout,
298
+ )
299
+ break
300
+ except (httpx.TimeoutException, httpx.ConnectError,
301
+ httpx.ReadError, httpx.RemoteProtocolError) as e:
302
+ if attempt + 1 < attempts:
303
+ if self.verbose:
304
+ import sys
305
+ print(f" ! {type(e).__name__}; retrying once with the same idempotency key",
306
+ file=sys.stderr)
307
+ continue
308
+ resp = e
309
+ except httpx.HTTPError as e:
310
+ resp = e
311
+ break
312
+ try:
313
+ if isinstance(resp, Exception):
314
+ raise resp
315
+ except httpx.TimeoutException as e:
316
+ raise CliError(
317
+ f"Request to {self.api_base} timed out ({e}).",
318
+ code="timeout", exit_code=EXIT_TIMEOUT,
319
+ hint="Retry; check your network connection.",
320
+ )
321
+ except httpx.ConnectError as e:
322
+ raise CliError(
323
+ f"Could not reach Synap at {self.api_base} ({e}). "
324
+ f"Is the server running?",
325
+ code="network_error", exit_code=EXIT_SERVER,
326
+ hint="Check your network connection and --api-base/--env.",
327
+ )
328
+ except httpx.HTTPError as e:
329
+ raise CliError(
330
+ f"Request failed: {e}", code="network_error", exit_code=EXIT_SERVER,
331
+ )
332
+
333
+ if self.verbose:
334
+ import sys
335
+ print(f" ← {resp.status_code}", file=sys.stderr)
336
+
337
+ if resp.status_code >= 400:
338
+ hint = None
339
+ if resp.status_code == 401:
340
+ hint = "If the key expired or is gone, ask the human for a fresh onboarding code, then run `maximem-synap auth login --code <code>`."
341
+ elif resp.status_code == 429:
342
+ hint = _rate_limit_hint(resp)
343
+ if resp.status_code in (401, 403) and self.key_from_env:
344
+ hint = f"{_ENV_KEY_HINT} {hint}" if hint else _ENV_KEY_HINT
345
+ detail = _error_detail(resp)
346
+ code = None
347
+ if (resp.status_code == 403 and isinstance(detail, dict)
348
+ and detail.get("error") == "instance_not_created_by_this_session"):
349
+ iid = detail.get("instance_id") or "that instance"
350
+ raise CliError(
351
+ f"This setup key only manages instances this session created itself, and {iid} "
352
+ "was not created by it.",
353
+ status_code=403, detail=detail, code="instance_not_created_by_this_session",
354
+ hint="Ask the human to create the API key for that instance in the dashboard (API keys "
355
+ "page) and put it into the project's .env themselves. Do not look for another way "
356
+ "around it.",
357
+ )
358
+ if resp.status_code == 409 and isinstance(detail, dict):
359
+ code, hint409 = _build_conflict(detail)
360
+ hint = hint409 or hint
361
+ if (resp.status_code == 429 and isinstance(detail, dict)
362
+ and detail.get("error") == "instance_create_rate_limited"):
363
+ code = "instance_create_rate_limited"
364
+ hint = ("Stop. This workspace created too many instances in the last hour. Tell the "
365
+ "human and ask whether to wait or contact support. Do not retry in a loop.")
366
+ raise CliError(
367
+ _explain(resp),
368
+ status_code=resp.status_code,
369
+ detail=detail,
370
+ code=code,
371
+ hint=hint,
372
+ )
373
+
374
+ try:
375
+ self.last_response_headers = {
376
+ str(k).lower(): str(v) for k, v in dict(getattr(resp, "headers", None) or {}).items()
377
+ }
378
+ except Exception:
379
+ self.last_response_headers = {}
380
+ if resp.status_code == 204 or not resp.content:
381
+ return None
382
+ try:
383
+ return resp.json()
384
+ except Exception:
385
+ return resp.text
386
+
387
+ # Convenience verbs ----------------------------------------------------
388
+
389
+ def get(self, path: str, **kw) -> Any:
390
+ return self.request("GET", path, **kw)
391
+
392
+ def post(self, path: str, **kw) -> Any:
393
+ return self.request("POST", path, **kw)
394
+
395
+ def put(self, path: str, **kw) -> Any:
396
+ return self.request("PUT", path, **kw)
397
+
398
+ def patch(self, path: str, **kw) -> Any:
399
+ return self.request("PATCH", path, **kw)
400
+
401
+ def delete(self, path: str, **kw) -> Any:
402
+ return self.request("DELETE", path, **kw)