@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
@@ -13,10 +13,10 @@ from clipen.projects.models import validate_project_id, validate_request_id
13
13
  from clipen.projects.storage import command_digest, utc_now
14
14
 
15
15
  from .agent_models import (
16
- AgentRevision,
17
- AgentRun,
18
16
  REVISION_ID_PATTERN,
19
17
  RUN_ID_PATTERN,
18
+ AgentRevision,
19
+ AgentRun,
20
20
  bounded_text,
21
21
  encoded,
22
22
  make_id,
@@ -50,42 +50,77 @@ class EditAgentRepository:
50
50
  """Start an AI production session; there are no runs without one."""
51
51
  validate_project_id(project_id)
52
52
  request = validate_request_id(request_id)
53
- from .program_direction import validate_direction, PROGRAM_DIRECTION, FULL_PRODUCTION_REQUIREMENTS
54
- if not isinstance(production, dict) or (not {"skill_id", "intent"} <= set(production) or not set(production) <= {"skill_id", "intent", "visual_style_id", "font_style_id", "target_duration_seconds", "music_asset_id", "template_id"}):
53
+ from .program_direction import FULL_PRODUCTION_REQUIREMENTS, PROGRAM_DIRECTION, validate_direction
54
+
55
+ if not isinstance(production, dict) or (
56
+ not {"skill_id", "intent"} <= set(production)
57
+ or not set(production)
58
+ <= {
59
+ "skill_id",
60
+ "intent",
61
+ "visual_style_id",
62
+ "font_style_id",
63
+ "target_duration_seconds",
64
+ "music_asset_id",
65
+ "template_id",
66
+ }
67
+ ):
55
68
  raise ProjectError("production_input_invalid", "請選擇剪輯樣板並填寫影片需求。", status_code=422)
56
69
  from clipen.skills import get_skill
70
+
57
71
  skill = get_skill(production["skill_id"])
58
- from clipen.skills.visual_styles import style_presets, font_presets
59
- template=None
60
- template_supplied='template_id' in production
61
- font_supplied='font_style_id' in production or template_supplied
62
- if 'template_id' not in production:
63
- inferred=next((t for t in skill.get('templates',[]) if t['visual_style_id']==production.get('visual_style_id')),None)
64
- if inferred is not None:production={**production,'template_id':inferred['template_id']}
65
- if 'template_id' in production:
66
- template=next((t for t in skill.get('templates',[]) if t['template_id']==production['template_id']),None)
67
- if template is None:raise ProjectError('template_unavailable','找不到這套影片模板。',status_code=422)
68
- if production.get('visual_style_id',template['visual_style_id'])!=template['visual_style_id']:
69
- raise ProjectError('template_conflict','畫面風格與選擇的模板不一致,請重新選擇。',status_code=422)
70
- production={**production,'visual_style_id':template['visual_style_id'],'font_style_id':production.get('font_style_id',template['font_style_id'])}
72
+ from clipen.skills.visual_styles import font_presets, style_presets
73
+
74
+ template = None
75
+ template_supplied = "template_id" in production
76
+ font_supplied = "font_style_id" in production or template_supplied
77
+ if "template_id" not in production:
78
+ inferred = next(
79
+ (t for t in skill.get("templates", []) if t["visual_style_id"] == production.get("visual_style_id")),
80
+ None,
81
+ )
82
+ if inferred is not None:
83
+ production = {**production, "template_id": inferred["template_id"]}
84
+ if "template_id" in production:
85
+ template = next(
86
+ (t for t in skill.get("templates", []) if t["template_id"] == production["template_id"]), None
87
+ )
88
+ if template is None:
89
+ raise ProjectError("template_unavailable", "找不到這套影片模板。", status_code=422)
90
+ if production.get("visual_style_id", template["visual_style_id"]) != template["visual_style_id"]:
91
+ raise ProjectError("template_conflict", "畫面風格與選擇的模板不一致,請重新選擇。", status_code=422)
92
+ production = {
93
+ **production,
94
+ "visual_style_id": template["visual_style_id"],
95
+ "font_style_id": production.get("font_style_id", template["font_style_id"]),
96
+ }
71
97
  # A template is its own skill over the production core.
72
- skill=get_skill(template['skill']['skill_id'])
73
- skill['selected_template_id']=template['template_id']
74
- elif skill.get('template'):
98
+ skill = get_skill(template["skill"]["skill_id"])
99
+ skill["selected_template_id"] = template["template_id"]
100
+ elif skill.get("template"):
75
101
  # The template skill was chosen directly; keep its design brief in the intent.
76
- template=skill['template']
77
- skill['selected_template_id']=template['template_id']
78
- target=production.get('target_duration_seconds',skill.get('default_duration_seconds',60))
79
- if isinstance(target,bool) or not isinstance(target,int) or not 30<=target<=1200:
80
- raise ProjectError('production_input_invalid','預計片長必須為 30 到 1200 秒。',status_code=422)
102
+ template = skill["template"]
103
+ skill["selected_template_id"] = template["template_id"]
104
+ target = production.get("target_duration_seconds", skill.get("default_duration_seconds", 60))
105
+ if isinstance(target, bool) or not isinstance(target, int) or not 30 <= target <= 1200:
106
+ raise ProjectError("production_input_invalid", "預計片長必須為 30 到 1200 秒。", status_code=422)
81
107
  from .workbench import music_choice
82
- selected_music=music_choice(self,project_id,production.get("music_asset_id"))
83
- supplied_style="visual_style_id" in production
84
- selected,_=style_presets(skill,production.get('visual_style_id'))
85
- skill['selected_visual_style_id']=selected
86
- selected_font,_=font_presets(skill,{},production.get('font_style_id'))
87
- skill['selected_font_style_id']=selected_font
88
- production = {**({'template_id':template['template_id']} if template_supplied else {}),"skill_id": skill["skill_id"], "intent": bounded_text(production["intent"], "影片需求", 8000), **({"visual_style_id":selected} if supplied_style else {}), **({"font_style_id":selected_font} if font_supplied else {}), **({"target_duration_seconds":target} if "target_duration_seconds" in production else {}), **({"music_asset_id":production["music_asset_id"]} if "music_asset_id" in production else {})}
108
+
109
+ selected_music = music_choice(self, project_id, production.get("music_asset_id"))
110
+ supplied_style = "visual_style_id" in production
111
+ selected, _ = style_presets(skill, production.get("visual_style_id"))
112
+ skill["selected_visual_style_id"] = selected
113
+ selected_font, _ = font_presets(skill, {}, production.get("font_style_id"))
114
+ skill["selected_font_style_id"] = selected_font
115
+ production = {
116
+ **({"template_id": template["template_id"]} if template_supplied else {}),
117
+ "skill_id": skill["skill_id"],
118
+ "intent": bounded_text(production["intent"], "影片需求", 8000),
119
+ **({"visual_style_id": selected} if supplied_style else {}),
120
+ **({"font_style_id": selected_font} if font_supplied else {}),
121
+ **({"target_duration_seconds": target} if "target_duration_seconds" in production else {}),
122
+ **({"music_asset_id": production["music_asset_id"]} if "music_asset_id" in production else {}),
123
+ }
89
124
  creative_direction = {**PROGRAM_DIRECTION, "production_requirements": FULL_PRODUCTION_REQUIREMENTS}
90
125
  creative_direction = validate_direction(creative_direction)
91
126
  if isinstance(max_tool_calls, bool) or not 1 <= max_tool_calls <= 500:
@@ -102,6 +137,7 @@ class EditAgentRepository:
102
137
  }
103
138
  )
104
139
  from clipen.provider_registry import implemented_providers
140
+
105
141
  if provider not in implemented_providers():
106
142
  raise ValueError("provider is invalid")
107
143
  run_id = make_id("editrun_", [project_id, request])
@@ -126,8 +162,7 @@ class EditAgentRepository:
126
162
  database.rollback()
127
163
  return result, False
128
164
  busy = database.execute(
129
- "SELECT run_id FROM edit_agent_runs "
130
- "WHERE state IN ('queued','running') LIMIT 1"
165
+ "SELECT run_id FROM edit_agent_runs WHERE state IN ('queued','running') LIMIT 1"
131
166
  ).fetchone()
132
167
  if busy is not None:
133
168
  raise ProjectError(
@@ -136,14 +171,24 @@ class EditAgentRepository:
136
171
  status_code=409,
137
172
  )
138
173
  from clipen.domain import Rational, Track, TrackKind
174
+
139
175
  from .production_media import source_rows
176
+
140
177
  sources = source_rows(self.projects, project_id)
141
178
  inventory = database.execute("SELECT run_id FROM current_inventory WHERE slot=1").fetchone()
142
179
  if inventory is None or not any(s["kind"] == "video" for s in sources):
143
180
  raise ProjectError("inventory_required", "請先檢查素材,至少需要一段可用影片。", status_code=409)
144
181
  timeline = EditTimeline(
145
- make_id("production_", run_id), project_id, None, None, None,
146
- Rational(30, 1), 1280, 720, 0, (Track("video-main", TrackKind.VIDEO, ()),),
182
+ make_id("production_", run_id),
183
+ project_id,
184
+ None,
185
+ None,
186
+ None,
187
+ Rational(30, 1),
188
+ 1280,
189
+ 720,
190
+ 0,
191
+ (Track("video-main", TrackKind.VIDEO, ()),),
147
192
  production_session_id=run_id,
148
193
  )
149
194
  payload = timeline.to_payload()
@@ -172,11 +217,35 @@ class EditAgentRepository:
172
217
  "payload_json,summary,created_at) VALUES(?,?,0,NULL,?,?,?,?)",
173
218
  (revision_id, run_id, digest, encoded(payload), "空白製作草稿", now),
174
219
  )
175
- database.execute("INSERT INTO production_sessions VALUES(?,?,?,?,?,?)", (
176
- run_id, encoded({**({'template':template} if template else {}),"authority": "user", "brief": production["intent"], "allow_local_model_downloads": True, "visual_style_id":selected, "font_style_id":selected_font, "target_duration_seconds":target, "music_choice":selected_music}),
177
- encoded(skill), encoded(sources), inventory["run_id"], now,
178
- ))
179
- self._append_event(database, run_id, "run_created", {"revision_id": revision_id, "creative_direction": creative_direction}, now)
220
+ database.execute(
221
+ "INSERT INTO production_sessions VALUES(?,?,?,?,?,?)",
222
+ (
223
+ run_id,
224
+ encoded(
225
+ {
226
+ **({"template": template} if template else {}),
227
+ "authority": "user",
228
+ "brief": production["intent"],
229
+ "allow_local_model_downloads": True,
230
+ "visual_style_id": selected,
231
+ "font_style_id": selected_font,
232
+ "target_duration_seconds": target,
233
+ "music_choice": selected_music,
234
+ }
235
+ ),
236
+ encoded(skill),
237
+ encoded(sources),
238
+ inventory["run_id"],
239
+ now,
240
+ ),
241
+ )
242
+ self._append_event(
243
+ database,
244
+ run_id,
245
+ "run_created",
246
+ {"revision_id": revision_id, "creative_direction": creative_direction},
247
+ now,
248
+ )
180
249
  database.execute(
181
250
  "INSERT INTO edit_agent_command_receipts VALUES(?,?,?,?,?)",
182
251
  (request, "start", request_hash, encoded({"run_id": run_id}), now),
@@ -201,98 +270,193 @@ class EditAgentRepository:
201
270
  row = db.execute("SELECT * FROM production_sessions WHERE run_id=?", (run_id,)).fetchone()
202
271
  if row is None:
203
272
  return None
204
- return {"run_id": run_id, "intent": json.loads(row["intent_json"]),
205
- "skill": json.loads(row["skill_json"]), "sources": json.loads(row["sources_json"]),
206
- "inventory_run_id": row["inventory_run_id"]}
273
+ return {
274
+ "run_id": run_id,
275
+ "intent": json.loads(row["intent_json"]),
276
+ "skill": json.loads(row["skill_json"]),
277
+ "sources": json.loads(row["sources_json"]),
278
+ "inventory_run_id": row["inventory_run_id"],
279
+ }
207
280
 
208
281
  def creative_direction(self, project_id: str, run_id: str) -> dict:
209
282
  self._validate_run_id(run_id)
210
283
  with self.projects.connect(project_id) as db:
211
- row=db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='run_created' ORDER BY sequence LIMIT 1",(run_id,)).fetchone()
212
- return {} if row is None else json.loads(row['payload_json']).get('creative_direction',{})
284
+ row = db.execute(
285
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='run_created' ORDER BY sequence LIMIT 1",
286
+ (run_id,),
287
+ ).fetchone()
288
+ return {} if row is None else json.loads(row["payload_json"]).get("creative_direction", {})
213
289
 
214
- def set_target_duration(self, project_id, run_id, expected_revision_id, *, target_duration_seconds, request_excerpt, summary):
290
+ def set_target_duration(
291
+ self, project_id, run_id, expected_revision_id, *, target_duration_seconds, request_excerpt, summary
292
+ ):
215
293
  """Reconcile a later user duration request without rewriting the film."""
216
- normalized=self._validate_run_id(run_id)
217
- if isinstance(target_duration_seconds,bool) or not isinstance(target_duration_seconds,int) or not 30<=target_duration_seconds<=1200:
218
- raise ProjectError('production_input_invalid','預計片長必須為 30 到 1200 秒。',status_code=422)
219
- excerpt=bounded_text(request_excerpt,'使用者要求引文',500)
220
- summary=bounded_text(summary,'修改說明',500)
294
+ normalized = self._validate_run_id(run_id)
295
+ if (
296
+ isinstance(target_duration_seconds, bool)
297
+ or not isinstance(target_duration_seconds, int)
298
+ or not 30 <= target_duration_seconds <= 1200
299
+ ):
300
+ raise ProjectError("production_input_invalid", "預計片長必須為 30 到 1200 秒。", status_code=422)
301
+ excerpt = bounded_text(request_excerpt, "使用者要求引文", 500)
302
+ summary = bounded_text(summary, "修改說明", 500)
221
303
  with self.projects.connect(project_id) as db:
222
- db.execute('BEGIN IMMEDIATE')
223
- run=self._read_run(db,normalized)
224
- if run.current_revision_id!=expected_revision_id:
225
- raise ProjectError('revision_conflict','影片已更新,請重新讀取後修改。',status_code=409)
226
- if run.state!='running':
227
- raise ProjectError('edit_agent_not_running','AI 製作目前未在執行。',status_code=409)
228
- row=db.execute('SELECT intent_json FROM production_sessions WHERE run_id=?',(normalized,)).fetchone()
229
- if row is None:raise ProjectError('production_required','這個版本不支援持續修訂。',status_code=422)
230
- intent=json.loads(row['intent_json'])
231
- request=intent.get('latest_revision_request',{})
232
- if request.get('authority')!='user' or excerpt not in request.get('instruction',''):
233
- raise ProjectError('duration_request_required','請引用使用者本輪修改片長的原文;不能自行降低交付目標。',status_code=422)
234
- previous=intent.get('target_duration_seconds',60)
235
- intent['target_duration_seconds']=target_duration_seconds
236
- db.execute('UPDATE production_sessions SET intent_json=? WHERE run_id=?',(encoded(intent),normalized))
237
- result={'revision_id':run.current_revision_id,'previous_target_duration_seconds':previous,
238
- 'target_duration_seconds':target_duration_seconds,'request_excerpt':excerpt}
239
- self._append_event(db,normalized,'production_duration_updated',{
240
- **result,'authority':'model','instruction':request['instruction'],
241
- 'request_created_at':request.get('created_at'),'summary':summary},utc_now())
304
+ db.execute("BEGIN IMMEDIATE")
305
+ run = self._read_run(db, normalized)
306
+ if run.current_revision_id != expected_revision_id:
307
+ raise ProjectError("revision_conflict", "影片已更新,請重新讀取後修改。", status_code=409)
308
+ if run.state != "running":
309
+ raise ProjectError("edit_agent_not_running", "AI 製作目前未在執行。", status_code=409)
310
+ row = db.execute("SELECT intent_json FROM production_sessions WHERE run_id=?", (normalized,)).fetchone()
311
+ if row is None:
312
+ raise ProjectError("production_required", "這個版本不支援持續修訂。", status_code=422)
313
+ intent = json.loads(row["intent_json"])
314
+ request = intent.get("latest_revision_request", {})
315
+ if request.get("authority") != "user" or excerpt not in request.get("instruction", ""):
316
+ raise ProjectError(
317
+ "duration_request_required",
318
+ "請引用使用者本輪修改片長的原文;不能自行降低交付目標。",
319
+ status_code=422,
320
+ )
321
+ previous = intent.get("target_duration_seconds", 60)
322
+ intent["target_duration_seconds"] = target_duration_seconds
323
+ db.execute("UPDATE production_sessions SET intent_json=? WHERE run_id=?", (encoded(intent), normalized))
324
+ result = {
325
+ "revision_id": run.current_revision_id,
326
+ "previous_target_duration_seconds": previous,
327
+ "target_duration_seconds": target_duration_seconds,
328
+ "request_excerpt": excerpt,
329
+ }
330
+ self._append_event(
331
+ db,
332
+ normalized,
333
+ "production_duration_updated",
334
+ {
335
+ **result,
336
+ "authority": "model",
337
+ "instruction": request["instruction"],
338
+ "request_created_at": request.get("created_at"),
339
+ "summary": summary,
340
+ },
341
+ utc_now(),
342
+ )
242
343
  db.commit()
243
344
  return result
244
345
 
245
- def request_refinement(self, project_id, run_id, request_id, expected_revision_id, instruction, music_asset_id=None, expected_references_version=None, provider=None):
346
+ def request_refinement(
347
+ self,
348
+ project_id,
349
+ run_id,
350
+ request_id,
351
+ expected_revision_id,
352
+ instruction,
353
+ music_asset_id=None,
354
+ expected_references_version=None,
355
+ provider=None,
356
+ ):
246
357
  from .refinement_references import hand_over, public_state, references
247
358
  from .workbench import music_choice
248
- normalized=self._validate_run_id(run_id)
249
- request=validate_request_id(request_id)
250
- instruction=bounded_text(instruction,'修改需求',8000)
251
- choice=music_choice(self,project_id,music_asset_id)
359
+
360
+ normalized = self._validate_run_id(run_id)
361
+ request = validate_request_id(request_id)
362
+ instruction = bounded_text(instruction, "修改需求", 8000)
363
+ choice = music_choice(self, project_id, music_asset_id)
252
364
  if provider is not None:
253
365
  from clipen.provider_registry import get_provider
366
+
254
367
  get_provider(provider)
255
- request_hash=command_digest({'run_id':normalized,'expected_revision_id':expected_revision_id,'instruction':instruction,'music_asset_id':music_asset_id,'expected_references_version':expected_references_version,
256
- **({'provider':provider} if provider is not None else {})})
368
+ request_hash = command_digest(
369
+ {
370
+ "run_id": normalized,
371
+ "expected_revision_id": expected_revision_id,
372
+ "instruction": instruction,
373
+ "music_asset_id": music_asset_id,
374
+ "expected_references_version": expected_references_version,
375
+ **({"provider": provider} if provider is not None else {}),
376
+ }
377
+ )
257
378
  with self.projects.connect(project_id) as db:
258
- db.execute('BEGIN IMMEDIATE')
259
- receipt=db.execute('SELECT * FROM edit_agent_command_receipts WHERE request_id=?',(request,)).fetchone()
379
+ db.execute("BEGIN IMMEDIATE")
380
+ receipt = db.execute("SELECT * FROM edit_agent_command_receipts WHERE request_id=?", (request,)).fetchone()
260
381
  if receipt:
261
- if receipt['command_type']!='refine' or receipt['request_hash']!=request_hash:
262
- raise ProjectError('request_reused','操作識別已用於其他修改。',status_code=409)
263
- return self._read_run(db,normalized),False
264
- run=self._read_run(db,normalized)
265
- latest=db.execute('SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC LIMIT 1').fetchone()
266
- if latest['run_id']!=normalized or db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone():
267
- raise ProjectError('edit_agent_busy','請先停止目前的 AI 製作。',status_code=409)
268
- if run.current_revision_id!=expected_revision_id:
269
- raise ProjectError('revision_conflict','影片已更新,請重新讀取後提出修改。',status_code=409)
270
- session=db.execute('SELECT intent_json FROM production_sessions WHERE run_id=?',(normalized,)).fetchone()
271
- if session is None:raise ProjectError('production_required','這個版本不支援持續修訂。',status_code=422)
272
- intent=json.loads(session['intent_json'])
273
- if expected_references_version is not None and (isinstance(expected_references_version,bool) or not isinstance(expected_references_version,int) or references(intent)['version'] != expected_references_version):
274
- raise ProjectError('reference_conflict','參考註記已更新,請重新讀取並確認後再送出。',status_code=409)
275
- reference_snapshot=public_state(intent,self._read_revision(db,run.current_revision_id).timeline)
276
- intent['latest_revision_request']={'authority':'user','instruction':instruction,'base_revision_id':expected_revision_id,'created_at':utc_now(),'references':reference_snapshot}
382
+ if receipt["command_type"] != "refine" or receipt["request_hash"] != request_hash:
383
+ raise ProjectError("request_reused", "操作識別已用於其他修改。", status_code=409)
384
+ return self._read_run(db, normalized), False
385
+ run = self._read_run(db, normalized)
386
+ latest = db.execute("SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC LIMIT 1").fetchone()
387
+ if (
388
+ latest["run_id"] != normalized
389
+ or db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone()
390
+ ):
391
+ raise ProjectError("edit_agent_busy", "請先停止目前的 AI 製作。", status_code=409)
392
+ if run.current_revision_id != expected_revision_id:
393
+ raise ProjectError("revision_conflict", "影片已更新,請重新讀取後提出修改。", status_code=409)
394
+ session = db.execute("SELECT intent_json FROM production_sessions WHERE run_id=?", (normalized,)).fetchone()
395
+ if session is None:
396
+ raise ProjectError("production_required", "這個版本不支援持續修訂。", status_code=422)
397
+ intent = json.loads(session["intent_json"])
398
+ if expected_references_version is not None and (
399
+ isinstance(expected_references_version, bool)
400
+ or not isinstance(expected_references_version, int)
401
+ or references(intent)["version"] != expected_references_version
402
+ ):
403
+ raise ProjectError("reference_conflict", "參考註記已更新,請重新讀取並確認後再送出。", status_code=409)
404
+ reference_snapshot = public_state(intent, self._read_revision(db, run.current_revision_id).timeline)
405
+ intent["latest_revision_request"] = {
406
+ "authority": "user",
407
+ "instruction": instruction,
408
+ "base_revision_id": expected_revision_id,
409
+ "created_at": utc_now(),
410
+ "references": reference_snapshot,
411
+ }
277
412
  # What the last change left for the person goes with the next request, so it is not lost.
278
413
  from .change_report import carried
279
- last=db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='run_finished' ORDER BY sequence DESC LIMIT 1",(normalized,)).fetchone()
280
- left=carried(json.loads(last['payload_json']).get('report') or {}) if last else []
281
- if left:intent['latest_revision_request']['left_last_time']=left
414
+
415
+ last = db.execute(
416
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='run_finished' ORDER BY sequence DESC LIMIT 1",
417
+ (normalized,),
418
+ ).fetchone()
419
+ left = carried(json.loads(last["payload_json"]).get("report") or {}) if last else []
420
+ if left:
421
+ intent["latest_revision_request"]["left_last_time"] = left
282
422
  # The AI gets this round's notes; only lasting facts stay listed.
283
423
  hand_over(intent)
284
- if choice is not None:intent['music_choice']=choice
285
- db.execute('UPDATE production_sessions SET intent_json=? WHERE run_id=?',(encoded(intent),normalized))
286
- self._append_event(db,normalized,'refinement_requested',{'instruction':instruction,'references':reference_snapshot,'base_revision_id':expected_revision_id,'previous_budget':run.to_public()['budget'],'previous_attempt_id':run.provider_attempt_id,'music_choice':intent.get('music_choice')},utc_now())
424
+ if choice is not None:
425
+ intent["music_choice"] = choice
426
+ db.execute("UPDATE production_sessions SET intent_json=? WHERE run_id=?", (encoded(intent), normalized))
427
+ self._append_event(
428
+ db,
429
+ normalized,
430
+ "refinement_requested",
431
+ {
432
+ "instruction": instruction,
433
+ "references": reference_snapshot,
434
+ "base_revision_id": expected_revision_id,
435
+ "previous_budget": run.to_public()["budget"],
436
+ "previous_attempt_id": run.provider_attempt_id,
437
+ "music_choice": intent.get("music_choice"),
438
+ },
439
+ utc_now(),
440
+ )
287
441
  # A revision is a new request from the user, so the AI Clipen runs with
288
442
  # now may take over the draft; it spends its own quota from a fresh budget.
289
443
  # Resuming an interrupted attempt never switches (see resume_stopped).
290
- if provider is not None and provider!=run.provider:
291
- self._append_event(db,normalized,'provider_switched',{'from':run.provider,'to':provider},utc_now())
292
- db.execute('UPDATE edit_agent_runs SET provider=? WHERE run_id=?',(provider,normalized))
293
- db.execute("UPDATE edit_agent_runs SET state='queued',phase='ready',tool_calls=0,preview_renders=0,max_tool_calls=500,max_preview_renders=6,error_code=NULL,provider_attempt_id=NULL,usage_json=NULL,completed_at=NULL WHERE run_id=?",(normalized,))
294
- db.execute('INSERT INTO edit_agent_command_receipts VALUES(?,?,?,?,?)',(request,'refine',request_hash,encoded({'run_id':normalized}),utc_now()))
295
- result=self._read_run(db,normalized);db.commit();return result,True
444
+ if provider is not None and provider != run.provider:
445
+ self._append_event(
446
+ db, normalized, "provider_switched", {"from": run.provider, "to": provider}, utc_now()
447
+ )
448
+ db.execute("UPDATE edit_agent_runs SET provider=? WHERE run_id=?", (provider, normalized))
449
+ db.execute(
450
+ "UPDATE edit_agent_runs SET state='queued',phase='ready',tool_calls=0,preview_renders=0,max_tool_calls=500,max_preview_renders=6,error_code=NULL,provider_attempt_id=NULL,usage_json=NULL,completed_at=NULL WHERE run_id=?",
451
+ (normalized,),
452
+ )
453
+ db.execute(
454
+ "INSERT INTO edit_agent_command_receipts VALUES(?,?,?,?,?)",
455
+ (request, "refine", request_hash, encoded({"run_id": normalized}), utc_now()),
456
+ )
457
+ result = self._read_run(db, normalized)
458
+ db.commit()
459
+ return result, True
296
460
 
297
461
  # Stops that leave a valid draft and say nothing about the draft itself: the
298
462
  # wall clock ran out, the provider account hit its usage limit, or the
@@ -300,47 +464,69 @@ class EditAgentRepository:
300
464
  # budget once the user asks again. A draft blocked by delivery checks needs
301
465
  # a revision request instead, since the same instructions hit the same checks.
302
466
  # A login that expired mid-run is the same: sign in again, then continue.
303
- RESUMABLE_ERRORS = frozenset({'provider_timed_out', 'provider_usage_limit', 'provider_stopped_early',
304
- 'provider_authentication_required'})
467
+ RESUMABLE_ERRORS = frozenset(
468
+ {"provider_timed_out", "provider_usage_limit", "provider_stopped_early", "provider_authentication_required"}
469
+ )
305
470
 
306
471
  def resume_stopped(self, project_id: str, run_id: object) -> AgentRun:
307
472
  normalized = self._validate_run_id(run_id)
308
473
  with self.projects.connect(project_id) as db:
309
- db.execute('BEGIN IMMEDIATE')
474
+ db.execute("BEGIN IMMEDIATE")
310
475
  run = self._read_run(db, normalized)
311
- latest = db.execute('SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC LIMIT 1').fetchone()
312
- if latest is None or latest['run_id'] != normalized:
313
- raise ProjectError('edit_agent_resume_invalid', '已有較新的製作工作,請使用最新工作。', status_code=409)
476
+ latest = db.execute("SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC LIMIT 1").fetchone()
477
+ if latest is None or latest["run_id"] != normalized:
478
+ raise ProjectError("edit_agent_resume_invalid", "已有較新的製作工作,請使用最新工作。", status_code=409)
314
479
  if db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone():
315
- raise ProjectError('edit_agent_busy', '目前已有 AI 製作工作。', status_code=409)
316
- if run.state != 'failed' or run.error_code not in self.RESUMABLE_ERRORS:
317
- raise ProjectError('edit_agent_resume_invalid', '只能接續因 AI 逾時、額度不足、登入過期或提早結束而停止的工作。', status_code=409)
318
- if not db.execute('SELECT 1 FROM production_sessions WHERE run_id=?', (normalized,)).fetchone():
319
- raise ProjectError('edit_agent_resume_invalid', '這份工作不支援接續製作。', status_code=409)
480
+ raise ProjectError("edit_agent_busy", "目前已有 AI 製作工作。", status_code=409)
481
+ if run.state != "failed" or run.error_code not in self.RESUMABLE_ERRORS:
482
+ raise ProjectError(
483
+ "edit_agent_resume_invalid",
484
+ "只能接續因 AI 逾時、額度不足、登入過期或提早結束而停止的工作。",
485
+ status_code=409,
486
+ )
487
+ if not db.execute("SELECT 1 FROM production_sessions WHERE run_id=?", (normalized,)).fetchone():
488
+ raise ProjectError("edit_agent_resume_invalid", "這份工作不支援接續製作。", status_code=409)
320
489
  if run.tool_calls >= run.max_tool_calls or run.preview_renders >= run.max_preview_renders:
321
- raise ProjectError('edit_agent_budget_exhausted', '這份工作的操作或輸出次數已用完。', status_code=409)
490
+ raise ProjectError("edit_agent_budget_exhausted", "這份工作的操作或輸出次數已用完。", status_code=409)
322
491
  # The run row only keeps the latest attempt's usage; keep what the
323
492
  # stopped attempt already spent in the append-only event log.
324
- previous_usage = db.execute('SELECT usage_json FROM edit_agent_runs WHERE run_id=?', (normalized,)).fetchone()['usage_json']
325
- self._append_event(db, normalized, 'run_resumed', {'previous_attempt_id':run.provider_attempt_id,
326
- 'previous_error_code':run.error_code,
327
- 'previous_usage':None if previous_usage is None else json.loads(previous_usage)}, utc_now())
328
- db.execute("UPDATE edit_agent_runs SET state='queued',phase='queued',error_code=NULL,provider_attempt_id=NULL,usage_json=NULL,completed_at=NULL WHERE run_id=?", (normalized,))
493
+ previous_usage = db.execute(
494
+ "SELECT usage_json FROM edit_agent_runs WHERE run_id=?", (normalized,)
495
+ ).fetchone()["usage_json"]
496
+ self._append_event(
497
+ db,
498
+ normalized,
499
+ "run_resumed",
500
+ {
501
+ "previous_attempt_id": run.provider_attempt_id,
502
+ "previous_error_code": run.error_code,
503
+ "previous_usage": None if previous_usage is None else json.loads(previous_usage),
504
+ },
505
+ utc_now(),
506
+ )
507
+ db.execute(
508
+ "UPDATE edit_agent_runs SET state='queued',phase='queued',error_code=NULL,provider_attempt_id=NULL,usage_json=NULL,completed_at=NULL WHERE run_id=?",
509
+ (normalized,),
510
+ )
329
511
  result = self._read_run(db, normalized)
330
512
  db.commit()
331
513
  return result
332
514
 
333
- resume_timed_out = resume_stopped
334
-
335
515
  def record_machine_sleep(self, project_id: str, run_id: object, periods) -> None:
336
516
  """Note each time the Mac slept during an attempt, so a stall is not blamed on the AI."""
337
517
  from datetime import datetime, timezone
518
+
338
519
  normalized = self._validate_run_id(run_id)
339
520
  with self.projects.connect(project_id) as db:
340
521
  for start, end in periods:
341
522
  stamp = lambda value: datetime.fromtimestamp(value, timezone.utc).isoformat()
342
- self._append_event(db, normalized, 'machine_slept',
343
- {'from': stamp(start), 'to': stamp(end), 'seconds': round(end - start)}, stamp(end))
523
+ self._append_event(
524
+ db,
525
+ normalized,
526
+ "machine_slept",
527
+ {"from": stamp(start), "to": stamp(end), "seconds": round(end - start)},
528
+ stamp(end),
529
+ )
344
530
  db.commit()
345
531
 
346
532
  def delivery_blockers(self, project_id: str, run_id: object) -> tuple[str, ...] | None:
@@ -348,14 +534,17 @@ class EditAgentRepository:
348
534
  normalized = self._validate_run_id(run_id)
349
535
  with self.projects.connect(project_id) as db:
350
536
  run = self._read_run(db, normalized)
351
- rows = db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='sequence_validation' ORDER BY sequence DESC LIMIT 30", (normalized,)).fetchall()
537
+ rows = db.execute(
538
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='sequence_validation' ORDER BY sequence DESC LIMIT 30",
539
+ (normalized,),
540
+ ).fetchall()
352
541
  for row in rows:
353
- value = json.loads(row['payload_json'])
354
- if value['revision_id'] == run.current_revision_id:
355
- if value['valid']:
542
+ value = json.loads(row["payload_json"])
543
+ if value["revision_id"] == run.current_revision_id:
544
+ if value["valid"]:
356
545
  return ()
357
- codes = [issue['code'] for issue in value.get('issues', []) + value.get('delivery_issues', [])]
358
- return tuple(dict.fromkeys(codes)) or ('sequence_invalid',)
546
+ codes = [issue["code"] for issue in value.get("issues", []) + value.get("delivery_issues", [])]
547
+ return tuple(dict.fromkeys(codes)) or ("sequence_invalid",)
359
548
  return None
360
549
 
361
550
  def activate(self, project_id: str, run_id: object) -> AgentRun:
@@ -366,8 +555,7 @@ class EditAgentRepository:
366
555
  if run.state == "queued":
367
556
  now = utc_now()
368
557
  database.execute(
369
- "UPDATE edit_agent_runs SET state='running',phase='editing',started_at=? "
370
- "WHERE run_id=?",
558
+ "UPDATE edit_agent_runs SET state='running',phase='editing',started_at=? WHERE run_id=?",
371
559
  (now, normalized),
372
560
  )
373
561
  self._append_event(database, normalized, "run_started", {}, now)
@@ -447,8 +635,11 @@ class EditAgentRepository:
447
635
  if run.state != "running" and not (allow_user_edit and run.state not in {"queued", "running"}):
448
636
  database.rollback()
449
637
  raise ProjectError("edit_agent_not_running", "AI 剪輯工作並未執行。", status_code=409)
450
- if allow_user_edit and database.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone():
451
- raise ProjectError('edit_agent_busy','AI 正在修改作品,請稍後再編輯。',status_code=409)
638
+ if (
639
+ allow_user_edit
640
+ and database.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone()
641
+ ):
642
+ raise ProjectError("edit_agent_busy", "AI 正在修改作品,請稍後再編輯。", status_code=409)
452
643
  existing = database.execute(
453
644
  "SELECT revision_id FROM edit_agent_revisions WHERE run_id=? AND payload_digest=?",
454
645
  (normalized, digest),
@@ -460,7 +651,9 @@ class EditAgentRepository:
460
651
  )
461
652
  if existing["revision_id"] != run.current_revision_id:
462
653
  # Arriving at an earlier picture again is still a step forward in the history people see.
463
- self._append_event(database, normalized, "revision_selected", {"revision_id": existing["revision_id"]}, utc_now())
654
+ self._append_event(
655
+ database, normalized, "revision_selected", {"revision_id": existing["revision_id"]}, utc_now()
656
+ )
464
657
  result = self._read_revision(database, existing["revision_id"])
465
658
  database.commit()
466
659
  return result, False
@@ -503,8 +696,8 @@ class EditAgentRepository:
503
696
  with self.projects.connect(project_id) as database:
504
697
  database.execute("BEGIN IMMEDIATE")
505
698
  run = self._read_run(database, normalized)
506
- if expected_revision_id is not None and expected_revision_id!=run.current_revision_id:
507
- raise ProjectError('revision_conflict','作品版本已更新,請重新讀取。',status_code=409)
699
+ if expected_revision_id is not None and expected_revision_id != run.current_revision_id:
700
+ raise ProjectError("revision_conflict", "作品版本已更新,請重新讀取。", status_code=409)
508
701
  current = self._read_revision(database, run.current_revision_id)
509
702
  if current.parent_revision_id is None:
510
703
  database.rollback()
@@ -524,14 +717,22 @@ class EditAgentRepository:
524
717
  database.commit()
525
718
  return parent
526
719
 
527
- def finish(self, project_id: str, run_id: object, summary: object, *, expected_revision_id: str | None = None, report: dict | None = None) -> AgentRun:
720
+ def finish(
721
+ self,
722
+ project_id: str,
723
+ run_id: object,
724
+ summary: object,
725
+ *,
726
+ expected_revision_id: str | None = None,
727
+ report: dict | None = None,
728
+ ) -> AgentRun:
528
729
  normalized = self._validate_run_id(run_id)
529
730
  normalized_summary = bounded_text(summary, "完成摘要", 1_000)
530
731
  with self.projects.connect(project_id) as database:
531
732
  database.execute("BEGIN IMMEDIATE")
532
733
  run = self._read_run(database, normalized)
533
- if expected_revision_id is not None and expected_revision_id!=run.current_revision_id:
534
- raise ProjectError('revision_conflict','作品版本已更新,請重新檢視。',status_code=409)
734
+ if expected_revision_id is not None and expected_revision_id != run.current_revision_id:
735
+ raise ProjectError("revision_conflict", "作品版本已更新,請重新檢視。", status_code=409)
535
736
  if run.state != "running":
536
737
  database.rollback()
537
738
  raise ProjectError("edit_agent_not_running", "AI 剪輯工作並未執行。", status_code=409)
@@ -541,7 +742,13 @@ class EditAgentRepository:
541
742
  "final_revision_id=current_revision_id,completed_at=? WHERE run_id=?",
542
743
  (now, normalized),
543
744
  )
544
- self._append_event(database, normalized, "run_finished", {"summary": normalized_summary, **({"report": report} if report else {})}, now)
745
+ self._append_event(
746
+ database,
747
+ normalized,
748
+ "run_finished",
749
+ {"summary": normalized_summary, **({"report": report} if report else {})},
750
+ now,
751
+ )
545
752
  result = self._read_run(database, normalized)
546
753
  database.commit()
547
754
  return result
@@ -564,8 +771,7 @@ class EditAgentRepository:
564
771
  if usage is not None:
565
772
  expected = {"input_tokens", "cached_input_tokens", "output_tokens"}
566
773
  if set(usage) != expected or any(
567
- isinstance(value, bool) or not isinstance(value, int) or value < 0
568
- for value in usage.values()
774
+ isinstance(value, bool) or not isinstance(value, int) or value < 0 for value in usage.values()
569
775
  ):
570
776
  raise ValueError("provider usage is invalid")
571
777
  if usage["cached_input_tokens"] > usage["input_tokens"]:
@@ -590,8 +796,12 @@ class EditAgentRepository:
590
796
  database,
591
797
  normalized,
592
798
  "provider_finished" if error_code is None else "provider_failed",
593
- {"attempt_id": attempt_id, "usage": usage, "error_code": error_code,
594
- "message": _closing_message(message)},
799
+ {
800
+ "attempt_id": attempt_id,
801
+ "usage": usage,
802
+ "error_code": error_code,
803
+ "message": _closing_message(message),
804
+ },
595
805
  now,
596
806
  )
597
807
  result = self._read_run(database, normalized)
@@ -660,9 +870,7 @@ class EditAgentRepository:
660
870
  validate_project_id(project_id)
661
871
  with self.projects.connect(project_id) as database:
662
872
  database.execute("BEGIN IMMEDIATE")
663
- rows = database.execute(
664
- "SELECT run_id FROM edit_agent_runs WHERE state IN ('queued','running')"
665
- ).fetchall()
873
+ rows = database.execute("SELECT run_id FROM edit_agent_runs WHERE state IN ('queued','running')").fetchall()
666
874
  now = utc_now()
667
875
  for row in rows:
668
876
  database.execute(
@@ -670,9 +878,7 @@ class EditAgentRepository:
670
878
  "error_code='controller_stopped',completed_at=? WHERE run_id=?",
671
879
  (now, row["run_id"]),
672
880
  )
673
- self._append_event(
674
- database, row["run_id"], "run_interrupted", {}, now
675
- )
881
+ self._append_event(database, row["run_id"], "run_interrupted", {}, now)
676
882
  database.commit()
677
883
  return len(rows)
678
884
 
@@ -727,31 +933,46 @@ class EditAgentRepository:
727
933
  except (json.JSONDecodeError, TypeError) as error:
728
934
  raise ProjectError("storage_corrupt", "Clipen 無法讀取 AI 用量紀錄。", status_code=500) from error
729
935
  return AgentRun(
730
- row["run_id"], row["project_id"], row["base_timeline_id"], row["state"],
731
- row["phase"], row["max_tool_calls"], row["tool_calls"],
732
- row["max_preview_renders"], row["preview_renders"], row["current_revision_id"],
733
- row["final_revision_id"], row["provider"], row["provider_attempt_id"], usage,
734
- row["error_code"], row["created_at"],
735
- row["started_at"], row["completed_at"],
936
+ row["run_id"],
937
+ row["project_id"],
938
+ row["base_timeline_id"],
939
+ row["state"],
940
+ row["phase"],
941
+ row["max_tool_calls"],
942
+ row["tool_calls"],
943
+ row["max_preview_renders"],
944
+ row["preview_renders"],
945
+ row["current_revision_id"],
946
+ row["final_revision_id"],
947
+ row["provider"],
948
+ row["provider_attempt_id"],
949
+ usage,
950
+ row["error_code"],
951
+ row["created_at"],
952
+ row["started_at"],
953
+ row["completed_at"],
736
954
  )
737
955
 
738
956
  @staticmethod
739
957
  def _read_revision(database, revision_id: str) -> AgentRevision:
740
958
  if not isinstance(revision_id, str) or REVISION_ID_PATTERN.fullmatch(revision_id) is None:
741
959
  raise ProjectError("edit_revision_not_found", "找不到剪輯修改版本。", status_code=404)
742
- row = database.execute(
743
- "SELECT * FROM edit_agent_revisions WHERE revision_id=?", (revision_id,)
744
- ).fetchone()
960
+ row = database.execute("SELECT * FROM edit_agent_revisions WHERE revision_id=?", (revision_id,)).fetchone()
745
961
  if row is None:
746
962
  raise ProjectError("edit_revision_not_found", "找不到剪輯修改版本。", status_code=404)
747
963
  try:
748
964
  payload = json.loads(row["payload_json"])
749
- if hashlib.sha256(encoded(payload).encode('utf-8')).hexdigest()!=row['payload_digest']:
750
- raise ValueError('revision content digest mismatch')
965
+ if hashlib.sha256(encoded(payload).encode("utf-8")).hexdigest() != row["payload_digest"]:
966
+ raise ValueError("revision content digest mismatch")
751
967
  timeline = EditTimeline.from_payload(payload)
752
968
  except (json.JSONDecodeError, TypeError, ValueError) as error:
753
969
  raise ProjectError("storage_corrupt", "Clipen 無法讀取剪輯修改版本。", status_code=500) from error
754
970
  return AgentRevision(
755
- row["revision_id"], row["run_id"], row["ordinal"], row["parent_revision_id"],
756
- timeline, row["summary"], row["created_at"],
971
+ row["revision_id"],
972
+ row["run_id"],
973
+ row["ordinal"],
974
+ row["parent_revision_id"],
975
+ timeline,
976
+ row["summary"],
977
+ row["created_at"],
757
978
  )