@clipen/clipen-cli 1.0.0 → 1.0.1

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 (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -7,18 +7,18 @@ attempt workspace.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- from dataclasses import dataclass, replace
11
10
  import json
12
11
  import os
13
- from pathlib import Path
14
12
  import re
15
13
  import shutil
16
14
  import signal
17
15
  import subprocess
18
16
  import tempfile
19
17
  import time
20
- from typing import Mapping
21
18
  import uuid
19
+ from dataclasses import dataclass, replace
20
+ from pathlib import Path
21
+ from typing import Mapping
22
22
 
23
23
  from jsonschema import Draft202012Validator
24
24
  from jsonschema.exceptions import SchemaError, ValidationError
@@ -45,7 +45,6 @@ from .recovery import (
45
45
  utc_now,
46
46
  )
47
47
 
48
-
49
48
  _MAX_PROMPT_BYTES = 1_000_000
50
49
  _MAX_SCHEMA_BYTES = 1_000_000
51
50
  _MAX_CAPTURE_BYTES = 2_000_000
@@ -142,10 +141,13 @@ def codex_preferences(environment: Mapping[str, str] | None = None) -> tuple[str
142
141
  tables.setdefault(table, {})
143
142
  elif value := _STRING.match(line):
144
143
  tables[table][value.group(1)] = value.group(2) if value.group(2) is not None else value.group(3)
145
- chosen = {**tables[""], **tables.get("profiles." + tables[""].get("profile", ""), {})} if tables[""].get("profile") else tables[""]
144
+ chosen = (
145
+ {**tables[""], **tables.get("profiles." + tables[""].get("profile", ""), {})}
146
+ if tables[""].get("profile")
147
+ else tables[""]
148
+ )
146
149
  model, effort = chosen.get("model"), chosen.get("model_reasoning_effort")
147
- return (model if model and _MODEL.fullmatch(model) else None,
148
- effort if effort in _EFFORTS else None)
150
+ return (model if model and _MODEL.fullmatch(model) else None, effort if effort in _EFFORTS else None)
149
151
 
150
152
 
151
153
  def model_config(binary: str | Path, environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
@@ -154,11 +156,14 @@ def model_config(binary: str | Path, environment: Mapping[str, str] | None = Non
154
156
  if preferences == (None, None):
155
157
  return ()
156
158
  from .account import available_models, resolve_codex_model
159
+
157
160
  resolved = resolve_codex_model(preferences, available_models(binary, environment or os.environ))
158
161
  if resolved is None:
159
162
  return ()
160
- return (*(("-c", f"model={json.dumps(resolved['id'])}") if resolved["apply_model"] else ()),
161
- *(("-c", f"model_reasoning_effort={json.dumps(resolved['effort'])}") if resolved["apply_effort"] else ()))
163
+ return (
164
+ *(("-c", f"model={json.dumps(resolved['id'])}") if resolved["apply_model"] else ()),
165
+ *(("-c", f"model_reasoning_effort={json.dumps(resolved['effort'])}") if resolved["apply_effort"] else ()),
166
+ )
162
167
 
163
168
 
164
169
  def _provider_environment(source: Mapping[str, str] | None = None) -> dict[str, str]:
@@ -209,12 +214,10 @@ def _permission_config(workspace: Path, temp_root: Path | None = None) -> tuple[
209
214
  f'{_toml_string(":minimal")}="read"',
210
215
  f'{_toml_string(":workspace_roots")}="read"',
211
216
  ]
212
- filesystem_entries.extend(
213
- f'{_toml_string(path)}="deny"' for path in sorted(denied_roots)
214
- )
217
+ filesystem_entries.extend(f'{_toml_string(path)}="deny"' for path in sorted(denied_roots))
215
218
  return (
216
219
  "-c",
217
- f'default_permissions={_toml_string(_PERMISSION_PROFILE)}',
220
+ f"default_permissions={_toml_string(_PERMISSION_PROFILE)}",
218
221
  "-c",
219
222
  f'permissions.{_PERMISSION_PROFILE}.description="Clipen isolated AI attempt"',
220
223
  "-c",
@@ -268,11 +271,7 @@ class CodexProbeResult:
268
271
 
269
272
  @property
270
273
  def available(self) -> bool:
271
- return (
272
- self.authenticated
273
- and self.capabilities.supports_bounded_attempts
274
- and self.confinement_verified
275
- )
274
+ return self.authenticated and self.capabilities.supports_bounded_attempts and self.confinement_verified
276
275
 
277
276
 
278
277
  @dataclass(frozen=True)
@@ -310,15 +309,17 @@ class CodexAttempt:
310
309
  with path.open("rb") as source:
311
310
  if source.read(8) != b"\x89PNG\r\n\x1a\n":
312
311
  raise ValueError("image input must be a PNG snapshot")
313
- identity.append({"name": str(path.relative_to(self.workspace.resolve())),
314
- "sha256": sha256_file(path, 2 * 1024**2)})
312
+ identity.append(
313
+ {"name": str(path.relative_to(self.workspace.resolve())), "sha256": sha256_file(path, 2 * 1024**2)}
314
+ )
315
315
  return identity
316
316
 
317
317
  def input_hash(self) -> str:
318
318
  if not self.images:
319
319
  return sha256_bytes(self.prompt.encode("utf-8"))
320
- return sha256_bytes(json.dumps({"prompt": self.prompt, "images": self.image_identity()},
321
- sort_keys=True).encode("utf-8"))
320
+ return sha256_bytes(
321
+ json.dumps({"prompt": self.prompt, "images": self.image_identity()}, sort_keys=True).encode("utf-8")
322
+ )
322
323
 
323
324
 
324
325
  @dataclass(frozen=True)
@@ -419,8 +420,7 @@ class CodexExecAdapter:
419
420
 
420
421
  try:
421
422
  with (
422
- tempfile.TemporaryDirectory(prefix=".permission-probe-", dir=self._attempt_root)
423
- as probe_directory,
423
+ tempfile.TemporaryDirectory(prefix=".permission-probe-", dir=self._attempt_root) as probe_directory,
424
424
  tempfile.TemporaryDirectory(prefix="clipen-denied-") as denied_directory,
425
425
  ):
426
426
  probe_root = Path(probe_directory)
@@ -529,9 +529,7 @@ class CodexExecAdapter:
529
529
  diagnostics_path = workspace / f"provider-diagnostics-{attempt.attempt_id}.log"
530
530
  store = AttemptReceiptStore(workspace, attempt.attempt_id)
531
531
  if store.path.exists() or store.path.is_symlink():
532
- raise ProviderProtocolError(
533
- "Codex attempt already has a receipt; reconcile it instead of rerunning"
534
- )
532
+ raise ProviderProtocolError("Codex attempt already has a receipt; reconcile it instead of rerunning")
535
533
  for artifact in (output_path, events_path, diagnostics_path):
536
534
  if artifact.exists() or artifact.is_symlink():
537
535
  raise ProviderProtocolError("Codex attempt artifact already exists")
@@ -568,9 +566,7 @@ class CodexExecAdapter:
568
566
  diagnostics_path,
569
567
  record_started,
570
568
  )
571
- self._sanitize_persisted_artifacts(
572
- events_path, diagnostics_path, attempt.prompt
573
- )
569
+ self._sanitize_persisted_artifacts(events_path, diagnostics_path, attempt.prompt)
574
570
  stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
575
571
  stderr = self._read_artifact(diagnostics_path, _MAX_CAPTURE_BYTES)
576
572
  self._raise_for_failed_turn(stdout)
@@ -586,32 +582,22 @@ class CodexExecAdapter:
586
582
  return_code=returncode,
587
583
  output_sha256=sha256_file(output_path, _MAX_RESULT_BYTES),
588
584
  events_sha256=sha256_file(events_path, _MAX_CAPTURE_BYTES),
589
- diagnostics_sha256=sha256_file(
590
- diagnostics_path, _MAX_CAPTURE_BYTES
591
- ),
585
+ diagnostics_sha256=sha256_file(diagnostics_path, _MAX_CAPTURE_BYTES),
592
586
  usage=result.usage,
593
587
  )
594
588
  store.write(receipt)
595
589
  return replace(result, elapsed_seconds=time.monotonic() - started)
596
590
  except Exception as error:
597
- self._sanitize_persisted_artifacts(
598
- events_path, diagnostics_path, attempt.prompt
599
- )
591
+ self._sanitize_persisted_artifacts(events_path, diagnostics_path, attempt.prompt)
600
592
  state, error_code = self._failure_receipt(error)
601
593
  receipt = replace(
602
594
  receipt,
603
595
  state=state,
604
596
  finished_at=utc_now(),
605
597
  return_code=returncode,
606
- output_sha256=self._optional_artifact_hash(
607
- output_path, _MAX_RESULT_BYTES
608
- ),
609
- events_sha256=self._optional_artifact_hash(
610
- events_path, _MAX_CAPTURE_BYTES
611
- ),
612
- diagnostics_sha256=self._optional_artifact_hash(
613
- diagnostics_path, _MAX_CAPTURE_BYTES
614
- ),
598
+ output_sha256=self._optional_artifact_hash(output_path, _MAX_RESULT_BYTES),
599
+ events_sha256=self._optional_artifact_hash(events_path, _MAX_CAPTURE_BYTES),
600
+ diagnostics_sha256=self._optional_artifact_hash(diagnostics_path, _MAX_CAPTURE_BYTES),
615
601
  usage=self._optional_usage(events_path),
616
602
  error_code=error_code,
617
603
  )
@@ -638,10 +624,8 @@ class CodexExecAdapter:
638
624
  try:
639
625
  if (
640
626
  receipt.attempt_id != attempt.attempt_id
641
- or receipt.prompt_sha256
642
- != attempt.input_hash()
643
- or receipt.schema_sha256
644
- != sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
627
+ or receipt.prompt_sha256 != attempt.input_hash()
628
+ or receipt.schema_sha256 != sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
645
629
  ):
646
630
  raise AttemptReceiptError("attempt identity does not match its receipt")
647
631
  output_path = workspace / f"provider-output-{attempt.attempt_id}.json"
@@ -655,21 +639,15 @@ class CodexExecAdapter:
655
639
  output_hash = sha256_file(output_path, _MAX_RESULT_BYTES)
656
640
  events_hash = sha256_file(events_path, _MAX_CAPTURE_BYTES)
657
641
  if receipt.state is ProviderAttemptState.SUCCEEDED:
658
- if (
659
- receipt.output_sha256 != output_hash
660
- or receipt.events_sha256 != events_hash
661
- ):
642
+ if receipt.output_sha256 != output_hash or receipt.events_sha256 != events_hash:
662
643
  raise AttemptReceiptError("terminal provider artifacts changed")
663
644
  self._verify_recorded_hash(
664
- workspace
665
- / f"provider-diagnostics-{attempt.attempt_id}.log",
645
+ workspace / f"provider-diagnostics-{attempt.attempt_id}.log",
666
646
  receipt.diagnostics_sha256,
667
647
  _MAX_CAPTURE_BYTES,
668
648
  )
669
649
  else:
670
- diagnostics_path = workspace / (
671
- f"provider-diagnostics-{attempt.attempt_id}.log"
672
- )
650
+ diagnostics_path = workspace / (f"provider-diagnostics-{attempt.attempt_id}.log")
673
651
  receipt = replace(
674
652
  receipt,
675
653
  state=ProviderAttemptState.SUCCEEDED,
@@ -677,9 +655,7 @@ class CodexExecAdapter:
677
655
  return_code=0,
678
656
  output_sha256=output_hash,
679
657
  events_sha256=events_hash,
680
- diagnostics_sha256=self._optional_artifact_hash(
681
- diagnostics_path, _MAX_CAPTURE_BYTES
682
- ),
658
+ diagnostics_sha256=self._optional_artifact_hash(diagnostics_path, _MAX_CAPTURE_BYTES),
683
659
  usage=result.usage,
684
660
  error_code=None,
685
661
  )
@@ -733,10 +709,7 @@ class CodexExecAdapter:
733
709
  "terminal_state_unverified",
734
710
  )
735
711
 
736
-
737
- def _validated_result(
738
- self, attempt: CodexAttempt, output_path: Path, stdout: bytes
739
- ) -> CodexAttemptResult:
712
+ def _validated_result(self, attempt: CodexAttempt, output_path: Path, stdout: bytes) -> CodexAttemptResult:
740
713
  if not output_path.is_file() or output_path.is_symlink():
741
714
  raise ProviderProtocolError("Codex did not create the expected result file")
742
715
  if output_path.stat().st_size > _MAX_RESULT_BYTES:
@@ -772,23 +745,29 @@ class CodexExecAdapter:
772
745
  @staticmethod
773
746
  def _raise_for_failed_turn(stdout: bytes, *, limit: int = _MAX_CAPTURE_BYTES) -> None:
774
747
  """CLI failures can be reported only in JSONL while stderr stays empty."""
775
- events=[]
776
- for line in _decode_capture(stdout,'JSONL stream',limit).splitlines():
777
- try:event=json.loads(line)
778
- except json.JSONDecodeError:continue # Normal protocol validation follows.
779
- if isinstance(event,dict):events.append(event)
780
- terminal=next((e for e in reversed(events) if e.get('type') in {'turn.completed','turn.failed'}),None)
781
- if terminal is not None and terminal.get('type')=='turn.completed':return
782
- messages=[]
748
+ events = []
749
+ for line in _decode_capture(stdout, "JSONL stream", limit).splitlines():
750
+ try:
751
+ event = json.loads(line)
752
+ except json.JSONDecodeError:
753
+ continue # Normal protocol validation follows.
754
+ if isinstance(event, dict):
755
+ events.append(event)
756
+ terminal = next((e for e in reversed(events) if e.get("type") in {"turn.completed", "turn.failed"}), None)
757
+ if terminal is not None and terminal.get("type") == "turn.completed":
758
+ return
759
+ messages = []
783
760
  for event in events:
784
- if event.get('type') not in {'error','turn.failed'}:continue
785
- detail=event.get('error',event)
786
- message=detail.get('message') if isinstance(detail,dict) else detail
787
- if isinstance(message,str):messages.append(message)
761
+ if event.get("type") not in {"error", "turn.failed"}:
762
+ continue
763
+ detail = event.get("error", event)
764
+ message = detail.get("message") if isinstance(detail, dict) else detail
765
+ if isinstance(message, str):
766
+ messages.append(message)
788
767
  if messages:
789
- CodexExecAdapter._raise_for_exit(1,'\n'.join(messages).encode('utf-8'))
768
+ CodexExecAdapter._raise_for_exit(1, "\n".join(messages).encode("utf-8"))
790
769
  if terminal is not None:
791
- raise ProviderProtocolError('Codex reported a failed turn without a diagnostic')
770
+ raise ProviderProtocolError("Codex reported a failed turn without a diagnostic")
792
771
 
793
772
  @staticmethod
794
773
  def _raise_for_exit(returncode: int, stderr: bytes) -> None:
@@ -798,8 +777,7 @@ class CodexExecAdapter:
798
777
  if any(marker in diagnostic for marker in ("usage limit", "rate limit", "quota", "credits")):
799
778
  raise ProviderUsageLimitError("Codex account usage limit prevented this attempt")
800
779
  if any(
801
- marker in diagnostic
802
- for marker in ("connection failed", "network is unreachable", "could not resolve host")
780
+ marker in diagnostic for marker in ("connection failed", "network is unreachable", "could not resolve host")
803
781
  ):
804
782
  raise ProviderNetworkError("Codex could not reach its service")
805
783
  if any(marker in diagnostic for marker in ("sandbox", "operation not permitted", "permission")):
@@ -824,13 +802,9 @@ class CodexExecAdapter:
824
802
  with tempfile.TemporaryFile() as prompt_stream:
825
803
  prompt_stream.write(self._stdin_payload(attempt))
826
804
  prompt_stream.seek(0)
827
- stdout_descriptor = os.open(
828
- events_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
829
- )
805
+ stdout_descriptor = os.open(events_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
830
806
  try:
831
- stderr_descriptor = os.open(
832
- diagnostics_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
833
- )
807
+ stderr_descriptor = os.open(diagnostics_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
834
808
  except Exception:
835
809
  os.close(stdout_descriptor)
836
810
  raise
@@ -855,22 +829,16 @@ class CodexExecAdapter:
855
829
  while process.poll() is None:
856
830
  if cancel_token is not None and cancel_token.is_set():
857
831
  self._terminate(process)
858
- raise ProviderCancelled(
859
- f"Codex attempt {attempt.attempt_id} was cancelled"
860
- )
832
+ raise ProviderCancelled(f"Codex attempt {attempt.attempt_id} was cancelled")
861
833
  if time.monotonic() >= deadline:
862
834
  self._terminate(process)
863
- raise ProviderTimedOut(
864
- f"Codex attempt {attempt.attempt_id} exceeded its timeout"
865
- )
835
+ raise ProviderTimedOut(f"Codex attempt {attempt.attempt_id} exceeded its timeout")
866
836
  if (
867
837
  os.fstat(stdout_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
868
838
  or os.fstat(stderr_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
869
839
  ):
870
840
  self._terminate(process)
871
- raise ProviderProtocolError(
872
- "Codex diagnostic output exceeded the capture limit"
873
- )
841
+ raise ProviderProtocolError("Codex diagnostic output exceeded the capture limit")
874
842
  time.sleep(_POLL_INTERVAL_SECONDS)
875
843
 
876
844
  stdout_stream.flush()
@@ -882,7 +850,8 @@ class CodexExecAdapter:
882
850
  @staticmethod
883
851
  def _events_and_usage(
884
852
  stdout: bytes,
885
- *, limit: int = _MAX_CAPTURE_BYTES,
853
+ *,
854
+ limit: int = _MAX_CAPTURE_BYTES,
886
855
  ) -> tuple[tuple[str, ...], ProviderUsage | None]:
887
856
  event_types: list[str] = []
888
857
  usage: ProviderUsage | None = None
@@ -900,29 +869,21 @@ class CodexExecAdapter:
900
869
  if isinstance(event_type, str) and event_type:
901
870
  event_types.append(event_type)
902
871
  candidate_usage = event.get("usage")
903
- if event_type in {"turn.completed", "turn.failed"} and isinstance(
904
- candidate_usage, dict
905
- ):
872
+ if event_type in {"turn.completed", "turn.failed"} and isinstance(candidate_usage, dict):
906
873
  try:
907
874
  usage = ProviderUsage(
908
875
  input_tokens=candidate_usage["input_tokens"],
909
- cached_input_tokens=candidate_usage.get(
910
- "cached_input_tokens", 0
911
- ),
876
+ cached_input_tokens=candidate_usage.get("cached_input_tokens", 0),
912
877
  output_tokens=candidate_usage["output_tokens"],
913
878
  )
914
879
  except (KeyError, TypeError, ValueError) as error:
915
- raise ProviderProtocolError(
916
- "Codex usage data was malformed"
917
- ) from error
880
+ raise ProviderProtocolError("Codex usage data was malformed") from error
918
881
  return tuple(event_types), usage
919
882
 
920
883
  @classmethod
921
884
  def _optional_usage(cls, path: Path) -> ProviderUsage | None:
922
885
  try:
923
- _, usage = cls._events_and_usage(
924
- cls._read_artifact(path, _MAX_CAPTURE_BYTES)
925
- )
886
+ _, usage = cls._events_and_usage(cls._read_artifact(path, _MAX_CAPTURE_BYTES))
926
887
  return usage
927
888
  except (OSError, ProviderProtocolError):
928
889
  return None
@@ -944,9 +905,7 @@ class CodexExecAdapter:
944
905
  return None
945
906
 
946
907
  @staticmethod
947
- def _sanitize_persisted_artifacts(
948
- events_path: Path, diagnostics_path: Path, prompt: str
949
- ) -> None:
908
+ def _sanitize_persisted_artifacts(events_path: Path, diagnostics_path: Path, prompt: str) -> None:
950
909
  prompt_bytes = prompt.encode("utf-8")
951
910
  for path in (events_path, diagnostics_path):
952
911
  if path.is_symlink() or not path.is_file():
@@ -964,9 +923,7 @@ class CodexExecAdapter:
964
923
  if sanitized == value:
965
924
  continue
966
925
  temporary = path.with_name(f".{path.name}.redacted-{uuid.uuid4().hex}")
967
- descriptor = os.open(
968
- temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
969
- )
926
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
970
927
  try:
971
928
  with os.fdopen(descriptor, "wb") as stream:
972
929
  stream.write(sanitized)
@@ -979,9 +936,7 @@ class CodexExecAdapter:
979
936
  temporary.unlink()
980
937
 
981
938
  @staticmethod
982
- def _verify_recorded_hash(
983
- path: Path, expected: str | None, limit: int
984
- ) -> None:
939
+ def _verify_recorded_hash(path: Path, expected: str | None, limit: int) -> None:
985
940
  if expected is None:
986
941
  return
987
942
  if sha256_file(path, limit) != expected:
@@ -3,8 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
- from pathlib import Path
7
6
  import tempfile
7
+ from pathlib import Path
8
8
  from typing import Mapping
9
9
 
10
10
  from .codex import (
@@ -73,7 +73,7 @@ class CodexEditingAgent(BoundedEditingAgent):
73
73
  "-c",
74
74
  "mcp_servers.clipen.tool_timeout_sec=600",
75
75
  "-c",
76
- "mcp_servers.clipen.default_tools_approval_mode=\"approve\"",
76
+ 'mcp_servers.clipen.default_tools_approval_mode="approve"',
77
77
  "-c",
78
78
  f"mcp_servers.clipen.enabled_tools={json.dumps(_MCP_TOOLS)}",
79
79
  *model_config(self.binary, self.environment),
@@ -7,9 +7,7 @@ completion, usage and failures.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- from dataclasses import dataclass
11
10
  import os
12
- from pathlib import Path
13
11
  import shutil
14
12
  import signal
15
13
  import subprocess
@@ -17,8 +15,10 @@ import sys
17
15
  import tempfile
18
16
  import threading
19
17
  import time
20
- from typing import Mapping
21
18
  import uuid
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Mapping
22
22
 
23
23
  from clipen.editing.agent import AgentRun, EditAgentRepository
24
24
  from clipen.editing.production_catalog import AGENT_NAMES
@@ -37,7 +37,6 @@ from .errors import (
37
37
  ProviderUsageLimitError,
38
38
  )
39
39
 
40
-
41
40
  # JSON events include the bounded MCP thumbnails returned to the model, and
42
41
  # Claude's stream repeats each tool result (images included) a second time. A
43
42
  # real Claude revision with ~90 previews reached 34 MB, so leave room for a long
@@ -292,7 +291,7 @@ def mcp_server_arguments(
292
291
  run_id,
293
292
  ]
294
293
  if local_runtime:
295
- args += ['--data-root',str(local_runtime[0]),'--asr-requirements',str(local_runtime[1])]
294
+ args += ["--data-root", str(local_runtime[0]), "--asr-requirements", str(local_runtime[1])]
296
295
  return args
297
296
 
298
297
 
@@ -313,8 +312,12 @@ def keep_awake(pid: int) -> subprocess.Popen[bytes] | None:
313
312
  if sys.platform != "darwin" or not os.access(_CAFFEINATE, os.X_OK):
314
313
  return None
315
314
  try:
316
- return subprocess.Popen([_CAFFEINATE, "-i", "-s", "-w", str(pid)], stdin=subprocess.DEVNULL,
317
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
315
+ return subprocess.Popen(
316
+ [_CAFFEINATE, "-i", "-s", "-w", str(pid)],
317
+ stdin=subprocess.DEVNULL,
318
+ stdout=subprocess.DEVNULL,
319
+ stderr=subprocess.DEVNULL,
320
+ )
318
321
  except OSError:
319
322
  return None
320
323
 
@@ -361,9 +364,7 @@ class BoundedEditingAgent:
361
364
  def provider_environment(self, source: Mapping[str, str] | None) -> dict[str, str]:
362
365
  raise NotImplementedError
363
366
 
364
- def command(
365
- self, project_id: str, run_id: str, workspace: Path, output_path: Path
366
- ) -> tuple[str, ...]:
367
+ def command(self, project_id: str, run_id: str, workspace: Path, output_path: Path) -> tuple[str, ...]:
367
368
  raise NotImplementedError
368
369
 
369
370
  def events_and_usage(self, stdout: bytes) -> tuple[tuple[str, ...], ProviderUsage | None]:
@@ -385,7 +386,7 @@ class BoundedEditingAgent:
385
386
  ) -> EditingResult:
386
387
  session = self.repository.production_session(project_id, run_id)
387
388
  if timeout_seconds is None:
388
- target = session['intent'].get('target_duration_seconds', 60) if session else 60
389
+ target = session["intent"].get("target_duration_seconds", 60) if session else 60
389
390
  # Include discovery, local evidence, rendering and revision review.
390
391
  # The legacy 20-minute wall clock killed actively progressing films.
391
392
  timeout_seconds = min(14400, max(3600, target * 12 + 1200)) if target > 75 else 1200
@@ -425,7 +426,8 @@ class BoundedEditingAgent:
425
426
  blockers = self.repository.delivery_blockers(project_id, run_id)
426
427
  if blockers:
427
428
  raise ProviderDeliveryBlocked(
428
- f"{self.display_name} stopped with failing delivery checks: {', '.join(blockers)}")
429
+ f"{self.display_name} stopped with failing delivery checks: {', '.join(blockers)}"
430
+ )
429
431
  raise ProviderStoppedEarly(f"{self.display_name} exited without finishing the Clipen edit")
430
432
  final = self.repository.record_provider_outcome(
431
433
  project_id,
@@ -460,7 +462,7 @@ class BoundedEditingAgent:
460
462
  deadline = time.monotonic() + timeout_seconds
461
463
  name = self.display_name
462
464
  with tempfile.TemporaryFile() as prompt:
463
- prompt.write(getattr(self, '_prompt', _PROMPT).encode("utf-8"))
465
+ prompt.write(getattr(self, "_prompt", _PROMPT).encode("utf-8"))
464
466
  prompt.seek(0)
465
467
  with events.open("xb") as stdout, diagnostics.open("xb") as stderr:
466
468
  process = subprocess.Popen(
@@ -543,13 +545,13 @@ class BoundedEditingAgent:
543
545
  @staticmethod
544
546
  def _error_code(error: Exception) -> str:
545
547
  if isinstance(error, ProviderUsageLimitError):
546
- return 'provider_usage_limit'
548
+ return "provider_usage_limit"
547
549
  if isinstance(error, ProviderAuthenticationError):
548
- return 'provider_authentication_required'
550
+ return "provider_authentication_required"
549
551
  if isinstance(error, ProviderNetworkError):
550
- return 'provider_network_error'
552
+ return "provider_network_error"
551
553
  if isinstance(error, ProviderPermissionError):
552
- return 'provider_permission_error'
554
+ return "provider_permission_error"
553
555
  if isinstance(error, ProviderCancelled):
554
556
  return "provider_cancelled"
555
557
  if isinstance(error, ProviderTimedOut):
@@ -2,15 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
- from datetime import datetime, timezone
7
- from enum import Enum
8
5
  import hashlib
9
6
  import json
10
7
  import os
11
- from pathlib import Path
12
8
  import uuid
13
-
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from enum import Enum
12
+ from pathlib import Path
14
13
 
15
14
  _RECEIPT_SCHEMA = 1
16
15
  _MAX_RECEIPT_BYTES = 64 * 1024
@@ -232,9 +231,9 @@ class AttemptReceiptStore:
232
231
  def write(self, receipt: ProviderAttemptReceipt) -> None:
233
232
  if self.path.is_symlink():
234
233
  raise AttemptReceiptError("provider attempt receipt cannot be a symbolic link")
235
- encoded = json.dumps(
236
- receipt.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":")
237
- ).encode("utf-8")
234
+ encoded = json.dumps(receipt.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode(
235
+ "utf-8"
236
+ )
238
237
  if len(encoded) > _MAX_RECEIPT_BYTES:
239
238
  raise AttemptReceiptError("provider attempt receipt exceeds its size limit")
240
239
  temporary = self.workspace / f".receipt-{receipt.attempt_id}-{uuid.uuid4().hex}"
@@ -3,10 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
- from pathlib import Path
7
6
  import secrets
8
7
  import shutil
9
8
  import subprocess
9
+ from pathlib import Path
10
10
 
11
11
  from clipen.media import MediaPreviewRepository
12
12
  from clipen.projects import ProjectError, ProjectRepository
@@ -14,7 +14,6 @@ from clipen.projects.models import validate_project_id
14
14
 
15
15
  from .storage import PreviewRenderRepository
16
16
 
17
-
18
17
  # Far enough in to skip a black fade-in, then the very first frame for clips shorter than that.
19
18
  _STILL_OFFSETS = (3.0, 0.0)
20
19
  _SOURCE_CANDIDATES = 20
@@ -104,9 +103,23 @@ class ProjectCoverRepository:
104
103
 
105
104
  def _cut(self, media: Path, offset: float, output: Path) -> bool:
106
105
  command = (
107
- self.executable, "-nostdin", "-hide_banner", "-loglevel", "error",
108
- "-ss", f"{offset:.3f}", "-i", str(media),
109
- "-frames:v", "1", "-vf", "scale=640:-2", "-q:v", "4", "-y", str(output),
106
+ self.executable,
107
+ "-nostdin",
108
+ "-hide_banner",
109
+ "-loglevel",
110
+ "error",
111
+ "-ss",
112
+ f"{offset:.3f}",
113
+ "-i",
114
+ str(media),
115
+ "-frames:v",
116
+ "1",
117
+ "-vf",
118
+ "scale=640:-2",
119
+ "-q:v",
120
+ "4",
121
+ "-y",
122
+ str(output),
110
123
  )
111
124
  try:
112
125
  completed = subprocess.run(