pcific 0.0.0-stage → 0.2.0

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,793 @@
1
+ export function renderPythonClient(options) {
2
+ const defaultBaseUrl = (options.defaultBaseUrl ?? "https://business.pcific.ai").replace(/\/+$/u, "");
3
+ const generatedDate = options.generatedDate.trim();
4
+ return `# @pcific-generated ${generatedDate} mode=copy lang=python
5
+ """Zero-dependency PCIFIC Business API client for Python 3.10+.
6
+
7
+ Uses only the Python standard library. Copy this file into your project and
8
+ configure PCIFIC_TEST_KEY (and optionally PCIFIC_LIVE_KEY, PCIFIC_MODE,
9
+ PCIFIC_MARKETPLACE_ID).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime, timezone
16
+ from email.utils import parsedate_to_datetime
17
+ import hashlib
18
+ import hmac
19
+ import json
20
+ import os
21
+ import random
22
+ import time
23
+ from typing import Any, Callable, Mapping, Sequence
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+ import uuid
28
+ import warnings
29
+
30
+ DEFAULT_BASE_URL = ${JSON.stringify(defaultBaseUrl)}
31
+ DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300
32
+ MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
33
+ RETRYABLE_STATUSES = frozenset({408, 429, 500, 502, 503, 504})
34
+ SAFEGUARD_TERMINAL_STATUSES = frozenset({"done", "questions", "failed"})
35
+ ORBIT_TERMINAL_STATUSES = frozenset({"listing", "questions", "failed", "cancelled"})
36
+
37
+
38
+ class PcificConfigError(Exception):
39
+ """Raised when PCIFIC client configuration or environment variables are invalid."""
40
+
41
+ def __init__(
42
+ self,
43
+ message: str,
44
+ *,
45
+ code: str = "CONFIG_ERROR",
46
+ try_this: str | None = None,
47
+ ) -> None:
48
+ self.code = code
49
+ self.error = message
50
+ self.try_this = try_this
51
+ super().__init__(self._format())
52
+
53
+ def _format(self) -> str:
54
+ parts = [f"[{self.code}] {self.error}"]
55
+ if self.try_this:
56
+ parts.append(f"Next step: {self.try_this}")
57
+ return " ".join(parts)
58
+
59
+
60
+ class PcificApiError(Exception):
61
+ """Raised when the PCIFIC API returns a non-2xx HTTP status."""
62
+
63
+ def __init__(
64
+ self,
65
+ message: str,
66
+ *,
67
+ status: int,
68
+ code: str,
69
+ try_this: str | None = None,
70
+ problems: list[dict[str, Any]] | None = None,
71
+ request_id: str | None = None,
72
+ raw_body: Any = None,
73
+ ) -> None:
74
+ self.status = status
75
+ self.code = code
76
+ self.error = message
77
+ self.try_this = try_this
78
+ self.problems: list[dict[str, Any]] = problems or []
79
+ self.request_id = request_id
80
+ self.raw_body = raw_body
81
+ super().__init__(self._format())
82
+
83
+ def _format(self) -> str:
84
+ lines = [f"{self.code} (HTTP {self.status}): {self.error}"]
85
+ if self.try_this:
86
+ lines.append(f"Next step: {self.try_this}")
87
+ if self.request_id:
88
+ lines.append(f"Request ID: {self.request_id}")
89
+ if self.problems:
90
+ for item in self.problems:
91
+ where = item.get("path") or item.get("where") or "(root)"
92
+ detail = item.get("problem") or "Invalid field"
93
+ fix = item.get("tryThis")
94
+ suffix = f" -> {fix}" if fix else ""
95
+ lines.append(f" - {where}: {detail}{suffix}")
96
+ return "\\n".join(lines)
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class ResolvedPcificAuth:
101
+ api_key: str
102
+ mode: str
103
+ source: str
104
+ marketplace_id: str | None = None
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class WebhookVerificationResult:
109
+ valid: bool
110
+ timestamp: int | None = None
111
+ reason: str | None = None
112
+
113
+ def __bool__(self) -> bool:
114
+ return self.valid
115
+
116
+
117
+ def _non_empty(value: str | None) -> str | None:
118
+ if value is None:
119
+ return None
120
+ stripped = value.strip()
121
+ return stripped if stripped else None
122
+
123
+
124
+ def _is_production(env: Mapping[str, str]) -> bool:
125
+ for var_name in ("NODE_ENV", "ENVIRONMENT", "PYTHON_ENV", "APP_ENV"):
126
+ if _non_empty(env.get(var_name)) == "production":
127
+ return True
128
+ return False
129
+
130
+
131
+ def _resolve_mode(explicit_mode: str | None, env: Mapping[str, str]) -> str:
132
+ raw = _non_empty(explicit_mode) or _non_empty(env.get("PCIFIC_MODE"))
133
+ if raw is None:
134
+ return "live" if _is_production(env) else "test"
135
+ if raw in ("test", "live"):
136
+ return raw
137
+ raise PcificConfigError(
138
+ f'Invalid PCIFIC_MODE "{raw}". Expected "test" or "live".',
139
+ code="INVALID_PCIFIC_MODE",
140
+ try_this='Set PCIFIC_MODE to "test" or "live", or leave it unset to default to "live" in production and "test" elsewhere.',
141
+ )
142
+
143
+
144
+ def resolve_pcific_auth(
145
+ *,
146
+ api_key: str | None = None,
147
+ test_key: str | None = None,
148
+ live_key: str | None = None,
149
+ mode: str | None = None,
150
+ marketplace_id: str | None = None,
151
+ env: Mapping[str, str] | None = None,
152
+ warn: Callable[[str], None] | None = None,
153
+ ) -> ResolvedPcificAuth:
154
+ """Resolve PCIFIC API credentials, mirroring @pcific/sdk auth rules."""
155
+ source_env = env if env is not None else os.environ
156
+ is_prod = _is_production(source_env)
157
+ emit_warn = warn if warn is not None else (lambda msg: warnings.warn(msg, UserWarning, stacklevel=2))
158
+ resolved_marketplace = _non_empty(marketplace_id) or _non_empty(source_env.get("PCIFIC_MARKETPLACE_ID"))
159
+
160
+ direct = _non_empty(api_key)
161
+ if direct is not None:
162
+ if direct.startswith("pcific_live_"):
163
+ inferred_mode = "live"
164
+ elif direct.startswith("pcific_test_"):
165
+ inferred_mode = "test"
166
+ else:
167
+ inferred_mode = _resolve_mode(mode, source_env)
168
+ if inferred_mode == "live" and not is_prod:
169
+ emit_warn("[pcific] Using a live API key outside production.")
170
+ return ResolvedPcificAuth(
171
+ api_key=direct,
172
+ mode=inferred_mode,
173
+ source="api_key",
174
+ marketplace_id=resolved_marketplace,
175
+ )
176
+
177
+ resolved_mode = _resolve_mode(mode, source_env)
178
+
179
+ if resolved_mode == "live":
180
+ explicit_live = _non_empty(live_key)
181
+ env_live = _non_empty(source_env.get("PCIFIC_LIVE_KEY"))
182
+ key = explicit_live or env_live
183
+ if not key:
184
+ raise PcificConfigError(
185
+ 'Missing PCIFIC live API key for mode "live". Set PCIFIC_LIVE_KEY or pass live_key.',
186
+ code="MISSING_LIVE_KEY",
187
+ try_this='Set PCIFIC_LIVE_KEY or set PCIFIC_MODE="test" to use PCIFIC_TEST_KEY.',
188
+ )
189
+ if not is_prod:
190
+ emit_warn("[pcific] Using PCIFIC_LIVE_KEY outside production (PCIFIC_MODE=live).")
191
+ return ResolvedPcificAuth(
192
+ api_key=key,
193
+ mode="live",
194
+ source="live_key" if explicit_live else "PCIFIC_LIVE_KEY",
195
+ marketplace_id=resolved_marketplace,
196
+ )
197
+
198
+ explicit_test = _non_empty(test_key)
199
+ env_test = _non_empty(source_env.get("PCIFIC_TEST_KEY"))
200
+ key = explicit_test or env_test
201
+ if not key:
202
+ raise PcificConfigError(
203
+ 'Missing PCIFIC test API key for mode "test". Set PCIFIC_TEST_KEY or pass test_key.',
204
+ code="MISSING_TEST_KEY",
205
+ try_this="Set PCIFIC_TEST_KEY in your environment, or pass test_key / api_key when constructing PcificClient.",
206
+ )
207
+ return ResolvedPcificAuth(
208
+ api_key=key,
209
+ mode="test",
210
+ source="test_key" if explicit_test else "PCIFIC_TEST_KEY",
211
+ marketplace_id=resolved_marketplace,
212
+ )
213
+
214
+
215
+ def _parse_retry_after_seconds(header_value: str | None, now_fn: Callable[[], float]) -> float | None:
216
+ if not header_value:
217
+ return None
218
+ trimmed = header_value.strip()
219
+ if trimmed.isdigit():
220
+ return float(int(trimmed))
221
+ try:
222
+ parsed_dt = parsedate_to_datetime(trimmed)
223
+ if parsed_dt.tzinfo is None:
224
+ parsed_dt = parsed_dt.replace(tzinfo=timezone.utc)
225
+ delta = parsed_dt.timestamp() - now_fn()
226
+ return max(0.0, delta)
227
+ except Exception:
228
+ return None
229
+
230
+
231
+ def _encode_multipart(
232
+ fields: Mapping[str, str],
233
+ files: Sequence[tuple[str, str, bytes, str]],
234
+ ) -> tuple[bytes, str]:
235
+ boundary = f"----pcific-{uuid.uuid4().hex}"
236
+ chunks: list[bytes] = []
237
+
238
+ for name, value in fields.items():
239
+ chunks.append(f"--{boundary}\\r\\n".encode("utf-8"))
240
+ chunks.append(
241
+ f'Content-Disposition: form-data; name="{name}"\\r\\n\\r\\n'.encode("utf-8")
242
+ )
243
+ chunks.append(value.encode("utf-8"))
244
+ chunks.append(b"\\r\\n")
245
+
246
+ for field_name, filename, data, content_type in files:
247
+ safe_name = filename.replace('"', "")
248
+ chunks.append(f"--{boundary}\\r\\n".encode("utf-8"))
249
+ chunks.append(
250
+ f'Content-Disposition: form-data; name="{field_name}"; filename="{safe_name}"\\r\\n'.encode(
251
+ "utf-8"
252
+ )
253
+ )
254
+ chunks.append(f"Content-Type: {content_type}\\r\\n\\r\\n".encode("utf-8"))
255
+ chunks.append(data)
256
+ chunks.append(b"\\r\\n")
257
+
258
+ chunks.append(f"--{boundary}--\\r\\n".encode("utf-8"))
259
+ return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
260
+
261
+
262
+ def _parse_api_error(status: int, headers: Mapping[str, str], raw_bytes: bytes) -> PcificApiError:
263
+ request_id_header = headers.get("x-request-id") or headers.get("X-Request-Id")
264
+ raw_text = raw_bytes.decode("utf-8", errors="replace") if raw_bytes else ""
265
+ parsed: Any = None
266
+ if raw_text:
267
+ try:
268
+ parsed = json.loads(raw_text)
269
+ except json.JSONDecodeError:
270
+ parsed = raw_text
271
+
272
+ if isinstance(parsed, dict):
273
+ return PcificApiError(
274
+ str(parsed.get("error") or f"PCIFIC API request failed with HTTP {status}."),
275
+ status=status,
276
+ code=str(parsed.get("code") or f"HTTP_{status}"),
277
+ try_this=(
278
+ str(parsed["tryThis"])
279
+ if isinstance(parsed.get("tryThis"), str)
280
+ else "Inspect the status code and request parameters, then try again."
281
+ ),
282
+ problems=parsed.get("problems") if isinstance(parsed.get("problems"), list) else [],
283
+ request_id=(
284
+ str(parsed["requestId"])
285
+ if isinstance(parsed.get("requestId"), str)
286
+ else request_id_header
287
+ ),
288
+ raw_body=parsed,
289
+ )
290
+
291
+ return PcificApiError(
292
+ f"PCIFIC API request failed with HTTP {status}.",
293
+ status=status,
294
+ code=f"HTTP_{status}",
295
+ try_this="Retry if this is a transient server error, or contact PCIFIC support with the request ID.",
296
+ request_id=request_id_header,
297
+ raw_body=parsed,
298
+ )
299
+
300
+
301
+ def verify_webhook_signature(
302
+ raw_body: str | bytes,
303
+ signature_header: str | None,
304
+ secret: str,
305
+ *,
306
+ tolerance_seconds: int = DEFAULT_WEBHOOK_TOLERANCE_SECONDS,
307
+ now: int | None = None,
308
+ ) -> WebhookVerificationResult:
309
+ """Verify a PCIFIC webhook PCIFIC-Signature header (t=<unix>,v1=<hex>)."""
310
+ if not signature_header or not isinstance(signature_header, str):
311
+ return WebhookVerificationResult(valid=False, reason="invalid_header")
312
+
313
+ timestamp: int | None = None
314
+ sig_hex: str | None = None
315
+ t_count = 0
316
+ v1_count = 0
317
+
318
+ for segment in signature_header.split(","):
319
+ part = segment.strip()
320
+ if not part or "=" not in part:
321
+ continue
322
+ key, value = part.split("=", 1)
323
+ key = key.strip()
324
+ value = value.strip()
325
+ if key == "t":
326
+ t_count += 1
327
+ try:
328
+ timestamp = int(value)
329
+ except ValueError:
330
+ timestamp = None
331
+ elif key == "v1":
332
+ v1_count += 1
333
+ if len(value) == 64:
334
+ try:
335
+ bytes.fromhex(value)
336
+ sig_hex = value.lower()
337
+ except ValueError:
338
+ sig_hex = None
339
+
340
+ if t_count != 1 or v1_count != 1 or timestamp is None or sig_hex is None:
341
+ return WebhookVerificationResult(valid=False, reason="invalid_header")
342
+
343
+ current_ts = int(time.time()) if now is None else int(now)
344
+ if abs(current_ts - timestamp) > tolerance_seconds:
345
+ return WebhookVerificationResult(
346
+ valid=False,
347
+ timestamp=timestamp,
348
+ reason="timestamp_out_of_range",
349
+ )
350
+
351
+ body_bytes = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
352
+ signed_payload = f"{timestamp}.".encode("utf-8") + body_bytes
353
+ expected_hex = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
354
+
355
+ if not hmac.compare_digest(expected_hex, sig_hex):
356
+ return WebhookVerificationResult(
357
+ valid=False,
358
+ timestamp=timestamp,
359
+ reason="signature_mismatch",
360
+ )
361
+
362
+ return WebhookVerificationResult(valid=True, timestamp=timestamp)
363
+
364
+
365
+ class PcificClient:
366
+ """Zero-dependency HTTP client for the PCIFIC Business API."""
367
+
368
+ def __init__(
369
+ self,
370
+ *,
371
+ api_key: str | None = None,
372
+ test_key: str | None = None,
373
+ live_key: str | None = None,
374
+ mode: str | None = None,
375
+ base_url: str = DEFAULT_BASE_URL,
376
+ marketplace_id: str | None = None,
377
+ timeout: float = 30.0,
378
+ max_retries: int = 3,
379
+ base_delay: float = 0.25,
380
+ max_delay: float = 10.0,
381
+ env: Mapping[str, str] | None = None,
382
+ warn: Callable[[str], None] | None = None,
383
+ sleep: Callable[[float], None] | None = None,
384
+ now: Callable[[], float] | None = None,
385
+ ) -> None:
386
+ auth = resolve_pcific_auth(
387
+ api_key=api_key,
388
+ test_key=test_key,
389
+ live_key=live_key,
390
+ mode=mode,
391
+ marketplace_id=marketplace_id,
392
+ env=env,
393
+ warn=warn,
394
+ )
395
+ self.api_key = auth.api_key
396
+ self.mode = auth.mode
397
+ self.base_url = base_url.rstrip("/")
398
+ self.marketplace_id = auth.marketplace_id
399
+ self.timeout = timeout
400
+ self.max_retries = max_retries
401
+ self.base_delay = base_delay
402
+ self.max_delay = max_delay
403
+ self._sleep = sleep if sleep is not None else time.sleep
404
+ self._now = now if now is not None else time.time
405
+
406
+ def _build_url(
407
+ self,
408
+ path: str,
409
+ query: Mapping[str, Any] | None = None,
410
+ marketplace_id: str | None = None,
411
+ ) -> str:
412
+ params: list[tuple[str, str]] = []
413
+ effective_marketplace = marketplace_id or self.marketplace_id
414
+ has_marketplace_param = bool(query and "marketplaceId" in query and query["marketplaceId"] is not None)
415
+ if effective_marketplace and not has_marketplace_param:
416
+ params.append(("marketplaceId", effective_marketplace))
417
+ if query:
418
+ for key, value in query.items():
419
+ if value is not None:
420
+ params.append((key, str(value)))
421
+ qs = urllib.parse.urlencode(params)
422
+ return f"{self.base_url}{path}?{qs}" if qs else f"{self.base_url}{path}"
423
+
424
+ def _compute_backoff(self, attempt: int, retry_after: str | None) -> float:
425
+ retry_after_secs = _parse_retry_after_seconds(retry_after, self._now)
426
+ if retry_after_secs is not None:
427
+ return retry_after_secs
428
+ exp = min(self.max_delay, self.base_delay * (2**attempt))
429
+ jitter = exp * 0.25 * random.random()
430
+ return min(self.max_delay, exp + jitter)
431
+
432
+ def _request_json(
433
+ self,
434
+ method: str,
435
+ path: str,
436
+ *,
437
+ query: Mapping[str, Any] | None = None,
438
+ json_body: Any = None,
439
+ raw_body: bytes | None = None,
440
+ content_type: str | None = None,
441
+ marketplace_id: str | None = None,
442
+ idempotency_key: str | None | bool = None,
443
+ extra_headers: Mapping[str, str] | None = None,
444
+ ) -> dict[str, Any]:
445
+ url = self._build_url(path, query=query, marketplace_id=marketplace_id)
446
+
447
+ # Serialize body ONCE before retries so retries send identical bytes.
448
+ body_bytes: bytes | None = raw_body
449
+ resolved_content_type = content_type
450
+ if json_body is not None:
451
+ body_bytes = json.dumps(json_body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
452
+ resolved_content_type = resolved_content_type or "application/json"
453
+
454
+ resolved_idempotency: str | None
455
+ if idempotency_key is False:
456
+ resolved_idempotency = None
457
+ elif isinstance(idempotency_key, str):
458
+ resolved_idempotency = idempotency_key
459
+ elif method in MUTATING_METHODS:
460
+ resolved_idempotency = str(uuid.uuid4())
461
+ else:
462
+ resolved_idempotency = None
463
+
464
+ attempt = 0
465
+ while True:
466
+ headers: dict[str, str] = {
467
+ "Authorization": f"Bearer {self.api_key}",
468
+ "Accept": "application/json",
469
+ "User-Agent": "pcific-python/copy",
470
+ }
471
+ if resolved_content_type:
472
+ headers["Content-Type"] = resolved_content_type
473
+ if resolved_idempotency:
474
+ headers["Idempotency-Key"] = resolved_idempotency
475
+ if extra_headers:
476
+ headers.update(extra_headers)
477
+
478
+ req = urllib.request.Request(url=url, data=body_bytes, headers=headers, method=method)
479
+
480
+ try:
481
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
482
+ payload = resp.read()
483
+ if not payload:
484
+ return {}
485
+ decoded = json.loads(payload.decode("utf-8"))
486
+ return decoded if isinstance(decoded, dict) else {"data": decoded}
487
+ except urllib.error.HTTPError as exc:
488
+ err_bytes = exc.read()
489
+ retry_after = exc.headers.get("Retry-After") if exc.headers else None
490
+ if exc.code in RETRYABLE_STATUSES and attempt < self.max_retries:
491
+ delay = self._compute_backoff(attempt, retry_after)
492
+ attempt += 1
493
+ self._sleep(delay)
494
+ continue
495
+ header_map = dict(exc.headers.items()) if exc.headers else {}
496
+ raise _parse_api_error(exc.code, header_map, err_bytes) from None
497
+ except urllib.error.URLError:
498
+ if attempt < self.max_retries:
499
+ delay = self._compute_backoff(attempt, None)
500
+ attempt += 1
501
+ self._sleep(delay)
502
+ continue
503
+ raise
504
+
505
+ # --- Account & Catalogue -------------------------------------------------
506
+
507
+ def account_get_key(self) -> dict[str, Any]:
508
+ return self._request_json("GET", "/api/v1/key")
509
+
510
+ def account_get_me(self) -> dict[str, Any]:
511
+ return self._request_json("GET", "/api/v1/me")
512
+
513
+ def account_get_usage(
514
+ self,
515
+ *,
516
+ key_kind: str | None = None,
517
+ from_date: str | None = None,
518
+ to_date: str | None = None,
519
+ marketplace_id: str | None = None,
520
+ ) -> dict[str, Any]:
521
+ return self._request_json(
522
+ "GET",
523
+ "/api/v1/usage",
524
+ query={"keyKind": key_kind, "from": from_date, "to": to_date},
525
+ marketplace_id=marketplace_id,
526
+ )
527
+
528
+ def account_list_marketplaces(self) -> dict[str, Any]:
529
+ return self._request_json("GET", "/api/v1/marketplaces")
530
+
531
+ def catalogue_status(self, *, marketplace_id: str | None = None) -> dict[str, Any]:
532
+ return self._request_json("GET", "/api/v1/catalogue/status", marketplace_id=marketplace_id)
533
+
534
+ # --- Embed ---------------------------------------------------------------
535
+
536
+ def embed_create_session(
537
+ self,
538
+ *,
539
+ origin: str,
540
+ tools: Sequence[str],
541
+ minutes: int | None = None,
542
+ chat: Mapping[str, Any] | None = None,
543
+ marketplace_id: str | None = None,
544
+ idempotency_key: str | None = None,
545
+ ) -> dict[str, Any]:
546
+ body: dict[str, Any] = {"origin": origin, "tools": list(tools)}
547
+ if minutes is not None:
548
+ body["minutes"] = minutes
549
+ if chat is not None:
550
+ body["chat"] = dict(chat)
551
+ return self._request_json(
552
+ "POST",
553
+ "/api/v1/embed-sessions",
554
+ json_body=body,
555
+ marketplace_id=marketplace_id,
556
+ idempotency_key=idempotency_key,
557
+ )
558
+
559
+ # --- Safeguard -----------------------------------------------------------
560
+
561
+ def safeguard_create_review(
562
+ self,
563
+ payload: Mapping[str, Any],
564
+ *,
565
+ marketplace_id: str | None = None,
566
+ idempotency_key: str | None = None,
567
+ ) -> dict[str, Any]:
568
+ return self._request_json(
569
+ "POST",
570
+ "/api/v1/safeguard/reviews",
571
+ json_body=dict(payload),
572
+ marketplace_id=marketplace_id,
573
+ idempotency_key=idempotency_key,
574
+ )
575
+
576
+ def safeguard_get_review(
577
+ self,
578
+ review_id: str,
579
+ *,
580
+ marketplace_id: str | None = None,
581
+ ) -> dict[str, Any]:
582
+ encoded = urllib.parse.quote(review_id, safe="")
583
+ return self._request_json(
584
+ "GET",
585
+ f"/api/v1/safeguard/reviews/{encoded}",
586
+ marketplace_id=marketplace_id,
587
+ )
588
+
589
+ def safeguard_wait_for_review(
590
+ self,
591
+ id_or_payload: str | Mapping[str, Any],
592
+ *,
593
+ poll_interval: float = 1.0,
594
+ timeout: float = 180.0,
595
+ marketplace_id: str | None = None,
596
+ ) -> dict[str, Any]:
597
+ if isinstance(id_or_payload, str):
598
+ review_id = id_or_payload
599
+ else:
600
+ created = self.safeguard_create_review(id_or_payload, marketplace_id=marketplace_id)
601
+ if created.get("status") in SAFEGUARD_TERMINAL_STATUSES:
602
+ return created
603
+ review_id = str(created.get("reviewId") or created.get("id") or "")
604
+
605
+ deadline = self._now() + timeout
606
+ while True:
607
+ snapshot = self.safeguard_get_review(review_id, marketplace_id=marketplace_id)
608
+ if snapshot.get("status") in SAFEGUARD_TERMINAL_STATUSES:
609
+ return snapshot
610
+ if self._now() >= deadline:
611
+ return snapshot
612
+ self._sleep(poll_interval)
613
+
614
+ # --- Orbit ---------------------------------------------------------------
615
+
616
+ def orbit_create_listing(
617
+ self,
618
+ payload: Mapping[str, Any],
619
+ *,
620
+ marketplace_id: str | None = None,
621
+ idempotency_key: str | None = None,
622
+ ) -> dict[str, Any]:
623
+ return self._request_json(
624
+ "POST",
625
+ "/api/v1/listings",
626
+ json_body=dict(payload),
627
+ marketplace_id=marketplace_id,
628
+ idempotency_key=idempotency_key,
629
+ )
630
+
631
+ def orbit_get_listing(
632
+ self,
633
+ listing_id: str,
634
+ *,
635
+ marketplace_id: str | None = None,
636
+ ) -> dict[str, Any]:
637
+ encoded = urllib.parse.quote(listing_id, safe="")
638
+ return self._request_json(
639
+ "GET",
640
+ f"/api/v1/listings/{encoded}",
641
+ marketplace_id=marketplace_id,
642
+ )
643
+
644
+ def orbit_wait_for_listing(
645
+ self,
646
+ id_or_payload: str | Mapping[str, Any],
647
+ *,
648
+ poll_interval: float = 1.0,
649
+ timeout: float = 180.0,
650
+ marketplace_id: str | None = None,
651
+ ) -> dict[str, Any]:
652
+ if isinstance(id_or_payload, str):
653
+ run_id = id_or_payload
654
+ else:
655
+ created = self.orbit_create_listing(id_or_payload, marketplace_id=marketplace_id)
656
+ if created.get("status") in ORBIT_TERMINAL_STATUSES and created.get("processing") is not True:
657
+ return created
658
+ run_id = str(created.get("runId") or created.get("id") or "")
659
+
660
+ deadline = self._now() + timeout
661
+ while True:
662
+ snapshot = self.orbit_get_listing(run_id, marketplace_id=marketplace_id)
663
+ if snapshot.get("status") in ORBIT_TERMINAL_STATUSES and snapshot.get("processing") is not True:
664
+ return snapshot
665
+ if self._now() >= deadline:
666
+ return snapshot
667
+ self._sleep(poll_interval)
668
+
669
+ # --- Ask PCIFIC & Message Check ------------------------------------------
670
+
671
+ def ask_pcific(
672
+ self,
673
+ payload: Mapping[str, Any],
674
+ *,
675
+ marketplace_id: str | None = None,
676
+ idempotency_key: str | None = None,
677
+ ) -> dict[str, Any]:
678
+ return self._request_json(
679
+ "POST",
680
+ "/api/v1/ask-pcific",
681
+ json_body=dict(payload),
682
+ marketplace_id=marketplace_id,
683
+ idempotency_key=idempotency_key,
684
+ )
685
+
686
+ def message_check(
687
+ self,
688
+ payload: Mapping[str, Any],
689
+ *,
690
+ marketplace_id: str | None = None,
691
+ idempotency_key: str | None = None,
692
+ ) -> dict[str, Any]:
693
+ return self._request_json(
694
+ "POST",
695
+ "/api/v1/message-check",
696
+ json_body=dict(payload),
697
+ marketplace_id=marketplace_id,
698
+ idempotency_key=idempotency_key,
699
+ )
700
+
701
+ # --- Dispute Pack --------------------------------------------------------
702
+
703
+ def dispute_pack_push_listing(
704
+ self,
705
+ *,
706
+ listing_ref: str,
707
+ listing: Mapping[str, Any] | str,
708
+ occurred_at: str | None = None,
709
+ photos: Sequence[tuple[str, bytes, str]] | None = None,
710
+ marketplace_id: str | None = None,
711
+ idempotency_key: str | None = None,
712
+ ) -> dict[str, Any]:
713
+ fields: dict[str, str] = {
714
+ "listingRef": listing_ref,
715
+ "listing": listing if isinstance(listing, str) else json.dumps(listing, ensure_ascii=False),
716
+ }
717
+ if occurred_at is not None:
718
+ fields["occurredAt"] = occurred_at
719
+ file_parts: list[tuple[str, str, bytes, str]] = []
720
+ if photos:
721
+ for filename, data, content_type in photos:
722
+ file_parts.append(("photos", filename, data, content_type))
723
+ body_bytes, content_type = _encode_multipart(fields, file_parts)
724
+ return self._request_json(
725
+ "POST",
726
+ "/api/v1/dispute-pack/listings",
727
+ raw_body=body_bytes,
728
+ content_type=content_type,
729
+ marketplace_id=marketplace_id,
730
+ idempotency_key=idempotency_key,
731
+ )
732
+
733
+ def dispute_pack_create_dispute(
734
+ self,
735
+ payload: Mapping[str, Any],
736
+ *,
737
+ marketplace_id: str | None = None,
738
+ idempotency_key: str | None = None,
739
+ ) -> dict[str, Any]:
740
+ return self._request_json(
741
+ "POST",
742
+ "/api/v1/dispute-pack/disputes",
743
+ json_body=dict(payload),
744
+ marketplace_id=marketplace_id,
745
+ idempotency_key=idempotency_key,
746
+ )
747
+
748
+ # --- Schemas & Webhooks --------------------------------------------------
749
+
750
+ def schema_put_category(
751
+ self,
752
+ category: str,
753
+ schema: Mapping[str, Any],
754
+ *,
755
+ parent: str | None = None,
756
+ marketplace_id: str | None = None,
757
+ idempotency_key: str | None = None,
758
+ ) -> dict[str, Any]:
759
+ encoded = urllib.parse.quote(category, safe="")
760
+ return self._request_json(
761
+ "PUT",
762
+ f"/api/v1/schema-draft/categories/{encoded}",
763
+ query={"parent": parent} if parent else None,
764
+ json_body=dict(schema),
765
+ marketplace_id=marketplace_id,
766
+ idempotency_key=idempotency_key,
767
+ )
768
+
769
+ def schema_publish(
770
+ self,
771
+ *,
772
+ about: str | None = None,
773
+ marketplace_id: str | None = None,
774
+ idempotency_key: str | None = None,
775
+ ) -> dict[str, Any]:
776
+ body: dict[str, Any] = {"about": about} if about is not None else {}
777
+ return self._request_json(
778
+ "POST",
779
+ "/api/v1/schema-versions",
780
+ json_body=body,
781
+ marketplace_id=marketplace_id,
782
+ idempotency_key=idempotency_key,
783
+ )
784
+
785
+ def webhooks_list(self, *, marketplace_id: str | None = None) -> dict[str, Any]:
786
+ return self._request_json("GET", "/api/v1/webhooks", marketplace_id=marketplace_id)
787
+
788
+
789
+ def create_pcific_client(**kwargs: Any) -> PcificClient:
790
+ """Create a configured PcificClient instance."""
791
+ return PcificClient(**kwargs)
792
+ `;
793
+ }