@cliptude/cli 0.1.3 → 0.1.7

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.
@@ -13,6 +13,7 @@ import httpx
13
13
  from cliptude_mcp.credentials import stored_access_token
14
14
 
15
15
  DEFAULT_SAAS_URL = "https://cliptude.com"
16
+ TALKING_HEAD_EXTS = {".mp4", ".mov", ".webm", ".avi"}
16
17
  _request_token: ContextVar[str | None] = ContextVar("cliptude_request_token", default=None)
17
18
 
18
19
 
@@ -53,6 +54,18 @@ def resolve_base_url() -> str:
53
54
  return desktop or DEFAULT_SAAS_URL
54
55
 
55
56
 
57
+ def django_proxy_headers(base_url: str) -> dict[str, str]:
58
+ """Mark docker-internal HTTP as HTTPS so Django skips SECURE_SSL_REDIRECT.
59
+
60
+ Production Django 301s ``http://web:5021`` to ``https://web:5021``. That
61
+ handshake times out inside the compose network, so MCP token verification
62
+ always failed after a successful OAuth exchange.
63
+ """
64
+ if (base_url or "").strip().lower().startswith("http://"):
65
+ return {"X-Forwarded-Proto": "https"}
66
+ return {}
67
+
68
+
56
69
  class CliptudeApiError(Exception):
57
70
  def __init__(self, message: str, status: int | None = None, payload: Any = None):
58
71
  super().__init__(message)
@@ -60,6 +73,48 @@ class CliptudeApiError(Exception):
60
73
  self.payload = payload
61
74
 
62
75
 
76
+ def _talking_head_content_type(ext: str) -> str:
77
+ return {
78
+ ".mp4": "video/mp4",
79
+ ".mov": "video/quicktime",
80
+ ".webm": "video/webm",
81
+ ".avi": "video/x-msvideo",
82
+ }.get((ext or "").lower(), "video/mp4")
83
+
84
+
85
+ def _probe_local_video_duration_seconds(path: Path) -> float | None:
86
+ """Return duration via ffprobe when available; None if ffprobe is missing or fails."""
87
+ import shutil
88
+ import subprocess
89
+
90
+ ffprobe = shutil.which("ffprobe")
91
+ if not ffprobe:
92
+ return None
93
+ try:
94
+ result = subprocess.run(
95
+ [
96
+ ffprobe,
97
+ "-v",
98
+ "error",
99
+ "-show_entries",
100
+ "format=duration",
101
+ "-of",
102
+ "default=noprint_wrappers=1:nokey=1",
103
+ str(path),
104
+ ],
105
+ capture_output=True,
106
+ text=True,
107
+ timeout=30,
108
+ check=False,
109
+ )
110
+ value = float((result.stdout or "").strip())
111
+ if value > 0:
112
+ return value
113
+ except (OSError, ValueError, subprocess.TimeoutExpired):
114
+ return None
115
+ return None
116
+
117
+
63
118
  def _resolve_token(explicit: str | None) -> str:
64
119
  return (
65
120
  (explicit or "").strip()
@@ -69,6 +124,54 @@ def _resolve_token(explicit: str | None) -> str:
69
124
  )
70
125
 
71
126
 
127
+ def _avatar_job_fields(
128
+ avatar_intro_only: bool | None,
129
+ avatar_ai_footage: bool | None,
130
+ *,
131
+ as_strings: bool = False,
132
+ ) -> dict[str, Any]:
133
+ fields: dict[str, Any] = {}
134
+ if avatar_intro_only is not None:
135
+ fields["avatar_intro_only"] = (
136
+ ("true" if avatar_intro_only else "false") if as_strings else bool(avatar_intro_only)
137
+ )
138
+ if avatar_ai_footage is not None:
139
+ fields["avatar_ai_footage"] = (
140
+ ("true" if avatar_ai_footage else "false") if as_strings else bool(avatar_ai_footage)
141
+ )
142
+ return fields
143
+
144
+
145
+ def _motion_control_job_fields(
146
+ *,
147
+ disable_animations: bool | None = None,
148
+ disable_overlays: bool | None = None,
149
+ disable_effects: bool | None = None,
150
+ disable_transitions: bool | None = None,
151
+ excluded_animation_types: list[str] | None = None,
152
+ excluded_transition_kinds: list[str] | None = None,
153
+ as_strings: bool = False,
154
+ ) -> dict[str, Any]:
155
+ fields: dict[str, Any] = {}
156
+ bool_fields = {
157
+ "disable_animations": disable_animations,
158
+ "disable_overlays": disable_overlays,
159
+ "disable_effects": disable_effects,
160
+ "disable_transitions": disable_transitions,
161
+ }
162
+ for key, value in bool_fields.items():
163
+ if value is not None:
164
+ fields[key] = ("true" if value else "false") if as_strings else bool(value)
165
+ list_fields = {
166
+ "excluded_animation_types": excluded_animation_types,
167
+ "excluded_transition_kinds": excluded_transition_kinds,
168
+ }
169
+ for key, value in list_fields.items():
170
+ if value is not None:
171
+ fields[key] = ",".join(value) if as_strings else list(value)
172
+ return fields
173
+
174
+
72
175
  class CliptudeClient:
73
176
  def __init__(self, base_url: str | None = None, api_key: str | None = None, timeout: float = 30.0):
74
177
  self.base_url = (base_url or resolve_base_url()).rstrip("/")
@@ -80,14 +183,17 @@ class CliptudeClient:
80
183
  or (os.environ.get("CLIPTUDE_API_KEY") or "").strip()
81
184
  )
82
185
 
83
- def _headers(self) -> dict[str, str]:
186
+ def _headers(self, *, json_content: bool = True) -> dict[str, str]:
84
187
  if not self.api_key:
85
188
  raise CliptudeApiError("Not authenticated. Run: cliptude auth login")
86
- return {
189
+ headers = {
87
190
  "Authorization": f"Bearer {self.api_key}",
88
191
  "Accept": "application/json",
89
- "Content-Type": "application/json",
192
+ **django_proxy_headers(self.base_url),
90
193
  }
194
+ if json_content:
195
+ headers["Content-Type"] = "application/json"
196
+ return headers
91
197
 
92
198
  def _maybe_refresh(self) -> bool:
93
199
  if not self._session_file:
@@ -136,6 +242,21 @@ class CliptudeClient:
136
242
  def get_template(self, template_id: str) -> Any:
137
243
  return self.request("GET", f"/api/v1/templates/{template_id}")
138
244
 
245
+ def create_template(self, *, name: str, format: str, settings: dict[str, Any]) -> Any:
246
+ """Create a ready-to-use template from settings (no create wizard)."""
247
+ return self.request(
248
+ "POST", "/api/v1/templates", json_body={"name": name, "format": format, "settings": settings}
249
+ )
250
+
251
+ def template_options(self, format: str) -> Any:
252
+ return self.request("GET", "/api/v1/templates/options", params={"format": format})
253
+
254
+ def list_voices(self, *, provider: str = "elevenlabs", language: str | None = None) -> Any:
255
+ params = {"provider": provider}
256
+ if language:
257
+ params["language"] = language
258
+ return self.request("GET", "/api/v1/voices", params=params)
259
+
139
260
  def create_job(
140
261
  self,
141
262
  *,
@@ -143,40 +264,378 @@ class CliptudeClient:
143
264
  title: str,
144
265
  prompt: str | None = None,
145
266
  script: str | None = None,
146
- faceless_coding: str | None = None,
147
267
  duration: str | None = None,
268
+ voiceover_path: str | Path | None = None,
269
+ talking_head_path: str | Path | None = None,
270
+ output: str | None = None,
271
+ avatar_intro_only: bool | None = None,
272
+ avatar_ai_footage: bool | None = None,
273
+ disable_animations: bool | None = None,
274
+ disable_overlays: bool | None = None,
275
+ disable_effects: bool | None = None,
276
+ disable_transitions: bool | None = None,
277
+ excluded_animation_types: list[str] | None = None,
278
+ excluded_transition_kinds: list[str] | None = None,
148
279
  ) -> Any:
280
+ motion_fields = _motion_control_job_fields(
281
+ disable_animations=disable_animations,
282
+ disable_overlays=disable_overlays,
283
+ disable_effects=disable_effects,
284
+ disable_transitions=disable_transitions,
285
+ excluded_animation_types=excluded_animation_types,
286
+ excluded_transition_kinds=excluded_transition_kinds,
287
+ )
288
+ motion_fields_str = _motion_control_job_fields(
289
+ disable_animations=disable_animations,
290
+ disable_overlays=disable_overlays,
291
+ disable_effects=disable_effects,
292
+ disable_transitions=disable_transitions,
293
+ excluded_animation_types=excluded_animation_types,
294
+ excluded_transition_kinds=excluded_transition_kinds,
295
+ as_strings=True,
296
+ )
297
+ th_path = (str(talking_head_path).strip() if talking_head_path else "") or None
298
+ vo_path = (str(voiceover_path).strip() if voiceover_path else "") or None
299
+ output_kind = (output or "").strip().lower() or None
300
+ if output_kind and output_kind not in ("video", "script", "voiceover", "plan"):
301
+ raise CliptudeApiError('output must be "video", "script", "voiceover", or "plan".')
302
+ if output_kind in ("script", "voiceover") and (th_path or vo_path):
303
+ raise CliptudeApiError(
304
+ "Script and voiceover jobs cannot upload a voiceover or talking-head file."
305
+ )
306
+ if th_path and vo_path:
307
+ raise CliptudeApiError("Upload either a talking head video or a voiceover — not both.")
308
+ if th_path and (prompt or script):
309
+ raise CliptudeApiError(
310
+ "Upload a talking head video, or send a prompt / custom script — not both. "
311
+ "An uploaded talking head is transcribed and used as the narration."
312
+ )
313
+ if vo_path and (prompt or script):
314
+ raise CliptudeApiError(
315
+ "Upload a voiceover, or send a prompt / custom script — not both. "
316
+ "An uploaded file is transcribed and used as the narration."
317
+ )
318
+ if th_path:
319
+ return self._create_job_talking_head(
320
+ template_id=template_id,
321
+ title=title,
322
+ talking_head_path=th_path,
323
+ avatar_intro_only=avatar_intro_only,
324
+ avatar_ai_footage=avatar_ai_footage,
325
+ disable_animations=disable_animations,
326
+ disable_overlays=disable_overlays,
327
+ disable_effects=disable_effects,
328
+ disable_transitions=disable_transitions,
329
+ excluded_animation_types=excluded_animation_types,
330
+ excluded_transition_kinds=excluded_transition_kinds,
331
+ )
332
+ if vo_path:
333
+ extra_data = {
334
+ **_avatar_job_fields(avatar_intro_only, avatar_ai_footage, as_strings=True),
335
+ **motion_fields_str,
336
+ **({"output": output_kind} if output_kind == "plan" else {}),
337
+ }
338
+ return self._create_job_multipart(
339
+ template_id=template_id,
340
+ title=title,
341
+ duration=duration,
342
+ file_field="voiceover",
343
+ file_path=vo_path,
344
+ missing_message=f"Voiceover file not found: {vo_path}",
345
+ extra_data=extra_data or None,
346
+ )
149
347
  body: dict[str, Any] = {"template_id": template_id, "title": title}
150
348
  if prompt:
151
349
  body["prompt"] = prompt
152
350
  if script:
153
351
  body["script"] = script
154
- if faceless_coding:
155
- body["faceless_coding"] = faceless_coding
156
352
  if duration:
157
353
  body["duration"] = duration
354
+ if output_kind and output_kind != "video":
355
+ body["output"] = output_kind
356
+ body.update(_avatar_job_fields(avatar_intro_only, avatar_ai_footage))
357
+ body.update(motion_fields)
358
+ return self.request("POST", "/api/v1/jobs", json_body=body)
359
+
360
+ def _raise_http(self, resp, *, payload=None) -> None:
361
+ if payload is None:
362
+ try:
363
+ payload = resp.json()
364
+ except ValueError:
365
+ payload = {"error": resp.text}
366
+ message = payload.get("error") if isinstance(payload, dict) else str(payload)
367
+ if resp.status_code == 401:
368
+ message = message or "Not authenticated. Run: cliptude auth login"
369
+ raise CliptudeApiError(
370
+ message or f"HTTP {resp.status_code}",
371
+ status=resp.status_code,
372
+ payload=payload,
373
+ )
374
+
375
+ def _create_job_multipart(
376
+ self,
377
+ *,
378
+ template_id: str,
379
+ title: str,
380
+ duration: str | None,
381
+ file_field: str,
382
+ file_path: str | Path,
383
+ missing_message: str,
384
+ extra_data: dict[str, str] | None = None,
385
+ _retried: bool = False,
386
+ ) -> Any:
387
+ path = Path(file_path)
388
+ if not path.is_file():
389
+ raise CliptudeApiError(missing_message)
390
+ data: dict[str, str] = {"template_id": str(template_id), "title": title}
391
+ if duration:
392
+ data["duration"] = duration
393
+ if extra_data:
394
+ data.update(extra_data)
395
+ url = f"{self.base_url}/api/v1/jobs"
396
+ headers = self._headers(json_content=False)
397
+ try:
398
+ with path.open("rb") as fh:
399
+ resp = httpx.post(
400
+ url,
401
+ headers=headers,
402
+ data=data,
403
+ files={file_field: (path.name, fh, "application/octet-stream")},
404
+ timeout=max(self.timeout, 300.0),
405
+ )
406
+ except httpx.HTTPError as exc:
407
+ raise CliptudeApiError(str(exc)) from exc
408
+ if resp.status_code == 401 and not _retried and self._maybe_refresh():
409
+ return self._create_job_multipart(
410
+ template_id=template_id,
411
+ title=title,
412
+ duration=duration,
413
+ file_field=file_field,
414
+ file_path=file_path,
415
+ missing_message=missing_message,
416
+ extra_data=extra_data,
417
+ _retried=True,
418
+ )
419
+ try:
420
+ payload = resp.json()
421
+ except ValueError:
422
+ payload = {"error": resp.text}
423
+ if resp.status_code >= 400:
424
+ self._raise_http(resp, payload=payload)
425
+ return payload
426
+
427
+ def _abort_talking_head_upload(self, key: str | None, upload_id: str | None) -> None:
428
+ if not key or not upload_id:
429
+ return
430
+ try:
431
+ self.request(
432
+ "POST",
433
+ "/api/v1/uploads/talking-head/abort",
434
+ json_body={"key": key, "upload_id": upload_id},
435
+ )
436
+ except Exception:
437
+ pass
438
+
439
+ def _create_job_talking_head(
440
+ self,
441
+ *,
442
+ template_id: str,
443
+ title: str,
444
+ talking_head_path: str | Path,
445
+ avatar_intro_only: bool | None = None,
446
+ avatar_ai_footage: bool | None = None,
447
+ disable_animations: bool | None = None,
448
+ disable_overlays: bool | None = None,
449
+ disable_effects: bool | None = None,
450
+ disable_transitions: bool | None = None,
451
+ excluded_animation_types: list[str] | None = None,
452
+ excluded_transition_kinds: list[str] | None = None,
453
+ ) -> Any:
454
+ motion_extra = _motion_control_job_fields(
455
+ disable_animations=disable_animations,
456
+ disable_overlays=disable_overlays,
457
+ disable_effects=disable_effects,
458
+ disable_transitions=disable_transitions,
459
+ excluded_animation_types=excluded_animation_types,
460
+ excluded_transition_kinds=excluded_transition_kinds,
461
+ as_strings=True,
462
+ )
463
+ path = Path(talking_head_path)
464
+ if not path.is_file():
465
+ raise CliptudeApiError(f"Talking head file not found: {path}")
466
+ ext = path.suffix.lower()
467
+ if ext not in TALKING_HEAD_EXTS:
468
+ raise CliptudeApiError(
469
+ f'Unsupported file type "{ext}". Please upload MP4, MOV, WEBM, or AVI.'
470
+ )
471
+ size = path.stat().st_size
472
+ duration = _probe_local_video_duration_seconds(path)
473
+ init = self.request(
474
+ "POST",
475
+ "/api/v1/uploads/talking-head/init",
476
+ json_body={
477
+ "filename": path.name,
478
+ "size": size,
479
+ "content_type": _talking_head_content_type(ext),
480
+ },
481
+ )
482
+ if not isinstance(init, dict) or init.get("fallback"):
483
+ extra_data = {
484
+ **_avatar_job_fields(avatar_intro_only, avatar_ai_footage, as_strings=True),
485
+ **motion_extra,
486
+ }
487
+ return self._create_job_multipart(
488
+ template_id=template_id,
489
+ title=title,
490
+ duration=None,
491
+ file_field="talking_head",
492
+ file_path=path,
493
+ missing_message=f"Talking head file not found: {path}",
494
+ extra_data=extra_data or None,
495
+ )
496
+ key = str(init.get("key") or "").strip()
497
+ upload_id = str(init.get("upload_id") or "").strip()
498
+ if duration is None:
499
+ self._abort_talking_head_upload(key, upload_id)
500
+ extra_data = {
501
+ **_avatar_job_fields(avatar_intro_only, avatar_ai_footage, as_strings=True),
502
+ **motion_extra,
503
+ }
504
+ return self._create_job_multipart(
505
+ template_id=template_id,
506
+ title=title,
507
+ duration=None,
508
+ file_field="talking_head",
509
+ file_path=path,
510
+ missing_message=f"Talking head file not found: {path}",
511
+ extra_data=extra_data or None,
512
+ )
513
+ try:
514
+ self._upload_talking_head_parts(path, init)
515
+ self.request(
516
+ "POST",
517
+ "/api/v1/uploads/talking-head/complete",
518
+ json_body={"key": key, "upload_id": upload_id},
519
+ )
520
+ except Exception:
521
+ self._abort_talking_head_upload(key, upload_id)
522
+ raise
523
+ body: dict[str, Any] = {
524
+ "template_id": str(template_id),
525
+ "title": title,
526
+ "talking_head_r2_key": key,
527
+ "talking_head_duration": str(duration),
528
+ }
529
+ body.update(_avatar_job_fields(avatar_intro_only, avatar_ai_footage))
530
+ body.update(
531
+ _motion_control_job_fields(
532
+ disable_animations=disable_animations,
533
+ disable_overlays=disable_overlays,
534
+ disable_effects=disable_effects,
535
+ disable_transitions=disable_transitions,
536
+ excluded_animation_types=excluded_animation_types,
537
+ excluded_transition_kinds=excluded_transition_kinds,
538
+ )
539
+ )
158
540
  return self.request("POST", "/api/v1/jobs", json_body=body)
159
541
 
542
+ def _upload_talking_head_parts(self, path: Path, init: dict[str, Any]) -> None:
543
+ key = str(init.get("key") or "").strip()
544
+ upload_id = str(init.get("upload_id") or "").strip()
545
+ part_size = int(init.get("part_size") or 0)
546
+ part_count = int(init.get("part_count") or 0)
547
+ if not key or not upload_id or part_size <= 0 or part_count <= 0:
548
+ raise CliptudeApiError("Talking head upload init returned an incomplete plan.")
549
+ with path.open("rb") as fh:
550
+ for start in range(0, part_count, 50):
551
+ nums = list(range(start + 1, min(start + 50, part_count) + 1))
552
+ signed = self.request(
553
+ "POST",
554
+ "/api/v1/uploads/talking-head/sign-parts",
555
+ json_body={"key": key, "upload_id": upload_id, "part_numbers": nums},
556
+ )
557
+ urls = (signed or {}).get("urls") if isinstance(signed, dict) else None
558
+ if not isinstance(urls, dict):
559
+ raise CliptudeApiError("Could not sign talking head upload parts.")
560
+ for num in nums:
561
+ url = urls.get(str(num))
562
+ if not url:
563
+ raise CliptudeApiError(f"Could not sign part {num}.")
564
+ chunk = fh.read(part_size)
565
+ try:
566
+ resp = httpx.put(url, content=chunk, timeout=max(self.timeout, 300.0))
567
+ except httpx.HTTPError as exc:
568
+ raise CliptudeApiError(str(exc)) from exc
569
+ if resp.status_code >= 400:
570
+ raise CliptudeApiError(
571
+ f"Failed to upload talking head part {num}.",
572
+ status=resp.status_code,
573
+ )
574
+
160
575
  def get_job(self, job_id: str) -> Any:
161
576
  return self.request("GET", f"/api/v1/jobs/{job_id}")
162
577
 
163
- def download_coding_kit(self, job_id: str) -> Any:
164
- """Return coding_kit url/path from get_job. Never downloads zip bytes."""
165
- job = self.get_job(job_id)
166
- kit = job.get("coding_kit") if isinstance(job, dict) else None
167
- if not kit:
168
- raise CliptudeApiError("Coding kit is not ready yet. Poll until status is awaiting_project.")
169
- return kit
578
+ def continue_job(self, job_id: str) -> Any:
579
+ """Queue a completed script/voiceover job, or a plan job with a locked plan, as a full video."""
580
+ return self.request("POST", f"/api/v1/jobs/{job_id}/continue")
581
+
582
+ # Agent-planned videos -------------------------------------------------------------------------
170
583
 
171
- def download_coding_kit_file(self, job_id: str, dest: Path) -> Path:
172
- url = f"{self.base_url}/api/v1/jobs/{job_id}/coding-kit"
584
+ def get_narration(self, job_id: str) -> Any:
585
+ """Numbered sentences (with word timings), digest, pricing and template flags of a plan job."""
586
+ return self.request("GET", f"/api/v1/jobs/{job_id}/narration")
587
+
588
+ def get_kind_catalog(
589
+ self,
590
+ *,
591
+ format: str | None = None,
592
+ theme: str | None = None,
593
+ compact: bool = False,
594
+ types: list[str] | None = None,
595
+ premium: bool = False,
596
+ ) -> Any:
597
+ """Every graphic an agent can place. compact: one summary line each; types: full entries for those;
598
+ premium: only the premium boards."""
599
+ params = {k: v for k, v in (("format", format), ("theme", theme)) if v}
600
+ if compact:
601
+ params["compact"] = "1"
602
+ if premium:
603
+ params["premium"] = "1"
604
+ if types:
605
+ params["types"] = ",".join(types)
606
+ return self.request("GET", "/api/v1/catalog/kinds", params=params or None)
607
+
608
+ def put_plan(self, job_id: str, plan: dict[str, Any], *, dry_run: bool = True) -> Any:
609
+ """Check a plan (dry_run) or lock it. A failing check returns its report, not an exception."""
610
+ path = f"/api/v1/jobs/{job_id}/plan" + ("?dry_run=1" if dry_run else "")
611
+ try:
612
+ return self.request("PUT", path, json_body=plan)
613
+ except CliptudeApiError as exc:
614
+ if exc.status in (400, 409, 413) and isinstance(exc.payload, dict) and "errors" in exc.payload:
615
+ return {**exc.payload, "http_status": exc.status}
616
+ raise
617
+
618
+ def get_plan(self, job_id: str) -> Any:
619
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan")
620
+
621
+ def get_plan_report(self, job_id: str) -> Any:
622
+ """What sourcing used for each media request of the locked plan, and every fallback."""
623
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan/report")
624
+
625
+ def get_plan_review(self, job_id: str) -> Any:
626
+ """The built design, beat by beat and graphic by graphic, with links to the media (review before render)."""
627
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan/review")
628
+
629
+ def download_voiceover_file(self, job_id: str, dest: Path) -> Path:
630
+ url = f"{self.base_url}/api/v1/jobs/{job_id}/voiceover"
173
631
  try:
174
632
  with httpx.stream(
175
633
  "GET",
176
634
  url,
177
635
  headers={
178
636
  "Authorization": f"Bearer {self.api_key}",
179
- "Accept": "application/zip, application/json",
637
+ "Accept": "audio/mpeg, application/json",
638
+ **django_proxy_headers(self.base_url),
180
639
  },
181
640
  timeout=self.timeout,
182
641
  follow_redirects=True,
@@ -200,34 +659,6 @@ class CliptudeClient:
200
659
  raise CliptudeApiError(str(exc)) from exc
201
660
  return dest
202
661
 
203
- def submit_faceless_project(self, job_id: str, zip_path: str | Path) -> Any:
204
- path = Path(zip_path)
205
- if not path.is_file():
206
- raise CliptudeApiError(f"Project zip not found: {path}")
207
- url = f"{self.base_url}/api/v1/jobs/{job_id}/project"
208
- headers = {
209
- "Authorization": f"Bearer {self.api_key}",
210
- "Accept": "application/json",
211
- }
212
- try:
213
- with path.open("rb") as fh:
214
- resp = httpx.post(
215
- url,
216
- headers=headers,
217
- files={"zip": (path.name, fh, "application/zip")},
218
- timeout=max(self.timeout, 120.0),
219
- )
220
- except httpx.HTTPError as exc:
221
- raise CliptudeApiError(str(exc)) from exc
222
- try:
223
- payload = resp.json()
224
- except ValueError:
225
- payload = {"error": resp.text}
226
- if resp.status_code >= 400:
227
- message = payload.get("error") if isinstance(payload, dict) else str(payload)
228
- raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=payload)
229
- return payload
230
-
231
662
  def list_jobs(self, *, status: str | None = None, limit: int = 20, offset: int = 0) -> Any:
232
663
  params: dict[str, Any] = {"limit": limit, "offset": offset}
233
664
  if status:
@@ -237,5 +668,59 @@ class CliptudeClient:
237
668
  def cancel_job(self, job_id: str) -> Any:
238
669
  return self.request("POST", f"/api/v1/jobs/{job_id}/cancel")
239
670
 
671
+ # --- Timeline editor + Cliptude Agent -------------------------------------------------
672
+
673
+ def open_editor_project(self, job_id: str) -> Any:
674
+ """Open (or create) the editor project for a completed video job; includes a compact timeline."""
675
+ return self.request("GET", f"/api/v1/jobs/{job_id}/editor-project")
676
+
677
+ def get_editor_project(self, project_id: int | str, *, design: bool = False) -> Any:
678
+ params = {"design": "1"} if design else None
679
+ return self.request("GET", f"/api/v1/editor-projects/{project_id}", params=params)
680
+
681
+ def agent_tiers(self) -> Any:
682
+ return self.request("GET", "/api/v1/agent/tiers")
683
+
684
+ def run_agent(
685
+ self,
686
+ project_id: int | str,
687
+ *,
688
+ prompt: str,
689
+ tier: str = "fast",
690
+ referenced_item_ids: list[str] | None = None,
691
+ chat_id: str | None = None,
692
+ expected_revision: int | None = None,
693
+ idempotency_key: str | None = None,
694
+ ) -> Any:
695
+ """Ask Cliptude Agent to edit the timeline. Uses the project's current revision unless given."""
696
+ import uuid
697
+
698
+ if expected_revision is None:
699
+ project = self.get_editor_project(project_id).get("project") or {}
700
+ expected_revision = int(project.get("revision") or 0)
701
+ body: dict[str, Any] = {
702
+ "prompt": prompt,
703
+ "tier": tier,
704
+ "referenced_item_ids": list(referenced_item_ids or []),
705
+ "expected_revision": expected_revision,
706
+ "idempotency_key": idempotency_key or uuid.uuid4().hex,
707
+ }
708
+ if chat_id:
709
+ body["chat_id"] = chat_id
710
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs", json_body=body)
711
+
712
+ def get_agent_run(self, project_id: int | str, run_id: str) -> Any:
713
+ return self.request("GET", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}")
714
+
715
+ def cancel_agent_run(self, project_id: int | str, run_id: str) -> Any:
716
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}/cancel")
717
+
718
+ def render_project(self, project_id: int | str) -> Any:
719
+ """Render the edited timeline to a new MP4 (charged like an editor export)."""
720
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/render")
721
+
722
+ def get_render(self, render_id: int | str) -> Any:
723
+ return self.request("GET", f"/api/v1/editor-renders/{render_id}")
724
+
240
725
  def get_account(self) -> Any:
241
726
  return self.request("GET", "/api/v1/account")