@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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,757 @@
|
|
|
1
|
+
"""Crash-safe persistence for bounded AI editing sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import sqlite3
|
|
8
|
+
from typing import Mapping
|
|
9
|
+
|
|
10
|
+
from clipen.domain import EditTimeline
|
|
11
|
+
from clipen.projects import ProjectError, ProjectRepository
|
|
12
|
+
from clipen.projects.models import validate_project_id, validate_request_id
|
|
13
|
+
from clipen.projects.storage import command_digest, utc_now
|
|
14
|
+
|
|
15
|
+
from .agent_models import (
|
|
16
|
+
AgentRevision,
|
|
17
|
+
AgentRun,
|
|
18
|
+
REVISION_ID_PATTERN,
|
|
19
|
+
RUN_ID_PATTERN,
|
|
20
|
+
bounded_text,
|
|
21
|
+
encoded,
|
|
22
|
+
make_id,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _closing_message(value: str | None) -> str | None:
|
|
27
|
+
"""Keep the provider's last words to the user short enough to show on the status panel."""
|
|
28
|
+
if not isinstance(value, str) or not value.strip():
|
|
29
|
+
return None
|
|
30
|
+
text = value.strip()
|
|
31
|
+
return text if len(text) <= 2000 else text[:1999].rstrip() + "…"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class EditAgentRepository:
|
|
35
|
+
"""Persist every agent mutation as an immutable revision and append-only event."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, projects: ProjectRepository) -> None:
|
|
38
|
+
self.projects = projects
|
|
39
|
+
|
|
40
|
+
def create_run(
|
|
41
|
+
self,
|
|
42
|
+
project_id: str,
|
|
43
|
+
request_id: object,
|
|
44
|
+
*,
|
|
45
|
+
provider: str = "codex",
|
|
46
|
+
max_tool_calls: int = 80,
|
|
47
|
+
max_preview_renders: int = 4,
|
|
48
|
+
production: dict,
|
|
49
|
+
) -> tuple[AgentRun, bool]:
|
|
50
|
+
"""Start an AI production session; there are no runs without one."""
|
|
51
|
+
validate_project_id(project_id)
|
|
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"}):
|
|
55
|
+
raise ProjectError("production_input_invalid", "請選擇剪輯樣板並填寫影片需求。", status_code=422)
|
|
56
|
+
from clipen.skills import get_skill
|
|
57
|
+
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'])}
|
|
71
|
+
# 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'):
|
|
75
|
+
# 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)
|
|
81
|
+
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 {})}
|
|
89
|
+
creative_direction = {**PROGRAM_DIRECTION, "production_requirements": FULL_PRODUCTION_REQUIREMENTS}
|
|
90
|
+
creative_direction = validate_direction(creative_direction)
|
|
91
|
+
if isinstance(max_tool_calls, bool) or not 1 <= max_tool_calls <= 500:
|
|
92
|
+
raise ValueError("max_tool_calls is invalid")
|
|
93
|
+
if isinstance(max_preview_renders, bool) or not 0 <= max_preview_renders <= 20:
|
|
94
|
+
raise ValueError("max_preview_renders is invalid")
|
|
95
|
+
request_hash = command_digest(
|
|
96
|
+
{
|
|
97
|
+
"provider": provider,
|
|
98
|
+
"max_tool_calls": max_tool_calls,
|
|
99
|
+
"max_preview_renders": max_preview_renders,
|
|
100
|
+
"creative_direction": creative_direction,
|
|
101
|
+
"production": production,
|
|
102
|
+
}
|
|
103
|
+
)
|
|
104
|
+
from clipen.provider_registry import implemented_providers
|
|
105
|
+
if provider not in implemented_providers():
|
|
106
|
+
raise ValueError("provider is invalid")
|
|
107
|
+
run_id = make_id("editrun_", [project_id, request])
|
|
108
|
+
now = utc_now()
|
|
109
|
+
with self.projects.connect(project_id) as database:
|
|
110
|
+
try:
|
|
111
|
+
database.execute("BEGIN IMMEDIATE")
|
|
112
|
+
receipt = database.execute(
|
|
113
|
+
"SELECT command_type,request_hash,response_json "
|
|
114
|
+
"FROM edit_agent_command_receipts WHERE request_id=?",
|
|
115
|
+
(request,),
|
|
116
|
+
).fetchone()
|
|
117
|
+
if receipt is not None:
|
|
118
|
+
if receipt["command_type"] != "start" or receipt["request_hash"] != request_hash:
|
|
119
|
+
raise ProjectError(
|
|
120
|
+
"request_reused",
|
|
121
|
+
"這次操作的識別資訊已用於不同內容。",
|
|
122
|
+
status_code=409,
|
|
123
|
+
)
|
|
124
|
+
replay_id = json.loads(receipt["response_json"])["run_id"]
|
|
125
|
+
result = self._read_run(database, replay_id)
|
|
126
|
+
database.rollback()
|
|
127
|
+
return result, False
|
|
128
|
+
busy = database.execute(
|
|
129
|
+
"SELECT run_id FROM edit_agent_runs "
|
|
130
|
+
"WHERE state IN ('queued','running') LIMIT 1"
|
|
131
|
+
).fetchone()
|
|
132
|
+
if busy is not None:
|
|
133
|
+
raise ProjectError(
|
|
134
|
+
"edit_agent_busy",
|
|
135
|
+
"已有一個 AI 剪輯工作正在進行。",
|
|
136
|
+
status_code=409,
|
|
137
|
+
)
|
|
138
|
+
from clipen.domain import Rational, Track, TrackKind
|
|
139
|
+
from .production_media import source_rows
|
|
140
|
+
sources = source_rows(self.projects, project_id)
|
|
141
|
+
inventory = database.execute("SELECT run_id FROM current_inventory WHERE slot=1").fetchone()
|
|
142
|
+
if inventory is None or not any(s["kind"] == "video" for s in sources):
|
|
143
|
+
raise ProjectError("inventory_required", "請先檢查素材,至少需要一段可用影片。", status_code=409)
|
|
144
|
+
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, ()),),
|
|
147
|
+
production_session_id=run_id,
|
|
148
|
+
)
|
|
149
|
+
payload = timeline.to_payload()
|
|
150
|
+
digest = hashlib.sha256(encoded(payload).encode("utf-8")).hexdigest()
|
|
151
|
+
revision_id = make_id("editrev_", [run_id, 0, digest])
|
|
152
|
+
database.execute(
|
|
153
|
+
"INSERT INTO edit_agent_runs "
|
|
154
|
+
"(run_id,project_id,request_id,base_timeline_id,state,phase,"
|
|
155
|
+
"max_tool_calls,max_preview_renders,current_revision_id,provider,created_at) "
|
|
156
|
+
"VALUES(?,?,?,?,'queued','ready',?,?,?,?,?)",
|
|
157
|
+
(
|
|
158
|
+
run_id,
|
|
159
|
+
project_id,
|
|
160
|
+
request,
|
|
161
|
+
None,
|
|
162
|
+
max_tool_calls,
|
|
163
|
+
max_preview_renders,
|
|
164
|
+
revision_id,
|
|
165
|
+
provider,
|
|
166
|
+
now,
|
|
167
|
+
),
|
|
168
|
+
)
|
|
169
|
+
database.execute(
|
|
170
|
+
"INSERT INTO edit_agent_revisions "
|
|
171
|
+
"(revision_id,run_id,ordinal,parent_revision_id,payload_digest,"
|
|
172
|
+
"payload_json,summary,created_at) VALUES(?,?,0,NULL,?,?,?,?)",
|
|
173
|
+
(revision_id, run_id, digest, encoded(payload), "空白製作草稿", now),
|
|
174
|
+
)
|
|
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)
|
|
180
|
+
database.execute(
|
|
181
|
+
"INSERT INTO edit_agent_command_receipts VALUES(?,?,?,?,?)",
|
|
182
|
+
(request, "start", request_hash, encoded({"run_id": run_id}), now),
|
|
183
|
+
)
|
|
184
|
+
result = self._read_run(database, run_id)
|
|
185
|
+
database.commit()
|
|
186
|
+
return result, True
|
|
187
|
+
except ProjectError:
|
|
188
|
+
database.rollback()
|
|
189
|
+
raise
|
|
190
|
+
except (json.JSONDecodeError, KeyError, TypeError, ValueError, sqlite3.Error) as error:
|
|
191
|
+
database.rollback()
|
|
192
|
+
raise ProjectError(
|
|
193
|
+
"edit_agent_storage_failed",
|
|
194
|
+
"Clipen 無法建立 AI 剪輯工作。",
|
|
195
|
+
status_code=500,
|
|
196
|
+
) from error
|
|
197
|
+
|
|
198
|
+
def production_session(self, project_id: str, run_id: str) -> dict | None:
|
|
199
|
+
self._validate_run_id(run_id)
|
|
200
|
+
with self.projects.connect(project_id) as db:
|
|
201
|
+
row = db.execute("SELECT * FROM production_sessions WHERE run_id=?", (run_id,)).fetchone()
|
|
202
|
+
if row is None:
|
|
203
|
+
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"]}
|
|
207
|
+
|
|
208
|
+
def creative_direction(self, project_id: str, run_id: str) -> dict:
|
|
209
|
+
self._validate_run_id(run_id)
|
|
210
|
+
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',{})
|
|
213
|
+
|
|
214
|
+
def set_target_duration(self, project_id, run_id, expected_revision_id, *, target_duration_seconds, request_excerpt, summary):
|
|
215
|
+
"""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)
|
|
221
|
+
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())
|
|
242
|
+
db.commit()
|
|
243
|
+
return result
|
|
244
|
+
|
|
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):
|
|
246
|
+
from .refinement_references import hand_over, public_state, references
|
|
247
|
+
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)
|
|
252
|
+
if provider is not None:
|
|
253
|
+
from clipen.provider_registry import get_provider
|
|
254
|
+
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 {})})
|
|
257
|
+
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()
|
|
260
|
+
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}
|
|
277
|
+
# What the last change left for the person goes with the next request, so it is not lost.
|
|
278
|
+
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
|
|
282
|
+
# The AI gets this round's notes; only lasting facts stay listed.
|
|
283
|
+
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())
|
|
287
|
+
# A revision is a new request from the user, so the AI Clipen runs with
|
|
288
|
+
# now may take over the draft; it spends its own quota from a fresh budget.
|
|
289
|
+
# 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
|
|
296
|
+
|
|
297
|
+
# Stops that leave a valid draft and say nothing about the draft itself: the
|
|
298
|
+
# wall clock ran out, the provider account hit its usage limit, or the
|
|
299
|
+
# provider ended its turn early. Resuming continues the same revision and
|
|
300
|
+
# budget once the user asks again. A draft blocked by delivery checks needs
|
|
301
|
+
# a revision request instead, since the same instructions hit the same checks.
|
|
302
|
+
# 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'})
|
|
305
|
+
|
|
306
|
+
def resume_stopped(self, project_id: str, run_id: object) -> AgentRun:
|
|
307
|
+
normalized = self._validate_run_id(run_id)
|
|
308
|
+
with self.projects.connect(project_id) as db:
|
|
309
|
+
db.execute('BEGIN IMMEDIATE')
|
|
310
|
+
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)
|
|
314
|
+
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)
|
|
320
|
+
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)
|
|
322
|
+
# The run row only keeps the latest attempt's usage; keep what the
|
|
323
|
+
# 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,))
|
|
329
|
+
result = self._read_run(db, normalized)
|
|
330
|
+
db.commit()
|
|
331
|
+
return result
|
|
332
|
+
|
|
333
|
+
resume_timed_out = resume_stopped
|
|
334
|
+
|
|
335
|
+
def record_machine_sleep(self, project_id: str, run_id: object, periods) -> None:
|
|
336
|
+
"""Note each time the Mac slept during an attempt, so a stall is not blamed on the AI."""
|
|
337
|
+
from datetime import datetime, timezone
|
|
338
|
+
normalized = self._validate_run_id(run_id)
|
|
339
|
+
with self.projects.connect(project_id) as db:
|
|
340
|
+
for start, end in periods:
|
|
341
|
+
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))
|
|
344
|
+
db.commit()
|
|
345
|
+
|
|
346
|
+
def delivery_blockers(self, project_id: str, run_id: object) -> tuple[str, ...] | None:
|
|
347
|
+
"""Issue codes from the latest delivery check of the current revision; None when it was never checked."""
|
|
348
|
+
normalized = self._validate_run_id(run_id)
|
|
349
|
+
with self.projects.connect(project_id) as db:
|
|
350
|
+
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()
|
|
352
|
+
for row in rows:
|
|
353
|
+
value = json.loads(row['payload_json'])
|
|
354
|
+
if value['revision_id'] == run.current_revision_id:
|
|
355
|
+
if value['valid']:
|
|
356
|
+
return ()
|
|
357
|
+
codes = [issue['code'] for issue in value.get('issues', []) + value.get('delivery_issues', [])]
|
|
358
|
+
return tuple(dict.fromkeys(codes)) or ('sequence_invalid',)
|
|
359
|
+
return None
|
|
360
|
+
|
|
361
|
+
def activate(self, project_id: str, run_id: object) -> AgentRun:
|
|
362
|
+
normalized = self._validate_run_id(run_id)
|
|
363
|
+
with self.projects.connect(project_id) as database:
|
|
364
|
+
database.execute("BEGIN IMMEDIATE")
|
|
365
|
+
run = self._read_run(database, normalized)
|
|
366
|
+
if run.state == "queued":
|
|
367
|
+
now = utc_now()
|
|
368
|
+
database.execute(
|
|
369
|
+
"UPDATE edit_agent_runs SET state='running',phase='editing',started_at=? "
|
|
370
|
+
"WHERE run_id=?",
|
|
371
|
+
(now, normalized),
|
|
372
|
+
)
|
|
373
|
+
self._append_event(database, normalized, "run_started", {}, now)
|
|
374
|
+
elif run.state != "running":
|
|
375
|
+
database.rollback()
|
|
376
|
+
raise ProjectError(
|
|
377
|
+
"edit_agent_finished",
|
|
378
|
+
"這次 AI 剪輯工作已經結束。",
|
|
379
|
+
status_code=409,
|
|
380
|
+
)
|
|
381
|
+
result = self._read_run(database, normalized)
|
|
382
|
+
database.commit()
|
|
383
|
+
return result
|
|
384
|
+
|
|
385
|
+
def consume_tool_call(self, project_id: str, run_id: object, tool_name: str) -> AgentRun:
|
|
386
|
+
normalized = self._validate_run_id(run_id)
|
|
387
|
+
bounded_text(tool_name, "工具名稱", 80)
|
|
388
|
+
with self.projects.connect(project_id) as database:
|
|
389
|
+
database.execute("BEGIN IMMEDIATE")
|
|
390
|
+
run = self._read_run(database, normalized)
|
|
391
|
+
if run.state != "running":
|
|
392
|
+
database.rollback()
|
|
393
|
+
raise ProjectError("edit_agent_not_running", "AI 剪輯工作並未執行。", status_code=409)
|
|
394
|
+
if run.tool_calls >= run.max_tool_calls:
|
|
395
|
+
now = utc_now()
|
|
396
|
+
database.execute(
|
|
397
|
+
"UPDATE edit_agent_runs SET state='interrupted',phase='budget_exhausted',"
|
|
398
|
+
"error_code='tool_budget_exhausted',completed_at=? WHERE run_id=?",
|
|
399
|
+
(now, normalized),
|
|
400
|
+
)
|
|
401
|
+
self._append_event(database, normalized, "budget_exhausted", {}, now)
|
|
402
|
+
database.commit()
|
|
403
|
+
raise ProjectError(
|
|
404
|
+
"tool_budget_exhausted",
|
|
405
|
+
"這次 AI 剪輯已達工具呼叫上限。",
|
|
406
|
+
status_code=409,
|
|
407
|
+
)
|
|
408
|
+
database.execute(
|
|
409
|
+
"UPDATE edit_agent_runs SET tool_calls=tool_calls+1 WHERE run_id=?",
|
|
410
|
+
(normalized,),
|
|
411
|
+
)
|
|
412
|
+
now = utc_now()
|
|
413
|
+
self._append_event(database, normalized, "tool_called", {"tool": tool_name}, now)
|
|
414
|
+
result = self._read_run(database, normalized)
|
|
415
|
+
database.commit()
|
|
416
|
+
return result
|
|
417
|
+
|
|
418
|
+
def current_revision(self, project_id: str, run_id: object) -> AgentRevision:
|
|
419
|
+
normalized = self._validate_run_id(run_id)
|
|
420
|
+
with self.projects.connect(project_id) as database:
|
|
421
|
+
run = self._read_run(database, normalized)
|
|
422
|
+
return self._read_revision(database, run.current_revision_id)
|
|
423
|
+
|
|
424
|
+
def save_revision(
|
|
425
|
+
self,
|
|
426
|
+
project_id: str,
|
|
427
|
+
run_id: object,
|
|
428
|
+
timeline: EditTimeline,
|
|
429
|
+
summary: object,
|
|
430
|
+
*,
|
|
431
|
+
expected_revision_id: str | None = None,
|
|
432
|
+
allow_user_edit: bool = False,
|
|
433
|
+
) -> tuple[AgentRevision, bool]:
|
|
434
|
+
normalized = self._validate_run_id(run_id)
|
|
435
|
+
normalized_summary = bounded_text(summary, "修改摘要", 500)
|
|
436
|
+
payload = timeline.to_payload()
|
|
437
|
+
digest = hashlib.sha256(encoded(payload).encode("utf-8")).hexdigest()
|
|
438
|
+
with self.projects.connect(project_id) as database:
|
|
439
|
+
database.execute("BEGIN IMMEDIATE")
|
|
440
|
+
run = self._read_run(database, normalized)
|
|
441
|
+
if expected_revision_id is not None and expected_revision_id != run.current_revision_id:
|
|
442
|
+
raise ProjectError("revision_conflict", "作品版本已更新,請重新讀取目前版本後再修改。", status_code=409)
|
|
443
|
+
if timeline.project_id != project_id or timeline.production_session_id != (
|
|
444
|
+
normalized if run.base_timeline_id is None else None
|
|
445
|
+
):
|
|
446
|
+
raise ProjectError("revision_owner_mismatch", "剪輯版本不屬於這次製作。", status_code=409)
|
|
447
|
+
if run.state != "running" and not (allow_user_edit and run.state not in {"queued", "running"}):
|
|
448
|
+
database.rollback()
|
|
449
|
+
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)
|
|
452
|
+
existing = database.execute(
|
|
453
|
+
"SELECT revision_id FROM edit_agent_revisions WHERE run_id=? AND payload_digest=?",
|
|
454
|
+
(normalized, digest),
|
|
455
|
+
).fetchone()
|
|
456
|
+
if existing is not None:
|
|
457
|
+
database.execute(
|
|
458
|
+
"UPDATE edit_agent_runs SET current_revision_id=?,phase=? WHERE run_id=?",
|
|
459
|
+
(existing["revision_id"], "user_edit" if allow_user_edit else run.phase, normalized),
|
|
460
|
+
)
|
|
461
|
+
if existing["revision_id"] != run.current_revision_id:
|
|
462
|
+
# 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())
|
|
464
|
+
result = self._read_revision(database, existing["revision_id"])
|
|
465
|
+
database.commit()
|
|
466
|
+
return result, False
|
|
467
|
+
ordinal = database.execute(
|
|
468
|
+
"SELECT COALESCE(MAX(ordinal),-1)+1 value FROM edit_agent_revisions WHERE run_id=?",
|
|
469
|
+
(normalized,),
|
|
470
|
+
).fetchone()["value"]
|
|
471
|
+
revision_id = make_id("editrev_", [normalized, ordinal, digest])
|
|
472
|
+
now = utc_now()
|
|
473
|
+
database.execute(
|
|
474
|
+
"INSERT INTO edit_agent_revisions VALUES(?,?,?,?,?,?,?,?)",
|
|
475
|
+
(
|
|
476
|
+
revision_id,
|
|
477
|
+
normalized,
|
|
478
|
+
ordinal,
|
|
479
|
+
run.current_revision_id,
|
|
480
|
+
digest,
|
|
481
|
+
encoded(payload),
|
|
482
|
+
normalized_summary,
|
|
483
|
+
now,
|
|
484
|
+
),
|
|
485
|
+
)
|
|
486
|
+
database.execute(
|
|
487
|
+
"UPDATE edit_agent_runs SET current_revision_id=?,phase=? WHERE run_id=?",
|
|
488
|
+
(revision_id, "user_edit" if allow_user_edit else "editing", normalized),
|
|
489
|
+
)
|
|
490
|
+
self._append_event(
|
|
491
|
+
database,
|
|
492
|
+
normalized,
|
|
493
|
+
"revision_created",
|
|
494
|
+
{"revision_id": revision_id, "summary": normalized_summary},
|
|
495
|
+
now,
|
|
496
|
+
)
|
|
497
|
+
result = self._read_revision(database, revision_id)
|
|
498
|
+
database.commit()
|
|
499
|
+
return result, True
|
|
500
|
+
|
|
501
|
+
def undo(self, project_id: str, run_id: object, *, expected_revision_id: str | None = None) -> AgentRevision:
|
|
502
|
+
normalized = self._validate_run_id(run_id)
|
|
503
|
+
with self.projects.connect(project_id) as database:
|
|
504
|
+
database.execute("BEGIN IMMEDIATE")
|
|
505
|
+
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)
|
|
508
|
+
current = self._read_revision(database, run.current_revision_id)
|
|
509
|
+
if current.parent_revision_id is None:
|
|
510
|
+
database.rollback()
|
|
511
|
+
raise ProjectError("undo_unavailable", "目前已是最初版本。", status_code=409)
|
|
512
|
+
parent = self._read_revision(database, current.parent_revision_id)
|
|
513
|
+
database.execute(
|
|
514
|
+
"UPDATE edit_agent_runs SET current_revision_id=? WHERE run_id=?",
|
|
515
|
+
(parent.revision_id, normalized),
|
|
516
|
+
)
|
|
517
|
+
self._append_event(
|
|
518
|
+
database,
|
|
519
|
+
normalized,
|
|
520
|
+
"revision_selected",
|
|
521
|
+
{"revision_id": parent.revision_id},
|
|
522
|
+
utc_now(),
|
|
523
|
+
)
|
|
524
|
+
database.commit()
|
|
525
|
+
return parent
|
|
526
|
+
|
|
527
|
+
def finish(self, project_id: str, run_id: object, summary: object, *, expected_revision_id: str | None = None, report: dict | None = None) -> AgentRun:
|
|
528
|
+
normalized = self._validate_run_id(run_id)
|
|
529
|
+
normalized_summary = bounded_text(summary, "完成摘要", 1_000)
|
|
530
|
+
with self.projects.connect(project_id) as database:
|
|
531
|
+
database.execute("BEGIN IMMEDIATE")
|
|
532
|
+
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)
|
|
535
|
+
if run.state != "running":
|
|
536
|
+
database.rollback()
|
|
537
|
+
raise ProjectError("edit_agent_not_running", "AI 剪輯工作並未執行。", status_code=409)
|
|
538
|
+
now = utc_now()
|
|
539
|
+
database.execute(
|
|
540
|
+
"UPDATE edit_agent_runs SET state='succeeded',phase='completed',"
|
|
541
|
+
"final_revision_id=current_revision_id,completed_at=? WHERE run_id=?",
|
|
542
|
+
(now, normalized),
|
|
543
|
+
)
|
|
544
|
+
self._append_event(database, normalized, "run_finished", {"summary": normalized_summary, **({"report": report} if report else {})}, now)
|
|
545
|
+
result = self._read_run(database, normalized)
|
|
546
|
+
database.commit()
|
|
547
|
+
return result
|
|
548
|
+
|
|
549
|
+
def record_provider_outcome(
|
|
550
|
+
self,
|
|
551
|
+
project_id: str,
|
|
552
|
+
run_id: object,
|
|
553
|
+
attempt_id: str,
|
|
554
|
+
*,
|
|
555
|
+
usage: Mapping[str, int] | None,
|
|
556
|
+
error_code: str | None = None,
|
|
557
|
+
message: str | None = None,
|
|
558
|
+
) -> AgentRun:
|
|
559
|
+
normalized = self._validate_run_id(run_id)
|
|
560
|
+
bounded_text(attempt_id, "Provider attempt", 128)
|
|
561
|
+
if error_code is not None:
|
|
562
|
+
bounded_text(error_code, "Provider 錯誤", 128)
|
|
563
|
+
usage_json = None
|
|
564
|
+
if usage is not None:
|
|
565
|
+
expected = {"input_tokens", "cached_input_tokens", "output_tokens"}
|
|
566
|
+
if set(usage) != expected or any(
|
|
567
|
+
isinstance(value, bool) or not isinstance(value, int) or value < 0
|
|
568
|
+
for value in usage.values()
|
|
569
|
+
):
|
|
570
|
+
raise ValueError("provider usage is invalid")
|
|
571
|
+
if usage["cached_input_tokens"] > usage["input_tokens"]:
|
|
572
|
+
raise ValueError("provider cached usage exceeds input usage")
|
|
573
|
+
usage_json = encoded(dict(usage))
|
|
574
|
+
with self.projects.connect(project_id) as database:
|
|
575
|
+
database.execute("BEGIN IMMEDIATE")
|
|
576
|
+
run = self._read_run(database, normalized)
|
|
577
|
+
now = utc_now()
|
|
578
|
+
if error_code is not None and run.state in {"queued", "running"}:
|
|
579
|
+
database.execute(
|
|
580
|
+
"UPDATE edit_agent_runs SET state='failed',phase='failed',error_code=?,"
|
|
581
|
+
"provider_attempt_id=?,usage_json=?,completed_at=? WHERE run_id=?",
|
|
582
|
+
(error_code, attempt_id, usage_json, now, normalized),
|
|
583
|
+
)
|
|
584
|
+
else:
|
|
585
|
+
database.execute(
|
|
586
|
+
"UPDATE edit_agent_runs SET provider_attempt_id=?,usage_json=? WHERE run_id=?",
|
|
587
|
+
(attempt_id, usage_json, normalized),
|
|
588
|
+
)
|
|
589
|
+
self._append_event(
|
|
590
|
+
database,
|
|
591
|
+
normalized,
|
|
592
|
+
"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)},
|
|
595
|
+
now,
|
|
596
|
+
)
|
|
597
|
+
result = self._read_run(database, normalized)
|
|
598
|
+
database.commit()
|
|
599
|
+
return result
|
|
600
|
+
|
|
601
|
+
def get(self, project_id: str, run_id: object) -> AgentRun:
|
|
602
|
+
normalized = self._validate_run_id(run_id)
|
|
603
|
+
with self.projects.connect(project_id) as database:
|
|
604
|
+
return self._read_run(database, normalized)
|
|
605
|
+
|
|
606
|
+
def latest(self, project_id: str) -> AgentRun | None:
|
|
607
|
+
validate_project_id(project_id)
|
|
608
|
+
with self.projects.connect(project_id) as database:
|
|
609
|
+
row = database.execute(
|
|
610
|
+
"SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1"
|
|
611
|
+
).fetchone()
|
|
612
|
+
return None if row is None else self._read_run(database, row["run_id"])
|
|
613
|
+
|
|
614
|
+
def latest_successful(self, project_id: str) -> AgentRun | None:
|
|
615
|
+
"""Return the newest published result, preserving it across failed retries."""
|
|
616
|
+
|
|
617
|
+
validate_project_id(project_id)
|
|
618
|
+
with self.projects.connect(project_id) as database:
|
|
619
|
+
row = database.execute(
|
|
620
|
+
"SELECT run_id FROM edit_agent_runs "
|
|
621
|
+
"WHERE state='succeeded' AND final_revision_id IS NOT NULL "
|
|
622
|
+
"ORDER BY completed_at DESC,rowid DESC LIMIT 1"
|
|
623
|
+
).fetchone()
|
|
624
|
+
return None if row is None else self._read_run(database, row["run_id"])
|
|
625
|
+
|
|
626
|
+
def final_revision(self, project_id: str, run_id: object) -> AgentRevision:
|
|
627
|
+
"""Return the immutable result only after the run finished successfully."""
|
|
628
|
+
|
|
629
|
+
normalized = self._validate_run_id(run_id)
|
|
630
|
+
with self.projects.connect(project_id) as database:
|
|
631
|
+
run = self._read_run(database, normalized)
|
|
632
|
+
if run.state != "succeeded" or run.final_revision_id is None:
|
|
633
|
+
raise ProjectError(
|
|
634
|
+
"edit_agent_result_not_ready",
|
|
635
|
+
"AI 剪輯版本尚未完成。",
|
|
636
|
+
status_code=409,
|
|
637
|
+
)
|
|
638
|
+
return self._read_revision(database, run.final_revision_id)
|
|
639
|
+
|
|
640
|
+
def cancel(self, project_id: str, run_id: object) -> AgentRun:
|
|
641
|
+
normalized = self._validate_run_id(run_id)
|
|
642
|
+
with self.projects.connect(project_id) as database:
|
|
643
|
+
database.execute("BEGIN IMMEDIATE")
|
|
644
|
+
run = self._read_run(database, normalized)
|
|
645
|
+
if run.state in {"succeeded", "failed", "cancelled", "interrupted"}:
|
|
646
|
+
database.rollback()
|
|
647
|
+
return run
|
|
648
|
+
now = utc_now()
|
|
649
|
+
database.execute(
|
|
650
|
+
"UPDATE edit_agent_runs SET state='cancelled',phase='cancelled',"
|
|
651
|
+
"error_code='user_cancelled',completed_at=? WHERE run_id=?",
|
|
652
|
+
(now, normalized),
|
|
653
|
+
)
|
|
654
|
+
self._append_event(database, normalized, "run_cancelled", {}, now)
|
|
655
|
+
result = self._read_run(database, normalized)
|
|
656
|
+
database.commit()
|
|
657
|
+
return result
|
|
658
|
+
|
|
659
|
+
def interrupt_incomplete(self, project_id: str) -> int:
|
|
660
|
+
validate_project_id(project_id)
|
|
661
|
+
with self.projects.connect(project_id) as database:
|
|
662
|
+
database.execute("BEGIN IMMEDIATE")
|
|
663
|
+
rows = database.execute(
|
|
664
|
+
"SELECT run_id FROM edit_agent_runs WHERE state IN ('queued','running')"
|
|
665
|
+
).fetchall()
|
|
666
|
+
now = utc_now()
|
|
667
|
+
for row in rows:
|
|
668
|
+
database.execute(
|
|
669
|
+
"UPDATE edit_agent_runs SET state='interrupted',phase='interrupted',"
|
|
670
|
+
"error_code='controller_stopped',completed_at=? WHERE run_id=?",
|
|
671
|
+
(now, row["run_id"]),
|
|
672
|
+
)
|
|
673
|
+
self._append_event(
|
|
674
|
+
database, row["run_id"], "run_interrupted", {}, now
|
|
675
|
+
)
|
|
676
|
+
database.commit()
|
|
677
|
+
return len(rows)
|
|
678
|
+
|
|
679
|
+
def interrupt_for_shutdown(self, project_id: str, run_id: object) -> AgentRun:
|
|
680
|
+
"""Record Controller shutdown after its provider process has been stopped."""
|
|
681
|
+
|
|
682
|
+
normalized = self._validate_run_id(run_id)
|
|
683
|
+
with self.projects.connect(project_id) as database:
|
|
684
|
+
database.execute("BEGIN IMMEDIATE")
|
|
685
|
+
run = self._read_run(database, normalized)
|
|
686
|
+
may_interrupt = run.state in {"queued", "running"} or (
|
|
687
|
+
run.state == "failed" and run.error_code == "provider_cancelled"
|
|
688
|
+
)
|
|
689
|
+
if not may_interrupt:
|
|
690
|
+
database.rollback()
|
|
691
|
+
return run
|
|
692
|
+
now = utc_now()
|
|
693
|
+
database.execute(
|
|
694
|
+
"UPDATE edit_agent_runs SET state='interrupted',phase='interrupted',"
|
|
695
|
+
"error_code='controller_stopped',completed_at=? WHERE run_id=?",
|
|
696
|
+
(now, normalized),
|
|
697
|
+
)
|
|
698
|
+
self._append_event(database, normalized, "run_interrupted", {}, now)
|
|
699
|
+
result = self._read_run(database, normalized)
|
|
700
|
+
database.commit()
|
|
701
|
+
return result
|
|
702
|
+
|
|
703
|
+
@staticmethod
|
|
704
|
+
def _validate_run_id(value: object) -> str:
|
|
705
|
+
if not isinstance(value, str) or RUN_ID_PATTERN.fullmatch(value) is None:
|
|
706
|
+
raise ProjectError("edit_agent_not_found", "找不到 AI 剪輯工作。", status_code=404)
|
|
707
|
+
return value
|
|
708
|
+
|
|
709
|
+
@staticmethod
|
|
710
|
+
def _append_event(database, run_id: str, event_type: str, payload: object, now: str) -> None:
|
|
711
|
+
# Background preview completion can race a foreground tool call. Keep
|
|
712
|
+
# sequence allocation and insertion in one write statement, including
|
|
713
|
+
# callers that intentionally use SQLite autocommit.
|
|
714
|
+
database.execute(
|
|
715
|
+
"INSERT INTO edit_agent_events(run_id,sequence,event_type,payload_json,created_at) "
|
|
716
|
+
"SELECT ?,COALESCE(MAX(sequence),0)+1,?,?,? FROM edit_agent_events WHERE run_id=?",
|
|
717
|
+
(run_id, event_type, encoded(payload), now, run_id),
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
@staticmethod
|
|
721
|
+
def _read_run(database, run_id: str) -> AgentRun:
|
|
722
|
+
row = database.execute("SELECT * FROM edit_agent_runs WHERE run_id=?", (run_id,)).fetchone()
|
|
723
|
+
if row is None:
|
|
724
|
+
raise ProjectError("edit_agent_not_found", "找不到 AI 剪輯工作。", status_code=404)
|
|
725
|
+
try:
|
|
726
|
+
usage = None if row["usage_json"] is None else json.loads(row["usage_json"])
|
|
727
|
+
except (json.JSONDecodeError, TypeError) as error:
|
|
728
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取 AI 用量紀錄。", status_code=500) from error
|
|
729
|
+
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"],
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
@staticmethod
|
|
739
|
+
def _read_revision(database, revision_id: str) -> AgentRevision:
|
|
740
|
+
if not isinstance(revision_id, str) or REVISION_ID_PATTERN.fullmatch(revision_id) is None:
|
|
741
|
+
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()
|
|
745
|
+
if row is None:
|
|
746
|
+
raise ProjectError("edit_revision_not_found", "找不到剪輯修改版本。", status_code=404)
|
|
747
|
+
try:
|
|
748
|
+
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')
|
|
751
|
+
timeline = EditTimeline.from_payload(payload)
|
|
752
|
+
except (json.JSONDecodeError, TypeError, ValueError) as error:
|
|
753
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取剪輯修改版本。", status_code=500) from error
|
|
754
|
+
return AgentRevision(
|
|
755
|
+
row["revision_id"], row["run_id"], row["ordinal"], row["parent_revision_id"],
|
|
756
|
+
timeline, row["summary"], row["created_at"],
|
|
757
|
+
)
|