@clipen/clipen-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +52 -4
  11. package/pyproject.toml +28 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/runtime.txt +20 -0
  14. package/src/clipen/__init__.py +3 -0
  15. package/src/clipen/analysis/__init__.py +89 -0
  16. package/src/clipen/analysis/artifacts.py +416 -0
  17. package/src/clipen/analysis/audio.py +392 -0
  18. package/src/clipen/analysis/evidence.py +102 -0
  19. package/src/clipen/analysis/evidence_service.py +751 -0
  20. package/src/clipen/analysis/image_similarity.py +143 -0
  21. package/src/clipen/analysis/keyframes.py +171 -0
  22. package/src/clipen/analysis/models.py +230 -0
  23. package/src/clipen/analysis/qwen_worker.py +629 -0
  24. package/src/clipen/analysis/resources.py +21 -0
  25. package/src/clipen/analysis/runtime.py +64 -0
  26. package/src/clipen/analysis/service.py +626 -0
  27. package/src/clipen/analysis/setup.py +935 -0
  28. package/src/clipen/analysis/setup_cli.py +117 -0
  29. package/src/clipen/analysis/storage.py +2046 -0
  30. package/src/clipen/analysis/transcription.py +948 -0
  31. package/src/clipen/analysis/visual.py +176 -0
  32. package/src/clipen/annotations/__init__.py +10 -0
  33. package/src/clipen/annotations/models.py +22 -0
  34. package/src/clipen/annotations/storage.py +380 -0
  35. package/src/clipen/annotations/suggestions.py +120 -0
  36. package/src/clipen/asr_release.py +139 -0
  37. package/src/clipen/bootstrap.py +967 -0
  38. package/src/clipen/cli.py +84 -0
  39. package/src/clipen/controller/__init__.py +17 -0
  40. package/src/clipen/controller/app.py +1470 -0
  41. package/src/clipen/controller/server.py +543 -0
  42. package/src/clipen/domain/__init__.py +30 -0
  43. package/src/clipen/domain/errors.py +5 -0
  44. package/src/clipen/domain/media_time.py +117 -0
  45. package/src/clipen/domain/timeline.py +584 -0
  46. package/src/clipen/domain/validation.py +15 -0
  47. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  48. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  49. package/src/clipen/editing/README.md +115 -0
  50. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  51. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  52. package/src/clipen/editing/__init__.py +15 -0
  53. package/src/clipen/editing/agent.py +13 -0
  54. package/src/clipen/editing/agent_models.py +134 -0
  55. package/src/clipen/editing/agent_repository.py +757 -0
  56. package/src/clipen/editing/agent_tools.py +532 -0
  57. package/src/clipen/editing/alignment.py +110 -0
  58. package/src/clipen/editing/alignment_setup.py +108 -0
  59. package/src/clipen/editing/alignment_worker.py +22 -0
  60. package/src/clipen/editing/change_report.py +71 -0
  61. package/src/clipen/editing/compiler.py +41 -0
  62. package/src/clipen/editing/component_looks.py +107 -0
  63. package/src/clipen/editing/component_review.py +78 -0
  64. package/src/clipen/editing/coordinator.py +374 -0
  65. package/src/clipen/editing/editorial_review.py +187 -0
  66. package/src/clipen/editing/evidence_jobs.py +295 -0
  67. package/src/clipen/editing/history_changes.py +131 -0
  68. package/src/clipen/editing/music_choices.py +15 -0
  69. package/src/clipen/editing/production_catalog.py +192 -0
  70. package/src/clipen/editing/production_limits.py +59 -0
  71. package/src/clipen/editing/production_media.py +226 -0
  72. package/src/clipen/editing/production_preview.py +180 -0
  73. package/src/clipen/editing/production_progress.py +141 -0
  74. package/src/clipen/editing/production_requirements.py +50 -0
  75. package/src/clipen/editing/production_tools.py +596 -0
  76. package/src/clipen/editing/program_audio.py +118 -0
  77. package/src/clipen/editing/program_direction.py +49 -0
  78. package/src/clipen/editing/program_story.py +53 -0
  79. package/src/clipen/editing/program_subtitles.py +134 -0
  80. package/src/clipen/editing/programme_review.py +73 -0
  81. package/src/clipen/editing/prompt_history.py +47 -0
  82. package/src/clipen/editing/recut.py +127 -0
  83. package/src/clipen/editing/refinement_references.py +188 -0
  84. package/src/clipen/editing/resolve_export.py +616 -0
  85. package/src/clipen/editing/resolve_titles.py +234 -0
  86. package/src/clipen/editing/skill_tools.py +575 -0
  87. package/src/clipen/editing/source_dialogue.py +82 -0
  88. package/src/clipen/editing/speech_coverage.py +30 -0
  89. package/src/clipen/editing/speech_quality.py +6 -0
  90. package/src/clipen/editing/tool_receipts.py +52 -0
  91. package/src/clipen/editing/versions.py +161 -0
  92. package/src/clipen/editing/visual_preview.py +93 -0
  93. package/src/clipen/editing/workbench.py +74 -0
  94. package/src/clipen/filesystem.py +25 -0
  95. package/src/clipen/finishing/README.md +103 -0
  96. package/src/clipen/finishing/__init__.py +1 -0
  97. package/src/clipen/finishing/audio.py +149 -0
  98. package/src/clipen/finishing/catalog.py +181 -0
  99. package/src/clipen/finishing/models.py +14 -0
  100. package/src/clipen/finishing/renderer.py +26 -0
  101. package/src/clipen/mcp_editing/__init__.py +5 -0
  102. package/src/clipen/mcp_editing/__main__.py +40 -0
  103. package/src/clipen/mcp_editing/server.py +353 -0
  104. package/src/clipen/media/__init__.py +50 -0
  105. package/src/clipen/media/discovery.py +266 -0
  106. package/src/clipen/media/models.py +360 -0
  107. package/src/clipen/media/preview.py +147 -0
  108. package/src/clipen/media/probe.py +446 -0
  109. package/src/clipen/media/service.py +317 -0
  110. package/src/clipen/media/storage.py +742 -0
  111. package/src/clipen/music_vocabulary.py +5 -0
  112. package/src/clipen/planning/__init__.py +9 -0
  113. package/src/clipen/planning/models.py +240 -0
  114. package/src/clipen/power.py +23 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +269 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +34 -0
  121. package/src/clipen/projects/models.py +192 -0
  122. package/src/clipen/projects/picker.py +256 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +175 -0
  125. package/src/clipen/projects/storage.py +1478 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +75 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +194 -0
  131. package/src/clipen/providers/claude.py +375 -0
  132. package/src/clipen/providers/claude_editing.py +111 -0
  133. package/src/clipen/providers/codex.py +1036 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +565 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +270 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +126 -0
  141. package/src/clipen/rendering/custom_components.py +240 -0
  142. package/src/clipen/rendering/custom_render.py +197 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +64 -0
  158. package/src/clipen/rendering/program_components.py +193 -0
  159. package/src/clipen/rendering/program_creator.py +649 -0
  160. package/src/clipen/rendering/program_identities.py +255 -0
  161. package/src/clipen/rendering/program_motion.py +141 -0
  162. package/src/clipen/rendering/program_studio.py +168 -0
  163. package/src/clipen/rendering/program_styles.py +235 -0
  164. package/src/clipen/rendering/program_subtitles.py +52 -0
  165. package/src/clipen/rendering/renderer.py +708 -0
  166. package/src/clipen/rendering/storage.py +243 -0
  167. package/src/clipen/rendering/titles.py +360 -0
  168. package/src/clipen/skills/__init__.py +4 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +218 -0
  228. package/src/clipen/skills/library.py +131 -0
  229. package/src/clipen/skills/package.py +231 -0
  230. package/src/clipen/skills/visual_styles.py +44 -0
  231. package/src/clipen/workspace.py +210 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,353 @@
1
+ """Minimal MCP stdio adapter over Clipen's allowlisted editing tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from copy import deepcopy
7
+ from io import BytesIO
8
+ import json
9
+ from pathlib import Path
10
+ import sys
11
+ from typing import BinaryIO, Mapping
12
+
13
+ from clipen.editing import EditAgentTools, ToolResult
14
+ from clipen.projects import ProjectError
15
+ from clipen.editing.production_catalog import AGENT_TOOLS
16
+ from clipen.editing.tool_receipts import TIMELINE_MUTATIONS
17
+
18
+
19
+ _MAX_MESSAGE_BYTES = 1024 * 1024
20
+ _MAX_IMAGE_BYTES = 96 * 1024
21
+ _MAX_IMAGE_SIZE = (640, 360)
22
+ _PROTOCOL_VERSION = "2025-06-18"
23
+
24
+
25
+ def _tool(
26
+ name: str,
27
+ description: str,
28
+ properties: Mapping[str, object],
29
+ required: tuple[str, ...] = (),
30
+ ) -> dict[str, object]:
31
+ schema: dict[str, object] = {
32
+ "type": "object",
33
+ "properties": dict(properties),
34
+ "additionalProperties": False,
35
+ }
36
+ if required:
37
+ schema["required"] = list(required)
38
+ return {"name": name, "description": description, "inputSchema": schema}
39
+
40
+
41
+ _TOOLS = (
42
+ _tool(
43
+ "get_edit_status",
44
+ "Read the run state, bounded budget, and authoritative user-confirmed edit direction.",
45
+ {},
46
+ ),
47
+ _tool(
48
+ "search_media",
49
+ "Search path-free candidate clips from the current approved material snapshot.",
50
+ {
51
+ "query": {"type": "string", "maxLength": 200},
52
+ "limit": {"type": "integer", "minimum": 1, "maximum": 50},
53
+ "offset": {"type":"integer","minimum":0,"maximum":100000},
54
+ },
55
+ ),
56
+ _tool(
57
+ "inspect_clip",
58
+ "Inspect one candidate's source-bound evidence and up to four local sample images.",
59
+ {"candidate_id": {"type": "string"}},
60
+ ("candidate_id",),
61
+ ),
62
+ _tool(
63
+ "inspect_sequence",
64
+ "Read the current immutable timeline revision. Long films return an outline; then read parts with "
65
+ "track (video, title or audio) and/or from_seconds/to_seconds.",
66
+ {
67
+ "track": {"type": "string", "enum": ["video", "title", "audio"]},
68
+ "from_seconds": {"type": "number", "minimum": 0},
69
+ "to_seconds": {"type": "number", "minimum": 0},
70
+ },
71
+ ),
72
+ _tool(
73
+ "replace_sequence",
74
+ "Build the short style proof from precise in/out ranges inside approved candidates.",
75
+ {
76
+ "clips": {
77
+ "type": "array",
78
+ "items": {
79
+ "type": "object",
80
+ "properties": {
81
+ "candidate_id": {"type": "string"},
82
+ "start_offset_seconds": {"type": "number", "minimum": 0},
83
+ "duration_seconds": {
84
+ "type": "number",
85
+ "minimum": 0.75,
86
+ "maximum": 30,
87
+ },
88
+ },
89
+ "required": [
90
+ "candidate_id",
91
+ "start_offset_seconds",
92
+ "duration_seconds",
93
+ ],
94
+ "additionalProperties": False,
95
+ },
96
+ "minItems": 1,
97
+ "maxItems": 180,
98
+ },
99
+ "summary": {"type": "string", "maxLength": 500},
100
+ "reprise_reason": {"type":"string","minLength":1,"maxLength":500,"description":"Explicit editorial reason for intentionally repeating a source range as a cold open/callback. Without this, duplicate source ranges are rejected."},
101
+ },
102
+ ("clips", "summary"),
103
+ ),
104
+ _tool(
105
+ "set_clip_effect",
106
+ "Set one semantic effect on an existing media clip; exporters map it safely.",
107
+ {
108
+ "item_id": {"type": "string"},
109
+ "effect_id": {
110
+ "type": "string",
111
+ "enum": [
112
+ "video.punch_in",
113
+ "video.slow_push",
114
+ "video.reframe",
115
+ "video.speed_ramp",
116
+ ],
117
+ },
118
+ "parameters": {
119
+ "type": "object",
120
+ "description": (
121
+ "Use {} for safe defaults, or exact numeric keys: "
122
+ "punch_in {scale,center_x,center_y}; slow_push "
123
+ "{scale_from,scale_to}; reframe {x,y}; speed_ramp {rate}."
124
+ ),
125
+ "properties": {
126
+ "scale": {"type": "number", "minimum": 1.01, "maximum": 2},
127
+ "center_x": {"type": "number", "minimum": 0, "maximum": 1},
128
+ "center_y": {"type": "number", "minimum": 0, "maximum": 1},
129
+ "scale_from": {"type": "number", "minimum": 1, "maximum": 2},
130
+ "scale_to": {"type": "number", "minimum": 1, "maximum": 2},
131
+ "x": {"type": "number", "minimum": 0, "maximum": 1},
132
+ "y": {"type": "number", "minimum": 0, "maximum": 1},
133
+ "rate": {"type": "number", "minimum": 0.25, "maximum": 4},
134
+ },
135
+ "additionalProperties": False,
136
+ },
137
+ "summary": {"type": "string", "maxLength": 500},
138
+ },
139
+ ("item_id", "effect_id", "parameters", "summary"),
140
+ ),
141
+ _tool("undo_revision", "Select the parent of the current immutable revision.", {}),
142
+ _tool(
143
+ "finish_edit",
144
+ "Finish this bounded run and freeze its selected final revision, with the change report the person reads: "
145
+ "summary (what this version is now, in plain words), changes (what you changed and why, as a viewer would put it), "
146
+ "notes (one answer per review note the person sent: reference_id, outcome done/partly/not_done/kept, explanation) "
147
+ "and not_done. Anything your tools can do is done before finishing, never left in not_done. not_done and a "
148
+ "partly/not_done note need reason needs_you (detail: what the person must decide or supply) or cannot "
149
+ "(detail: which tool limit stops it). Do not list limits that hold every time, such as not hearing audio.",
150
+ {"summary": {"type": "string", "maxLength": 1000},
151
+ "changes": {"type": "array", "minItems": 1, "maxItems": 20, "items": {"type": "object", "properties": {
152
+ "what": {"type": "string", "maxLength": 200}, "why": {"type": "string", "maxLength": 300}}, "required": ["what", "why"], "additionalProperties": False}},
153
+ "notes": {"type": "array", "maxItems": 40, "items": {"type": "object", "properties": {
154
+ "reference_id": {"type": "string", "maxLength": 160}, "outcome": {"enum": ["done", "partly", "not_done", "kept"]},
155
+ "explanation": {"type": "string", "maxLength": 300}, "reason": {"enum": ["needs_you", "cannot"]}},
156
+ "required": ["reference_id", "outcome", "explanation"], "additionalProperties": False}},
157
+ "not_done": {"type": "array", "maxItems": 10, "items": {"type": "object", "properties": {
158
+ "what": {"type": "string", "maxLength": 200}, "reason": {"enum": ["needs_you", "cannot"]},
159
+ "detail": {"type": "string", "maxLength": 300}}, "required": ["what", "reason", "detail"], "additionalProperties": False}}},
160
+ ("summary", "changes"),
161
+ ),
162
+ ) + AGENT_TOOLS
163
+ _TOOL_NAMES = frozenset(entry['name'] for entry in _TOOLS)
164
+
165
+ # The same optional compare-and-swap guard applies to every independent tool.
166
+ # Tools strip it before domain argument validation; actual revision writes also
167
+ # check inside the SQLite transaction.
168
+ for _entry in _TOOLS:
169
+ if _entry['name'] in TIMELINE_MUTATIONS:
170
+ _entry['inputSchema']['properties']['expected_revision_id'] = {
171
+ 'type':'string', 'pattern':'^editrev_[0-9a-f]{32}$',
172
+ 'description':'Current revision guard. A stale value fails without overwriting newer edits.'}
173
+ _entry['inputSchema']['properties']['mutation_id'] = {'type':'string','minLength':1,'maxLength':160,
174
+ 'description':'Unique operation key; reuse with identical arguments only when retrying the same operation.'}
175
+
176
+
177
+ class EditingMcpServer:
178
+ """Handle MCP JSON-RPC without exposing a shell, resources, or arbitrary files."""
179
+
180
+ def __init__(self, tools: EditAgentTools) -> None:
181
+ self.tools = tools
182
+
183
+ def start(self) -> None:
184
+ self.tools.activate()
185
+
186
+ def handle(self, message: object) -> dict[str, object] | None:
187
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
188
+ return self._error(None, -32600, "Invalid Request")
189
+ identifier = message.get("id")
190
+ method = message.get("method")
191
+ if not isinstance(method, str):
192
+ return self._error(identifier, -32600, "Invalid Request")
193
+ if identifier is None:
194
+ return None
195
+ params = message.get("params", {})
196
+ if method == "initialize":
197
+ return self._result(
198
+ identifier,
199
+ {
200
+ "protocolVersion": _PROTOCOL_VERSION,
201
+ "capabilities": {"tools": {"listChanged": False}},
202
+ "serverInfo": {"name": "clipen-editing", "version": "0.1.0"},
203
+ "instructions": (
204
+ "Start with get_edit_status. For skill_production read the frozen "
205
+ "SKILL.md through read_production_skill and explore authorized sources. "
206
+ "You decide the workflow; keep source media immutable and inspect results."
207
+ ),
208
+ },
209
+ )
210
+ if method == "ping":
211
+ return self._result(identifier, {})
212
+ if method == "tools/list":
213
+ entries=deepcopy(list(_TOOLS))
214
+ for entry in entries:
215
+ if entry['name'] in TIMELINE_MUTATIONS:
216
+ # Rebind instead of extending: tools may share one required
217
+ # list, and duplicates make the schema invalid for strict providers.
218
+ required=entry['inputSchema'].get('required',[])
219
+ entry['inputSchema']['required']=required+[k for k in ('expected_revision_id','mutation_id') if k not in required]
220
+ return self._result(identifier, {"tools": entries})
221
+ if method == "tools/call":
222
+ return self._call_tool(identifier, params)
223
+ return self._error(identifier, -32601, "Method not found")
224
+
225
+ def _call_tool(self, identifier: object, params: object) -> dict[str, object]:
226
+ if not isinstance(params, dict) or not isinstance(params.get("name"), str):
227
+ return self._error(identifier, -32602, "Invalid params")
228
+ if params["name"] not in _TOOL_NAMES:
229
+ # Only listed tools reach Clipen, even if the model guesses another name.
230
+ return self._error(identifier, -32602, "Unknown tool")
231
+ arguments = params.get("arguments", {})
232
+ try:
233
+ result = self.tools.call(params["name"], arguments)
234
+ except ProjectError as error:
235
+ return self._result(
236
+ identifier,
237
+ {
238
+ "content": [
239
+ {
240
+ "type": "text",
241
+ "text": json.dumps(
242
+ {"error": error.code, "message": error.message},
243
+ ensure_ascii=False,
244
+ ),
245
+ }
246
+ ],
247
+ "isError": True,
248
+ },
249
+ )
250
+ except (TypeError, ValueError) as error:
251
+ return self._result(
252
+ identifier,
253
+ {
254
+ "content": [
255
+ {
256
+ "type": "text",
257
+ "text": json.dumps(
258
+ {"error": "agent_input_invalid", "message": str(error)},
259
+ ensure_ascii=False,
260
+ ),
261
+ }
262
+ ],
263
+ "isError": True,
264
+ },
265
+ )
266
+ return self._result(identifier, self._content(result))
267
+
268
+ @staticmethod
269
+ def _content(result: ToolResult) -> dict[str, object]:
270
+ content: list[dict[str, object]] = [
271
+ {"type": "text", "text": json.dumps(result.payload, ensure_ascii=False)}
272
+ ]
273
+ for path in result.images:
274
+ encoded = _bounded_image(path)
275
+ if encoded is None:
276
+ continue
277
+ data, mime = encoded
278
+ content.append(
279
+ {
280
+ "type": "image",
281
+ "data": base64.b64encode(data).decode("ascii"),
282
+ "mimeType": mime,
283
+ }
284
+ )
285
+ return {"content": content, "isError": False}
286
+
287
+ @staticmethod
288
+ def _result(identifier: object, value: object) -> dict[str, object]:
289
+ return {"jsonrpc": "2.0", "id": identifier, "result": value}
290
+
291
+ @staticmethod
292
+ def _error(identifier: object, code: int, message: str) -> dict[str, object]:
293
+ return {
294
+ "jsonrpc": "2.0",
295
+ "id": identifier,
296
+ "error": {"code": code, "message": message},
297
+ }
298
+
299
+
300
+ def _bounded_image(path: Path) -> tuple[bytes, str] | None:
301
+ """Encode a model-readable thumbnail without modifying the evidence artifact."""
302
+
303
+ try:
304
+ from PIL import Image
305
+
306
+ with Image.open(path) as source:
307
+ image = source.convert("RGB")
308
+ for size in (_MAX_IMAGE_SIZE, (480, 270), (320, 180)):
309
+ image.thumbnail(size, Image.Resampling.LANCZOS)
310
+ for quality in (76, 60, 44):
311
+ output = BytesIO()
312
+ image.save(output, "JPEG", quality=quality, optimize=True)
313
+ data = output.getvalue()
314
+ if len(data) <= _MAX_IMAGE_BYTES:
315
+ return data, "image/jpeg"
316
+ return None
317
+ except (ImportError, OSError, ValueError):
318
+ try:
319
+ if path.stat().st_size > _MAX_IMAGE_BYTES:
320
+ return None
321
+ data = path.read_bytes()
322
+ except OSError:
323
+ return None
324
+ suffix = path.suffix.lower()
325
+ mime = "image/jpeg" if suffix in {".jpg", ".jpeg"} else "image/png"
326
+ return data, mime
327
+
328
+
329
+ def run_stdio(
330
+ server: EditingMcpServer,
331
+ source: BinaryIO | None = None,
332
+ destination: BinaryIO | None = None,
333
+ ) -> int:
334
+ """Serve newline-delimited MCP messages with a strict input bound."""
335
+
336
+ input_stream = source or sys.stdin.buffer
337
+ output_stream = destination or sys.stdout.buffer
338
+ server.start()
339
+ for raw in input_stream:
340
+ if len(raw) > _MAX_MESSAGE_BYTES:
341
+ response = server._error(None, -32600, "Message too large")
342
+ else:
343
+ try:
344
+ response = server.handle(json.loads(raw))
345
+ except (UnicodeDecodeError, json.JSONDecodeError):
346
+ response = server._error(None, -32700, "Parse error")
347
+ if response is not None:
348
+ output_stream.write(
349
+ json.dumps(response, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
350
+ + b"\n"
351
+ )
352
+ output_stream.flush()
353
+ return 0
@@ -0,0 +1,50 @@
1
+ """Local media inventory domain and persistence."""
2
+
3
+ from .models import (
4
+ AssetCandidate,
5
+ AssetKind,
6
+ InventoryCounts,
7
+ InventoryItem,
8
+ InventoryPage,
9
+ InventoryRoot,
10
+ InventoryRun,
11
+ InventoryState,
12
+ ItemStatus,
13
+ MediaStream,
14
+ ProbeStatus,
15
+ )
16
+ from .storage import InventoryRepository
17
+ from .discovery import DiscoveredAsset, DiscoveryError, MediaDiscovery
18
+ from .probe import (
19
+ FFprobeAdapter,
20
+ MediaProbeError,
21
+ MediaProbeResult,
22
+ bounded_file_fingerprint,
23
+ )
24
+ from .service import InventoryCoordinator
25
+ from .preview import MediaPreview, MediaPreviewRepository
26
+
27
+ __all__ = [
28
+ "AssetCandidate",
29
+ "AssetKind",
30
+ "DiscoveredAsset",
31
+ "DiscoveryError",
32
+ "FFprobeAdapter",
33
+ "InventoryCounts",
34
+ "InventoryCoordinator",
35
+ "MediaPreview",
36
+ "MediaPreviewRepository",
37
+ "InventoryItem",
38
+ "InventoryPage",
39
+ "InventoryRepository",
40
+ "InventoryRoot",
41
+ "InventoryRun",
42
+ "InventoryState",
43
+ "ItemStatus",
44
+ "MediaStream",
45
+ "MediaDiscovery",
46
+ "MediaProbeError",
47
+ "MediaProbeResult",
48
+ "ProbeStatus",
49
+ "bounded_file_fingerprint",
50
+ ]
@@ -0,0 +1,266 @@
1
+ """Bounded descriptor-based discovery below explicitly granted media roots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ from pathlib import PurePosixPath
8
+ import stat
9
+ import threading
10
+ import time
11
+ from typing import Iterator
12
+
13
+ from clipen.projects.models import DirectoryRole
14
+
15
+ from .models import AssetKind, InventoryRoot, validate_relative_path
16
+
17
+
18
+ _VIDEO_EXTENSIONS = frozenset(
19
+ {
20
+ ".avi",
21
+ ".braw",
22
+ ".m2ts",
23
+ ".m4v",
24
+ ".mkv",
25
+ ".mov",
26
+ ".mp4",
27
+ ".mts",
28
+ ".mxf",
29
+ ".r3d",
30
+ ".webm",
31
+ }
32
+ )
33
+ _AUDIO_EXTENSIONS = frozenset(
34
+ {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav"}
35
+ )
36
+ _IMAGE_EXTENSIONS = frozenset(
37
+ {".bmp", ".heic", ".heif", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".webp"}
38
+ )
39
+ _SYSTEM_NAMES = frozenset({".DS_Store", "Thumbs.db", "desktop.ini"})
40
+ # Clipen writes Resolve packages here, beside the footage; they are not footage.
41
+ EXPORT_FOLDER = "Clipen 匯出"
42
+
43
+
44
+ class DiscoveryError(RuntimeError):
45
+ def __init__(self, code: str) -> None:
46
+ super().__init__(code)
47
+ self.code = code
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class DiscoveredAsset:
52
+ role: DirectoryRole
53
+ relative_path: str
54
+ kind: AssetKind
55
+ size_bytes: int | None
56
+ mtime_ns: int | None
57
+ issue_code: str | None = None
58
+
59
+ def __post_init__(self) -> None:
60
+ validate_relative_path(self.relative_path)
61
+ if (self.size_bytes is None) != (self.mtime_ns is None):
62
+ raise ValueError("discovered file stat must be complete")
63
+
64
+ @property
65
+ def should_probe(self) -> bool:
66
+ return self.issue_code is None and self.kind is not AssetKind.UNKNOWN
67
+
68
+
69
+ class MediaDiscovery:
70
+ def __init__(
71
+ self,
72
+ *,
73
+ maximum_files: int = 100_000,
74
+ maximum_depth: int = 32,
75
+ maximum_seconds: float = 10 * 60,
76
+ ) -> None:
77
+ if maximum_files < 1 or maximum_depth < 1 or maximum_seconds <= 0:
78
+ raise ValueError("discovery bounds must be positive")
79
+ self.maximum_files = maximum_files
80
+ self.maximum_depth = maximum_depth
81
+ self.maximum_seconds = maximum_seconds
82
+
83
+ def scan(
84
+ self, root: InventoryRoot, cancel: threading.Event | None = None
85
+ ) -> Iterator[DiscoveredAsset]:
86
+ deadline = time.monotonic() + self.maximum_seconds
87
+ flags = (
88
+ os.O_RDONLY
89
+ | getattr(os, "O_DIRECTORY", 0)
90
+ | getattr(os, "O_NOFOLLOW", 0)
91
+ )
92
+ try:
93
+ root_fd = os.open(root.canonical_path, flags)
94
+ except OSError as error:
95
+ raise DiscoveryError("root_unavailable") from error
96
+ try:
97
+ identity = os.fstat(root_fd)
98
+ except OSError as error:
99
+ os.close(root_fd)
100
+ raise DiscoveryError("root_unavailable") from error
101
+ if identity.st_ino != root.inode:
102
+ os.close(root_fd)
103
+ raise DiscoveryError("root_changed")
104
+ discovered = [0]
105
+ yield from self._scan_directory(
106
+ root_fd,
107
+ root.role,
108
+ (),
109
+ 0,
110
+ deadline,
111
+ flags,
112
+ discovered,
113
+ cancel,
114
+ )
115
+
116
+ def _scan_directory(
117
+ self,
118
+ directory_fd: int,
119
+ role: DirectoryRole,
120
+ prefix: tuple[str, ...],
121
+ depth: int,
122
+ deadline: float,
123
+ flags: int,
124
+ discovered: list[int],
125
+ cancel: threading.Event | None,
126
+ ) -> Iterator[DiscoveredAsset]:
127
+ """Depth-first traversal keeps descriptor use bounded by maximum depth."""
128
+ try:
129
+ if cancel is not None and cancel.is_set():
130
+ raise DiscoveryError("cancelled")
131
+ if time.monotonic() >= deadline:
132
+ raise DiscoveryError("discovery_timeout")
133
+ for entry in _entries(directory_fd):
134
+ if cancel is not None and cancel.is_set():
135
+ raise DiscoveryError("cancelled")
136
+ if time.monotonic() >= deadline:
137
+ raise DiscoveryError("discovery_timeout")
138
+ name = entry.name
139
+ if not name or name in _SYSTEM_NAMES:
140
+ continue
141
+ relative_parts = prefix + (name,)
142
+ relative = PurePosixPath(*relative_parts).as_posix()
143
+ try:
144
+ validate_relative_path(relative)
145
+ except ValueError as error:
146
+ raise DiscoveryError("path_too_long") from error
147
+ try:
148
+ if entry.is_symlink():
149
+ discovered[0] += 1
150
+ self._check_file_limit(discovered[0])
151
+ yield DiscoveredAsset(
152
+ role,
153
+ relative,
154
+ AssetKind.UNKNOWN,
155
+ None,
156
+ None,
157
+ "symlink_ignored",
158
+ )
159
+ continue
160
+ if entry.is_dir(follow_symlinks=False):
161
+ if name.startswith(".") or (not prefix and name == EXPORT_FOLDER):
162
+ continue
163
+ if depth + 1 > self.maximum_depth:
164
+ raise DiscoveryError("tree_too_deep")
165
+ child_fd = os.open(name, flags, dir_fd=directory_fd)
166
+ yield from self._scan_directory(
167
+ child_fd,
168
+ role,
169
+ relative_parts,
170
+ depth + 1,
171
+ deadline,
172
+ flags,
173
+ discovered,
174
+ cancel,
175
+ )
176
+ continue
177
+ file_stat = entry.stat(follow_symlinks=False)
178
+ except OSError:
179
+ discovered[0] += 1
180
+ self._check_file_limit(discovered[0])
181
+ yield DiscoveredAsset(
182
+ role,
183
+ relative,
184
+ AssetKind.UNKNOWN,
185
+ None,
186
+ None,
187
+ "entry_unreadable",
188
+ )
189
+ continue
190
+ discovered[0] += 1
191
+ self._check_file_limit(discovered[0])
192
+ if name.startswith(".") or not stat.S_ISREG(file_stat.st_mode):
193
+ yield DiscoveredAsset(
194
+ role,
195
+ relative,
196
+ AssetKind.UNKNOWN,
197
+ None,
198
+ None,
199
+ "non_media",
200
+ )
201
+ continue
202
+ kind = _kind_for_name(name)
203
+ yield DiscoveredAsset(
204
+ role,
205
+ relative,
206
+ kind,
207
+ file_stat.st_size,
208
+ file_stat.st_mtime_ns,
209
+ None if kind is not AssetKind.UNKNOWN else "non_media",
210
+ )
211
+ finally:
212
+ os.close(directory_fd)
213
+
214
+ def _check_file_limit(self, discovered: int) -> None:
215
+ if discovered > self.maximum_files:
216
+ raise DiscoveryError("too_many_files")
217
+
218
+
219
+ def _kind_for_name(name: str) -> AssetKind:
220
+ extension = PurePosixPath(name).suffix.lower()
221
+ if extension in _VIDEO_EXTENSIONS:
222
+ return AssetKind.VIDEO
223
+ if extension in _AUDIO_EXTENSIONS:
224
+ return AssetKind.AUDIO
225
+ if extension in _IMAGE_EXTENSIONS:
226
+ return AssetKind.IMAGE
227
+ return AssetKind.UNKNOWN
228
+
229
+
230
+ def _entries(directory_fd: int) -> Iterator[os.DirEntry[str]]:
231
+ try:
232
+ with os.scandir(directory_fd) as iterator:
233
+ yield from iterator
234
+ except OSError as error:
235
+ raise DiscoveryError("directory_unreadable") from error
236
+
237
+
238
+ def open_file_beneath(root: InventoryRoot, relative_path: str) -> int:
239
+ """Open one regular file without following any component symlink."""
240
+ path = PurePosixPath(validate_relative_path(relative_path))
241
+ directory_flags = (
242
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
243
+ )
244
+ file_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
245
+ try:
246
+ current = os.open(root.canonical_path, directory_flags)
247
+ except OSError as error:
248
+ raise DiscoveryError("root_unavailable") from error
249
+ try:
250
+ identity = os.fstat(current)
251
+ if identity.st_ino != root.inode:
252
+ raise DiscoveryError("root_changed")
253
+ for component in path.parts[:-1]:
254
+ next_fd = os.open(component, directory_flags, dir_fd=current)
255
+ os.close(current)
256
+ current = next_fd
257
+ file_fd = os.open(path.parts[-1], file_flags, dir_fd=current)
258
+ file_stat = os.fstat(file_fd)
259
+ if not stat.S_ISREG(file_stat.st_mode):
260
+ os.close(file_fd)
261
+ raise DiscoveryError("entry_not_regular")
262
+ return file_fd
263
+ except OSError as error:
264
+ raise DiscoveryError("entry_unreadable") from error
265
+ finally:
266
+ os.close(current)