@cliptude/cli 0.1.19 → 0.1.30

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.
@@ -5,9 +5,13 @@ from __future__ import annotations
5
5
  import json
6
6
  import mimetypes
7
7
  import os
8
+ import re
9
+ import sys
10
+ import uuid
8
11
  from contextvars import ContextVar
9
12
  from pathlib import Path
10
13
  from typing import Any
14
+ from urllib.parse import quote
11
15
 
12
16
  import httpx
13
17
 
@@ -26,33 +30,107 @@ def reset_request_token(token):
26
30
  _request_token.reset(token)
27
31
 
28
32
 
29
- def discover_desktop_base_url() -> str | None:
30
- appdata = os.environ.get("APPDATA") or os.environ.get("XDG_CONFIG_HOME")
31
- candidates: list[Path] = []
32
- if appdata:
33
- candidates.append(Path(appdata) / "Cliptude" / "desktop-runtime.json")
33
+ TARGETS = ("auto", "desktop", "cloud")
34
+ DESKTOP_NOT_RUNNING = (
35
+ "The Cliptude desktop app is not running. Open Cliptude, sign in, then try again "
36
+ "(or run `cliptude use cloud` to make videos on cliptude.com)."
37
+ )
38
+ DESKTOP_NO_KEY = "Sign in to the Cliptude desktop app once so AI assistants can use it, then try again."
39
+
40
+
41
+ def desktop_data_dirs() -> list[Path]:
42
+ """Where the desktop app keeps desktop-runtime.json (same rules as desktop/paths.py)."""
43
+ override = (os.environ.get("CLIPTUDE_DESKTOP_DATA_DIR") or "").strip()
44
+ if override:
45
+ return [Path(override).expanduser()]
34
46
  home = Path.home()
35
- candidates.append(home / "Library" / "Application Support" / "Cliptude" / "desktop-runtime.json")
36
- candidates.append(home / ".cliptude" / "desktop-runtime.json")
37
- for path in candidates:
38
- try:
39
- data = json.loads(path.read_text(encoding="utf-8"))
40
- except OSError:
41
- continue
42
- except json.JSONDecodeError:
47
+ if sys.platform == "darwin":
48
+ return [home / "Library" / "Application Support" / "Cliptude"]
49
+ if sys.platform.startswith("win"):
50
+ return [Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming") / "Cliptude"]
51
+ return [Path(os.environ.get("XDG_DATA_HOME") or home / ".local" / "share") / "cliptude"]
52
+
53
+
54
+ def _read_json(path: Path) -> dict:
55
+ try:
56
+ data = json.loads(path.read_text(encoding="utf-8"))
57
+ except (OSError, ValueError):
58
+ return {}
59
+ return data if isinstance(data, dict) else {}
60
+
61
+
62
+ def discover_desktop() -> dict | None:
63
+ """{base_url, key} of a running desktop app, or None. The port changes every launch, so
64
+ this is read on every client; the app answers /api/desktop/health/ when it is really up."""
65
+ for folder in desktop_data_dirs():
66
+ runtime = _read_json(folder / "desktop-runtime.json")
67
+ port = runtime.get("django") or runtime.get("port") or runtime.get("django_port")
68
+ if not port:
43
69
  continue
44
- port = data.get("port") or data.get("django_port")
45
- if port:
46
- return f"http://127.0.0.1:{port}"
70
+ base_url = f"http://127.0.0.1:{port}"
71
+ try:
72
+ ok = httpx.get(f"{base_url}/api/desktop/health/", timeout=2.0).status_code < 500
73
+ except httpx.HTTPError:
74
+ ok = False
75
+ if ok:
76
+ key = str(_read_json(folder / "local-api.json").get("key") or "")
77
+ return {"base_url": base_url, "key": key}
47
78
  return None
48
79
 
49
80
 
50
- def resolve_base_url() -> str:
81
+ def discover_desktop_base_url() -> str | None:
82
+ found = discover_desktop()
83
+ return found["base_url"] if found else None
84
+
85
+
86
+ def config_path() -> Path:
87
+ return Path.home() / ".cliptude" / "config.json"
88
+
89
+
90
+ def chosen_target() -> str:
91
+ """desktop, cloud or auto: CLIPTUDE_TARGET, else `cliptude use`, else auto."""
92
+ value = (os.environ.get("CLIPTUDE_TARGET") or "").strip().lower()
93
+ if value not in TARGETS:
94
+ value = str(_read_json(config_path()).get("target") or "").strip().lower()
95
+ return value if value in TARGETS else "auto"
96
+
97
+
98
+ def save_target(target: str) -> Path:
99
+ if target not in TARGETS:
100
+ raise ValueError(f"target must be one of {', '.join(TARGETS)}")
101
+ path = config_path()
102
+ data = _read_json(path)
103
+ data["target"] = target
104
+ path.parent.mkdir(parents=True, exist_ok=True)
105
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
106
+ return path
107
+
108
+
109
+ def resolve_connection(api_key: str | None = None) -> dict:
110
+ """Where requests go and with which token: {base_url, token, runtime, error}.
111
+
112
+ CLIPTUDE_BASE_URL wins (any token). Otherwise the desktop app when it is chosen, or when it
113
+ is running and nothing points at the cloud; else cliptude.com. The desktop gets only its own
114
+ local key and cliptude.com only its own login, so neither token is ever sent to the other."""
51
115
  explicit = (os.environ.get("CLIPTUDE_BASE_URL") or "").rstrip("/")
52
116
  if explicit:
53
- return explicit
54
- desktop = discover_desktop_base_url()
55
- return desktop or DEFAULT_SAAS_URL
117
+ return {"base_url": explicit, "token": _resolve_token(api_key), "runtime": "custom", "error": ""}
118
+ target = chosen_target()
119
+ # A cloud API key in the environment (without CLIPTUDE_TARGET) has always meant cliptude.com.
120
+ cloud_key_env = bool((os.environ.get("CLIPTUDE_API_KEY") or "").strip())
121
+ if target == "desktop" or (target == "auto" and not cloud_key_env):
122
+ desktop = discover_desktop()
123
+ if desktop:
124
+ token = (api_key or "").strip() or desktop["key"]
125
+ return {"base_url": desktop["base_url"], "token": token, "runtime": "desktop",
126
+ "error": "" if token else DESKTOP_NO_KEY}
127
+ if target == "desktop":
128
+ return {"base_url": "", "token": "", "runtime": "desktop", "error": DESKTOP_NOT_RUNNING}
129
+ return {"base_url": DEFAULT_SAAS_URL, "token": _resolve_token(api_key), "runtime": "cloud", "error": ""}
130
+
131
+
132
+ def resolve_base_url() -> str:
133
+ return resolve_connection()["base_url"] or DEFAULT_SAAS_URL
56
134
 
57
135
 
58
136
  def django_proxy_headers(base_url: str) -> dict[str, str]:
@@ -74,6 +152,64 @@ class CliptudeApiError(Exception):
74
152
  self.payload = payload
75
153
 
76
154
 
155
+ LOCAL_FILES_REFUSED = (
156
+ "{param} reads a file on the machine running this MCP server, which a remote (hosted) server does not "
157
+ "allow. Upload the file instead: narration with start_voiceover_upload + finish_voiceover_upload and pass "
158
+ "the voiceover_url it returns; pictures and clips for a plan job with start_media_upload + "
159
+ "finish_media_upload; a character image as image_url (a public https link). Or run the local "
160
+ "`cliptude-mcp` / `cliptude` CLI, which can read your files."
161
+ )
162
+
163
+
164
+ def _uuid_seg(value: Any, label: str = "job_id") -> str:
165
+ """A UUID path segment in canonical form; anything else (slashes, ?, #, ..) is refused."""
166
+ try:
167
+ canonical = str(uuid.UUID(str(value).strip()))
168
+ except (ValueError, TypeError, AttributeError):
169
+ raise CliptudeApiError(f"{label} must be a UUID such as 1b4e28ba-2fa1-41d2-883f-0016d3cca427.", status=400) from None
170
+ return quote(canonical, safe="")
171
+
172
+
173
+ def _int_seg(value: Any, label: str = "project_id") -> str:
174
+ """A positive integer path segment; anything else is refused."""
175
+ text = str(value).strip() if not isinstance(value, bool) else ""
176
+ if not re.fullmatch(r"[0-9]{1,18}", text):
177
+ raise CliptudeApiError(f"{label} must be a whole number.", status=400)
178
+ return quote(text, safe="")
179
+
180
+
181
+ _PRIVATE_URL_RE = re.compile(
182
+ r"\b[a-z][a-z0-9+.-]*://"
183
+ r"(?:localhost|127(?:\.\d{1,3}){3}|10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}"
184
+ r"|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|169\.254(?:\.\d{1,3}){2}|0\.0\.0\.0|\[[0-9a-f:]+\]"
185
+ r"|[a-z0-9_-]+(?:\.(?:internal|local|lan|svc|cluster\.local))*)"
186
+ r"(?::\d+)?(?![a-z0-9.-])[^\s'\"<>)]*",
187
+ re.IGNORECASE,
188
+ )
189
+
190
+
191
+ def scrub_internal(value: Any, internal_urls: list[str] | tuple[str, ...] = ()) -> Any:
192
+ """Remove internal API addresses (the server-side base URL, docker hosts, private IPs) from error text.
193
+
194
+ Strings, lists and dicts are scrubbed recursively; public https links (billing_url ...) are kept."""
195
+ if isinstance(value, dict):
196
+ return {k: scrub_internal(v, internal_urls) for k, v in value.items()}
197
+ if isinstance(value, (list, tuple)):
198
+ return [scrub_internal(v, internal_urls) for v in value]
199
+ if not isinstance(value, str):
200
+ return value
201
+ text = value
202
+ for url in internal_urls:
203
+ url = (url or "").strip().rstrip("/")
204
+ if not url:
205
+ continue
206
+ text = text.replace(url, "<cliptude-api>")
207
+ host = url.split("://", 1)[-1].split("/", 1)[0]
208
+ if host:
209
+ text = text.replace(host, "<cliptude-api>")
210
+ return _PRIVATE_URL_RE.sub("<cliptude-api>", text)
211
+
212
+
77
213
  def _talking_head_content_type(ext: str) -> str:
78
214
  return {
79
215
  ".mp4": "video/mp4",
@@ -116,6 +252,16 @@ def _probe_local_video_duration_seconds(path: Path) -> float | None:
116
252
  return None
117
253
 
118
254
 
255
+ def _login_issuer() -> str:
256
+ """The server the stored browser login belongs to, or ""."""
257
+ try:
258
+ from cliptude_mcp.credentials import load_credentials
259
+
260
+ return str((load_credentials() or {}).get("issuer") or "").rstrip("/")
261
+ except Exception:
262
+ return ""
263
+
264
+
119
265
  def _resolve_token(explicit: str | None) -> str:
120
266
  return (
121
267
  (explicit or "").strip()
@@ -176,6 +322,7 @@ def _motion_control_job_fields(
176
322
  disable_overlays: bool | None = None,
177
323
  disable_effects: bool | None = None,
178
324
  disable_transitions: bool | None = None,
325
+ disable_sound_effects: bool | None = None,
179
326
  excluded_animation_types: list[str] | None = None,
180
327
  excluded_transition_kinds: list[str] | None = None,
181
328
  as_strings: bool = False,
@@ -186,6 +333,7 @@ def _motion_control_job_fields(
186
333
  "disable_overlays": disable_overlays,
187
334
  "disable_effects": disable_effects,
188
335
  "disable_transitions": disable_transitions,
336
+ "disable_sound_effects": disable_sound_effects,
189
337
  }
190
338
  for key, value in bool_fields.items():
191
339
  if value is not None:
@@ -208,18 +356,43 @@ class CliptudeClient:
208
356
  timeout: float = 30.0,
209
357
  client_kind: str | None = None,
210
358
  ):
211
- self.base_url = (base_url or resolve_base_url()).rstrip("/")
212
359
  # "cli" or "mcp": sent as X-Cliptude-Client so Cliptude records where a job was started.
213
360
  self.client_kind = (client_kind or os.environ.get("CLIPTUDE_CLIENT_KIND") or "").strip().lower()
214
- self.api_key = _resolve_token(api_key)
215
361
  self.timeout = timeout
216
- self._session_file = not bool(
362
+ self.connection_error = ""
363
+ # False on a hosted (HTTP) MCP server: a remote caller must never make it read or write local files.
364
+ self.allow_local_files = True
365
+ if base_url:
366
+ self.base_url = base_url.rstrip("/")
367
+ self.api_key = _resolve_token(api_key)
368
+ self.runtime = "custom"
369
+ else:
370
+ conn = resolve_connection(api_key)
371
+ self.base_url = conn["base_url"].rstrip("/")
372
+ self.api_key = conn["token"]
373
+ self.runtime = conn["runtime"]
374
+ self.connection_error = conn["error"]
375
+ # Only a cliptude.com browser login (~/.cliptude/credentials.json) can be refreshed: on the default
376
+ # cloud target, or when CLIPTUDE_BASE_URL names the server that login came from (its access token
377
+ # expires within the hour, and every call after that failed "Invalid or revoked API key").
378
+ explicit_token = bool(
217
379
  (api_key or "").strip()
218
380
  or (_request_token.get() or "").strip()
219
381
  or (os.environ.get("CLIPTUDE_API_KEY") or "").strip()
220
382
  )
383
+ self._session_file = not explicit_token and (
384
+ self.runtime == "cloud" or (self.runtime == "custom" and _login_issuer() == self.base_url)
385
+ )
386
+
387
+ def _local_file(self, value: str | Path, param: str) -> Path:
388
+ """A path on this machine, only when this client may touch local files (never on a hosted server)."""
389
+ if not self.allow_local_files:
390
+ raise CliptudeApiError(LOCAL_FILES_REFUSED.format(param=param), status=400)
391
+ return Path(value)
221
392
 
222
393
  def _headers(self, *, json_content: bool = True) -> dict[str, str]:
394
+ if self.connection_error:
395
+ raise CliptudeApiError(self.connection_error)
223
396
  if not self.api_key:
224
397
  raise CliptudeApiError("Not authenticated. Run: cliptude auth login")
225
398
  headers = {
@@ -278,7 +451,7 @@ class CliptudeClient:
278
451
  return self.request("GET", "/api/v1/templates", params={"limit": limit, "offset": offset})
279
452
 
280
453
  def get_template(self, template_id: str) -> Any:
281
- return self.request("GET", f"/api/v1/templates/{template_id}")
454
+ return self.request("GET", f"/api/v1/templates/{_uuid_seg(template_id, 'template_id')}")
282
455
 
283
456
  def create_template(self, *, name: str, format: str, settings: dict[str, Any]) -> Any:
284
457
  """Create a ready-to-use template from settings (no create wizard)."""
@@ -315,6 +488,7 @@ class CliptudeClient:
315
488
  disable_overlays: bool | None = None,
316
489
  disable_effects: bool | None = None,
317
490
  disable_transitions: bool | None = None,
491
+ disable_sound_effects: bool | None = None,
318
492
  excluded_animation_types: list[str] | None = None,
319
493
  excluded_transition_kinds: list[str] | None = None,
320
494
  render_only: bool | None = None,
@@ -338,6 +512,7 @@ class CliptudeClient:
338
512
  disable_overlays=disable_overlays,
339
513
  disable_effects=disable_effects,
340
514
  disable_transitions=disable_transitions,
515
+ disable_sound_effects=disable_sound_effects,
341
516
  excluded_animation_types=excluded_animation_types,
342
517
  excluded_transition_kinds=excluded_transition_kinds,
343
518
  )
@@ -346,12 +521,16 @@ class CliptudeClient:
346
521
  disable_overlays=disable_overlays,
347
522
  disable_effects=disable_effects,
348
523
  disable_transitions=disable_transitions,
524
+ disable_sound_effects=disable_sound_effects,
349
525
  excluded_animation_types=excluded_animation_types,
350
526
  excluded_transition_kinds=excluded_transition_kinds,
351
527
  as_strings=True,
352
528
  )
353
529
  th_path = (str(talking_head_path).strip() if talking_head_path else "") or None
354
530
  vo_path = (str(voiceover_path).strip() if voiceover_path else "") or None
531
+ for param, value in (("talking_head_path", th_path), ("voiceover_path", vo_path)):
532
+ if value:
533
+ self._local_file(value, param)
355
534
  output_kind = (output or "").strip().lower() or None
356
535
  if output_kind and output_kind not in ("video", "script", "voiceover", "plan"):
357
536
  raise CliptudeApiError('output must be "video", "script", "voiceover", or "plan".')
@@ -382,6 +561,7 @@ class CliptudeClient:
382
561
  disable_overlays=disable_overlays,
383
562
  disable_effects=disable_effects,
384
563
  disable_transitions=disable_transitions,
564
+ disable_sound_effects=disable_sound_effects,
385
565
  excluded_animation_types=excluded_animation_types,
386
566
  excluded_transition_kinds=excluded_transition_kinds,
387
567
  thumbnail=thumbnail,
@@ -467,7 +647,7 @@ class CliptudeClient:
467
647
  extra_data: dict[str, str] | None = None,
468
648
  _retried: bool = False,
469
649
  ) -> Any:
470
- path = Path(file_path)
650
+ path = self._local_file(file_path, file_field)
471
651
  if not path.is_file():
472
652
  raise CliptudeApiError(missing_message)
473
653
  data: dict[str, str] = {"template_id": str(template_id), "title": title}
@@ -531,6 +711,7 @@ class CliptudeClient:
531
711
  disable_overlays: bool | None = None,
532
712
  disable_effects: bool | None = None,
533
713
  disable_transitions: bool | None = None,
714
+ disable_sound_effects: bool | None = None,
534
715
  excluded_animation_types: list[str] | None = None,
535
716
  excluded_transition_kinds: list[str] | None = None,
536
717
  thumbnail: dict[str, str] | None = None,
@@ -544,11 +725,12 @@ class CliptudeClient:
544
725
  disable_overlays=disable_overlays,
545
726
  disable_effects=disable_effects,
546
727
  disable_transitions=disable_transitions,
728
+ disable_sound_effects=disable_sound_effects,
547
729
  excluded_animation_types=excluded_animation_types,
548
730
  excluded_transition_kinds=excluded_transition_kinds,
549
731
  as_strings=True,
550
732
  )
551
- path = Path(talking_head_path)
733
+ path = self._local_file(talking_head_path, "talking_head_path")
552
734
  if not path.is_file():
553
735
  raise CliptudeApiError(f"Talking head file not found: {path}")
554
736
  ext = path.suffix.lower()
@@ -626,6 +808,7 @@ class CliptudeClient:
626
808
  disable_overlays=disable_overlays,
627
809
  disable_effects=disable_effects,
628
810
  disable_transitions=disable_transitions,
811
+ disable_sound_effects=disable_sound_effects,
629
812
  excluded_animation_types=excluded_animation_types,
630
813
  excluded_transition_kinds=excluded_transition_kinds,
631
814
  )
@@ -671,11 +854,16 @@ class CliptudeClient:
671
854
  )
672
855
 
673
856
  def get_job(self, job_id: str) -> Any:
674
- return self.request("GET", f"/api/v1/jobs/{job_id}")
857
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}")
858
+
859
+ def continue_job(
860
+ self, job_id: str, *, thumbnail: dict[str, str] | None = None, review_token: str | None = None,
861
+ ) -> Any:
862
+ """Queue a completed script/voiceover job, or a plan job with a locked plan, as a full video.
675
863
 
676
- def continue_job(self, job_id: str) -> Any:
677
- """Queue a completed script/voiceover job, or a plan job with a locked plan, as a full video."""
678
- return self.request("POST", f"/api/v1/jobs/{job_id}/continue")
864
+ Without review_token Cliptude answers with the review (HTTP 428) and queues nothing."""
865
+ body = {**_thumbnail_job_field(thumbnail), **_review_job_fields(review_token, None, None)}
866
+ return self.request("POST", f"/api/v1/jobs/{_uuid_seg(job_id)}/continue", json_body=body or None)
679
867
 
680
868
  # Product videos (store products: Shopify, any store page) --------------------------------------
681
869
 
@@ -699,33 +887,56 @@ class CliptudeClient:
699
887
  cta_text: str | None = None,
700
888
  image_urls: list[str] | None = None,
701
889
  reviews: list[dict] | None = None,
890
+ script: str | None = None,
891
+ plan: bool = False,
892
+ review_token: str | None = None,
893
+ acknowledge: list[str] | None = None,
702
894
  ) -> Any:
703
- """Queue the 80/20 educational script for a product; returns {script_id, ...} immediately."""
895
+ """Queue the 80/20 educational script for a product; returns {script_id, ...} immediately.
896
+
897
+ A paid draft (plan, or no script) first answers with the review (HTTP 428): resend with review_token.
898
+
899
+ script: narration you researched and wrote yourself; the job is script_ready at once.
900
+ plan: you plan every visual; the job stops at plan_ready with the sentence timings."""
704
901
  body: dict[str, Any] = {"product_id": product_id}
705
902
  for key, value in (
706
903
  ("angle", angle), ("duration", duration), ("template_id", template_id), ("title", title),
707
904
  ("discount_code", discount_code), ("cta_url", cta_url), ("cta_text", cta_text),
708
- ("image_urls", image_urls), ("reviews", reviews),
905
+ ("image_urls", image_urls), ("reviews", reviews), ("script", script),
709
906
  ):
710
907
  if value not in (None, "", []):
711
908
  body[key] = value
909
+ if plan:
910
+ body["plan"] = True
911
+ body.update(_review_job_fields(review_token, acknowledge, None))
712
912
  return self.request("POST", "/api/v1/commerce/scripts", json_body=body)
713
913
 
714
- def render_product_video(self, job_id: str, *, aspect_ratio: str = "16:9") -> Any:
715
- """Turn a ready product script into the video on the same job id (returns immediately)."""
716
- return self.request("POST", f"/api/v1/commerce/videos/{job_id}/render", json_body={"aspect_ratio": aspect_ratio})
914
+ def render_product_video(
915
+ self, job_id: str, *, aspect_ratio: str = "16:9", thumbnail: dict[str, str] | None = None,
916
+ review_token: str | None = None,
917
+ ) -> Any:
918
+ """Turn a ready product script into the video on the same job id (returns immediately).
919
+
920
+ thumbnail: {custom_prompt} or {reference_url} for this video's thumbnail (optional).
921
+ Without review_token Cliptude answers with the review (HTTP 428) and builds nothing."""
922
+ body = {"aspect_ratio": aspect_ratio, **_thumbnail_job_field(thumbnail),
923
+ **_review_job_fields(review_token, None, None)}
924
+ return self.request("POST", f"/api/v1/commerce/videos/{_uuid_seg(job_id)}/render", json_body=body)
717
925
 
718
926
  def get_product_video_status(self, job_id: str) -> Any:
719
- return self.request("GET", f"/api/v1/commerce/videos/{job_id}")
927
+ return self.request("GET", f"/api/v1/commerce/videos/{_uuid_seg(job_id)}")
720
928
 
721
929
  # Agent-planned videos -------------------------------------------------------------------------
722
930
 
723
- def upload_plan_media(self, job_id: str, path: str | Path) -> Any:
724
- """Send a picture or clip you found to a plan job; returns {keep, file, media_type, size} for media.keep."""
725
- path = Path(path)
931
+ def upload_plan_media(self, job_id: str, path: str | Path, *, split_shots: bool = False) -> Any:
932
+ """Send a picture or clip you found to a plan job; returns {keep, file, media_type, size} for media.keep.
933
+
934
+ split_shots: a long source (a trailer, a featurette) is also cut into clips on its cuts, each checked and
935
+ kept like an upload: shots=[{keep, from_s, seconds, notes?} or {from_s, skipped}]."""
936
+ path = self._local_file(path, "path")
726
937
  if not path.is_file():
727
938
  raise CliptudeApiError(f"File not found: {path}")
728
- base = f"/api/v1/jobs/{job_id}/media"
939
+ base = f"/api/v1/jobs/{_uuid_seg(job_id)}/media"
729
940
  init = self.request(
730
941
  "POST",
731
942
  f"{base}/init",
@@ -738,7 +949,7 @@ class CliptudeClient:
738
949
  body = {"key": (init or {}).get("key"), "upload_id": (init or {}).get("upload_id")}
739
950
  try:
740
951
  self._upload_parts(path, init, f"{base}/sign-parts", "media")
741
- return self.request("POST", f"{base}/complete", json_body=body)
952
+ return self.request("POST", f"{base}/complete", json_body={**body, **({"split_shots": True} if split_shots else {})})
742
953
  except Exception:
743
954
  try:
744
955
  self.request("POST", f"{base}/abort", json_body=body)
@@ -770,13 +981,14 @@ class CliptudeClient:
770
981
 
771
982
  def start_media_upload(self, job_id: str, *, filename: str, size: int, content_type: str | None = None) -> dict[str, Any]:
772
983
  """Signed PUT URLs for a picture or clip of a plan job, for a host that sends the bytes itself."""
773
- return self._start_signed_upload(f"/api/v1/jobs/{job_id}/media", filename=filename, size=size, content_type=content_type)
984
+ return self._start_signed_upload(f"/api/v1/jobs/{_uuid_seg(job_id)}/media", filename=filename, size=size, content_type=content_type)
774
985
 
775
- def finish_media_upload(self, job_id: str, *, key: str, upload_id: str) -> Any:
776
- return self.request("POST", f"/api/v1/jobs/{job_id}/media/complete", json_body={"key": key, "upload_id": upload_id})
986
+ def finish_media_upload(self, job_id: str, *, key: str, upload_id: str, split_shots: bool = False) -> Any:
987
+ body = {"key": key, "upload_id": upload_id, **({"split_shots": True} if split_shots else {})}
988
+ return self.request("POST", f"/api/v1/jobs/{_uuid_seg(job_id)}/media/complete", json_body=body)
777
989
 
778
990
  def abort_media_upload(self, job_id: str, *, key: str, upload_id: str) -> Any:
779
- return self.request("POST", f"/api/v1/jobs/{job_id}/media/abort", json_body={"key": key, "upload_id": upload_id})
991
+ return self.request("POST", f"/api/v1/jobs/{_uuid_seg(job_id)}/media/abort", json_body={"key": key, "upload_id": upload_id})
780
992
 
781
993
  def start_voiceover_upload(self, *, filename: str, size: int, content_type: str | None = None) -> dict[str, Any]:
782
994
  """Signed PUT URLs for a narration file, before the job exists."""
@@ -791,7 +1003,7 @@ class CliptudeClient:
791
1003
 
792
1004
  def get_narration(self, job_id: str) -> Any:
793
1005
  """Numbered sentences (with word timings), digest, pricing and template flags of a plan job."""
794
- return self.request("GET", f"/api/v1/jobs/{job_id}/narration")
1006
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}/narration")
795
1007
 
796
1008
  def get_kind_catalog(
797
1009
  self,
@@ -815,7 +1027,7 @@ class CliptudeClient:
815
1027
 
816
1028
  def put_plan(self, job_id: str, plan: dict[str, Any], *, dry_run: bool = True) -> Any:
817
1029
  """Check a plan (dry_run) or lock it. A failing check returns its report, not an exception."""
818
- path = f"/api/v1/jobs/{job_id}/plan" + ("?dry_run=1" if dry_run else "")
1030
+ path = f"/api/v1/jobs/{_uuid_seg(job_id)}/plan" + ("?dry_run=1" if dry_run else "")
819
1031
  try:
820
1032
  return self.request("PUT", path, json_body=plan)
821
1033
  except CliptudeApiError as exc:
@@ -824,18 +1036,19 @@ class CliptudeClient:
824
1036
  raise
825
1037
 
826
1038
  def get_plan(self, job_id: str) -> Any:
827
- return self.request("GET", f"/api/v1/jobs/{job_id}/plan")
1039
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}/plan")
828
1040
 
829
1041
  def get_plan_report(self, job_id: str) -> Any:
830
1042
  """What sourcing used for each media request of the locked plan, and every fallback."""
831
- return self.request("GET", f"/api/v1/jobs/{job_id}/plan/report")
1043
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}/plan/report")
832
1044
 
833
1045
  def get_plan_review(self, job_id: str) -> Any:
834
1046
  """The built design, beat by beat and graphic by graphic, with links to the media (review before render)."""
835
- return self.request("GET", f"/api/v1/jobs/{job_id}/plan/review")
1047
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}/plan/review")
836
1048
 
837
1049
  def download_voiceover_file(self, job_id: str, dest: Path) -> Path:
838
- url = f"{self.base_url}/api/v1/jobs/{job_id}/voiceover"
1050
+ dest = self._local_file(dest, "dest")
1051
+ url = f"{self.base_url}/api/v1/jobs/{_uuid_seg(job_id)}/voiceover"
839
1052
  try:
840
1053
  with httpx.stream(
841
1054
  "GET",
@@ -874,24 +1087,24 @@ class CliptudeClient:
874
1087
  return self.request("GET", "/api/v1/jobs", params=params)
875
1088
 
876
1089
  def cancel_job(self, job_id: str) -> Any:
877
- return self.request("POST", f"/api/v1/jobs/{job_id}/cancel")
1090
+ return self.request("POST", f"/api/v1/jobs/{_uuid_seg(job_id)}/cancel")
878
1091
 
879
1092
  # --- Timeline editor + Cliptude Agent -------------------------------------------------
880
1093
 
881
1094
  def open_editor_project(self, job_id: str) -> Any:
882
1095
  """Open (or create) the editor project for a completed video job; includes a compact timeline."""
883
- return self.request("GET", f"/api/v1/jobs/{job_id}/editor-project")
1096
+ return self.request("GET", f"/api/v1/jobs/{_uuid_seg(job_id)}/editor-project")
884
1097
 
885
1098
  def get_editor_project(self, project_id: int | str, *, design: bool = False) -> Any:
886
1099
  params = {"design": "1"} if design else None
887
- return self.request("GET", f"/api/v1/editor-projects/{project_id}", params=params)
1100
+ return self.request("GET", f"/api/v1/editor-projects/{_int_seg(project_id)}", params=params)
888
1101
 
889
1102
  def view_scenes(self, project_id: int | str, *, start_s: float = 0.0, end_s: float | None = None) -> Any:
890
1103
  """Contact sheets (base64 JPEG) of the timeline's pictures, clip frames and graphics, with a legend."""
891
1104
  params: dict[str, Any] = {"start_s": start_s}
892
1105
  if end_s is not None:
893
1106
  params["end_s"] = end_s
894
- return self.request("GET", f"/api/v1/editor-projects/{project_id}/scenes", params=params)
1107
+ return self.request("GET", f"/api/v1/editor-projects/{_int_seg(project_id)}/scenes", params=params)
895
1108
 
896
1109
  def agent_tiers(self) -> Any:
897
1110
  return self.request("GET", "/api/v1/agent/tiers")
@@ -906,8 +1119,11 @@ class CliptudeClient:
906
1119
  chat_id: str | None = None,
907
1120
  expected_revision: int | None = None,
908
1121
  idempotency_key: str | None = None,
1122
+ review_token: str | None = None,
909
1123
  ) -> Any:
910
- """Ask Cliptude Agent to edit the timeline. Uses the project's current revision unless given."""
1124
+ """Ask Cliptude Agent to edit the timeline. Uses the project's current revision unless given.
1125
+
1126
+ Without review_token Cliptude answers with the review (HTTP 428) and starts nothing."""
911
1127
  import uuid
912
1128
 
913
1129
  if expected_revision is None:
@@ -922,21 +1138,27 @@ class CliptudeClient:
922
1138
  }
923
1139
  if chat_id:
924
1140
  body["chat_id"] = chat_id
925
- return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs", json_body=body)
1141
+ body.update(_review_job_fields(review_token, None, None))
1142
+ return self.request("POST", f"/api/v1/editor-projects/{_int_seg(project_id)}/agent/runs", json_body=body)
926
1143
 
927
1144
  def get_agent_run(self, project_id: int | str, run_id: str) -> Any:
928
- return self.request("GET", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}")
1145
+ return self.request("GET", f"/api/v1/editor-projects/{_int_seg(project_id)}/agent/runs/{_uuid_seg(run_id, 'run_id')}")
929
1146
 
930
1147
  def cancel_agent_run(self, project_id: int | str, run_id: str) -> Any:
931
- return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}/cancel")
1148
+ return self.request("POST", f"/api/v1/editor-projects/{_int_seg(project_id)}/agent/runs/{_uuid_seg(run_id, 'run_id')}/cancel")
1149
+
1150
+ def render_project(
1151
+ self, project_id: int | str, *, accept_quality_findings: bool = False, review_token: str | None = None,
1152
+ ) -> Any:
1153
+ """Render the edited timeline to a new MP4: free the first time, then 10% of the original generation.
932
1154
 
933
- def render_project(self, project_id: int | str, *, accept_quality_findings: bool = False) -> Any:
934
- """Render the edited timeline to a new MP4: free the first time, then 10% of the original generation."""
935
- body = {"accept_quality_findings": True} if accept_quality_findings else None
936
- return self.request("POST", f"/api/v1/editor-projects/{project_id}/render", json_body=body)
1155
+ A paid export first answers with the review (HTTP 428): resend with review_token."""
1156
+ body: dict[str, Any] = {"accept_quality_findings": True} if accept_quality_findings else {}
1157
+ body.update(_review_job_fields(review_token, None, None))
1158
+ return self.request("POST", f"/api/v1/editor-projects/{_int_seg(project_id)}/render", json_body=body or None)
937
1159
 
938
1160
  def get_render(self, render_id: int | str) -> Any:
939
- return self.request("GET", f"/api/v1/editor-renders/{render_id}")
1161
+ return self.request("GET", f"/api/v1/editor-renders/{_int_seg(render_id, 'render_id')}")
940
1162
 
941
1163
  def get_account(self) -> Any:
942
1164
  return self.request("GET", "/api/v1/account")
@@ -998,7 +1220,7 @@ class CliptudeClient:
998
1220
  return self.request(
999
1221
  "POST", "/api/v1/vector-characters", json_body={"image_url": image_url.strip(), "name": name}
1000
1222
  )
1001
- path = Path(image_path)
1223
+ path = self._local_file(image_path, "image_path")
1002
1224
  if not path.is_file():
1003
1225
  raise CliptudeApiError(f"Character image not found: {path}")
1004
1226
  mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
@@ -1025,7 +1247,7 @@ class CliptudeClient:
1025
1247
 
1026
1248
  def delete_vector_character(self, character_id: str) -> Any:
1027
1249
  """Delete one of your uploaded characters (refused while a template uses it)."""
1028
- return self.request("DELETE", f"/api/v1/vector-characters/{character_id}")
1250
+ return self.request("DELETE", f"/api/v1/vector-characters/{_uuid_seg(character_id, 'character_id')}")
1029
1251
 
1030
1252
  def list_avatars(
1031
1253
  self,