-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent_tools.py
More file actions
3186 lines (2908 loc) · 152 KB
/
Copy pathagent_tools.py
File metadata and controls
3186 lines (2908 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Custom Copilot tools exposing Shotwright container and project controls."""
from __future__ import annotations
import asyncio
import hashlib
import json
import math
import os
import re
import shutil
import subprocess
import sys
import threading
import wave
from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4
from copilot.tools import Tool, ToolInvocation, ToolResult
from app.config import settings
from app.database import get_admin_collection, get_message_collection, get_session_collection
from app.services import container_manager as cm
from app.services import nexrender as nr
from app.services import project_manager as pm
from app.services import reference_media as rm
from app.services import tts as tts_media
from app.services.codex_config import resolve_openai_api_key
from app.services.session_streams import publish_context_refresh, publish_session_updated
from app.services.video_streaming import generate_hls
_REFERENCE_ASSET_DIRECTORY = Path("assets") / "references"
_AUDIO_ASSET_DIRECTORY = Path("assets") / "audio"
_PYTHON_TOOL_SCRIPT_DIRECTORY = Path(".shotwright-python")
_PYTHON_TOOL_OUTPUT_LIMIT = 24_000
_PYTHON_TOOL_FILE_LIST_LIMIT = 80
_PYTHON_TOOL_SNAPSHOT_LIMIT = 5_000
_PYTHON_TOOL_ENV_STATE_FILENAME = ".shotwright-python-runtime.json"
_PYTHON_TOOL_DEFAULT_REQUIREMENTS_NAME = "requirements-aigc.txt"
_PYTHON_TOOL_ENV_LOCK = threading.Lock()
_AFTER_EFFECTS_SCRIPT_EXTENSIONS = {".js", ".jsx", ".jsxinc"}
_SENSITIVE_ENV_NAMES = (
"GITHUB_TOKEN",
"SHOTWRIGHT_GITHUB_TOKEN",
"OPENAI_API_KEY",
"SHOTWRIGHT_OPENAI_API_KEY",
"SHOTWRIGHT_TTS_OPENAI_API_KEY",
"SHOTWRIGHT_TTS_AZURE_SPEECH_KEY",
"SHOTWRIGHT_TTS_ELEVENLABS_API_KEY",
"AZURE_SPEECH_KEY",
"SPEECH_KEY",
"ELEVENLABS_API_KEY",
"ANTHROPIC_API_KEY",
)
_PYTHON_REQUIREMENT_IMPORT_NAMES = {
"edge-tts": "edge_tts",
"faster-whisper": "faster_whisper",
"imageio-ffmpeg": "imageio_ffmpeg",
"opencv-contrib-python": "cv2",
"opencv-contrib-python-headless": "cv2",
"opencv-python": "cv2",
"opencv-python-headless": "cv2",
"openai-whisper": "whisper",
"pillow": "PIL",
"python-dotenv": "dotenv",
"pyyaml": "yaml",
"scikit-image": "skimage",
"scikit-learn": "sklearn",
}
_PYTHON_REQUIREMENT_NAME_RE = re.compile(r"^\s*([A-Za-z0-9_.-]+)")
SHOTWRIGHT_RECOMMENDED_FONTS = {
"default_chinese_caption": {
"postscript_names": [
"NotoSansSC-Bold",
"NotoSansSC-Medium",
"NotoSansSC-Regular",
"MicrosoftYaHei-Bold",
"MicrosoftYaHeiUI-Bold",
"SimHei",
"SimSun",
],
"notes": "Use for Simplified Chinese subtitles and body text. Prefer PostScript names, not UI display names.",
},
"cute_handwritten_chinese": {
"postscript_names": [
"LXGWWenKai-Medium",
"LXGWWenKai-Regular",
"NotoSansSC-Bold",
],
"notes": "Use for cute pet stickers, friendly captions, and informal Chinese labels.",
},
"serif_chinese_title": {
"postscript_names": [
"NotoSerifSC-Bold",
"NotoSerifSC-Medium",
"NotoSerifSC-Regular",
"SimSun",
],
"notes": "Use for editorial title cards or premium Chinese title treatment.",
},
"avoid_for_chinese": [
"MS-Gothic",
"MSGothic",
"YuGothic",
],
"license": "Bundled recommended families are SIL Open Font License 1.1 fonts installed by scripts/install/install_open_fonts.ps1.",
}
SHOTWRIGHT_CREATIVE_QUALITY_POLICY = {
"intent_before_execution": [
"Choose an audience, emotion, story beat, and visual idea before writing JSX; the style should explain the content, not decorate it generically.",
"For reference-driven work, let the source footage decide rhythm, framing, and text placement before adding effects.",
"Name the creative reason for each major visual system: typography, motion, color, transitions, stickers, cards, or sound cues.",
],
"avoid_low_effort_success": [
"A render that is technically valid but visually plain, muddy, generic, or hard to read is not finished.",
"Do not satisfy broad style words by scattering random transitions, stickers, or text effects; each element must support the story beat.",
"Do not use stale QA, placeholder comps, or whole-frame pixel ratios as proof of creative quality.",
],
"storyboard_self_review": [
"After rendering, inspect full-frame and focused storyboards and identify the weakest frame before finalizing.",
"Ask whether the result has a clear first impression on a phone-sized screen, a coherent visual hierarchy, readable text, and at least one deliberate memorable moment.",
"If the storyboard only proves that nothing is broken, revise the design instead of finalizing.",
],
}
SHOTWRIGHT_SUBTITLE_STYLE_POLICY = {
"principles": [
"Do not force a universal subtitle look; choose typography, backing, contrast, and motion from the current art direction and footage.",
"Subtitle design is part of the creative idea. It should feel intentional in the storyboard, not merely pass a readability checklist.",
"Dense or busy footage needs an explicit separation strategy, but the strategy can be any style that fits the piece.",
],
"quality_risks": [
"Heavy dark strokes or shadows that become the visible style instead of a readability aid.",
"Text placed directly over busy footage without a deliberate contrast or layout reason.",
"Style labels such as cute, premium, TVC, or Douyin that are claimed in the response but not visible in storyboard frames.",
"Repeating a black-dominant caption treatment after the user rejects black subtitles.",
],
"qa_checks": [
"Inspect actual text layer fill, stroke, shadow, and backing-shape colors in JSX or AE properties before rendering.",
"Review cropped subtitle-zone storyboard frames at a large enough size; do not rely on whole-frame black-pixel ratios.",
"If captions are technically legible but visually weak, muddy, generic, or disconnected from the footage, revise before finalizing.",
],
}
def _tool_success(payload: dict, session_log: str) -> ToolResult:
return ToolResult(
text_result_for_llm=_serialize_tool_payload(payload),
result_type="success",
session_log=session_log,
)
def _tool_failure(message: str, *, error: str | None = None) -> ToolResult:
return ToolResult(
text_result_for_llm=message,
result_type="failure",
error=error or message,
)
def _normalize_tool_payload_value(value: object) -> object:
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, datetime):
return value.isoformat()
if isinstance(value, Path):
return str(value)
if isinstance(value, dict):
return {str(key): _normalize_tool_payload_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [_normalize_tool_payload_value(item) for item in value]
return str(value)
def _serialize_tool_payload(payload: dict) -> str:
return json.dumps(_normalize_tool_payload_value(payload), ensure_ascii=False)
def _truncate_text(value: str, limit: int = _PYTHON_TOOL_OUTPUT_LIMIT) -> str:
if len(value) <= limit:
return value
omitted = len(value) - limit
return f"{value[:limit]}\n... <truncated {omitted} chars>"
def _redact_sensitive_text(value: str) -> str:
redacted = value
for env_name in _SENSITIVE_ENV_NAMES:
secret = os.environ.get(env_name)
if secret and len(secret) >= 6:
redacted = redacted.replace(secret, f"<redacted:{env_name}>")
return redacted
def _path_is_inside(path: Path, root: Path) -> bool:
try:
path.resolve().relative_to(root.resolve())
return True
except ValueError:
return False
def _snapshot_workspace_files(root: Path, *, limit: int = _PYTHON_TOOL_SNAPSHOT_LIMIT) -> dict[str, tuple[int, int]]:
if not root.exists():
return {}
snapshot: dict[str, tuple[int, int]] = {}
for path in root.rglob("*"):
if not path.is_file():
continue
try:
relative_path = path.relative_to(root).as_posix()
stat = path.stat()
except OSError:
continue
snapshot[relative_path] = (stat.st_size, stat.st_mtime_ns)
if len(snapshot) >= limit:
break
return snapshot
def _diff_workspace_files(
before: dict[str, tuple[int, int]],
after: dict[str, tuple[int, int]],
*,
limit: int = _PYTHON_TOOL_FILE_LIST_LIMIT,
) -> list[dict]:
changed: list[dict] = []
for relative_path, state in sorted(after.items()):
previous_state = before.get(relative_path)
if previous_state == state:
continue
size_bytes, _mtime_ns = state
changed.append(
{
"relative_path": relative_path,
"size_bytes": size_bytes,
"change_type": "created" if previous_state is None else "modified",
}
)
if len(changed) >= limit:
break
return changed
def _split_configured_paths(value: str) -> list[Path]:
paths: list[Path] = []
for chunk in re.split(r"[;\r\n]+", value):
normalized = chunk.strip().strip('"').strip("'")
if normalized:
paths.append(Path(normalized))
return paths
def _python_tool_runtime_root() -> Path:
return Path(settings.python_tool_runtime_dir or "C:\\data\\python").resolve()
def _python_tool_venv_dir() -> Path:
configured = str(settings.python_tool_venv_dir or "").strip()
return Path(configured).resolve() if configured else (_python_tool_runtime_root() / "aigc-venv").resolve()
def _python_tool_pip_cache_dir() -> Path:
configured = str(settings.python_tool_pip_cache_dir or "").strip()
return Path(configured).resolve() if configured else (_python_tool_runtime_root() / "pip-cache").resolve()
def _python_tool_state_path(venv_dir: Path) -> Path:
return venv_dir / _PYTHON_TOOL_ENV_STATE_FILENAME
def _python_tool_venv_python(venv_dir: Path) -> Path:
if os.name == "nt":
return venv_dir / "Scripts" / "python.exe"
return venv_dir / "bin" / "python"
def _resolve_python_tool_requirements_paths() -> list[Path]:
configured = str(settings.python_tool_requirements or "").strip()
if configured:
return [path.resolve() for path in _split_configured_paths(configured)]
runtime_requirements = _python_tool_runtime_root() / _PYTHON_TOOL_DEFAULT_REQUIREMENTS_NAME
if runtime_requirements.exists():
return [runtime_requirements.resolve()]
return []
def _hash_python_tool_requirements(requirements_paths: list[Path]) -> str:
digest = hashlib.sha256()
digest.update(sys.version.encode("utf-8", errors="replace"))
digest.update(str(bool(settings.python_tool_system_site_packages)).encode("ascii"))
for requirements_path in requirements_paths:
digest.update(str(requirements_path).encode("utf-8", errors="replace"))
digest.update(b"\0")
digest.update(requirements_path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
def _parse_python_requirement_imports(requirements_paths: list[Path]) -> list[str]:
imports: set[str] = set()
for requirements_path in requirements_paths:
try:
lines = requirements_path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
for raw_line in lines:
line = raw_line.split("#", 1)[0].strip()
if not line or line.startswith("-") or "://" in line:
continue
line = line.split(";", 1)[0].strip()
match = _PYTHON_REQUIREMENT_NAME_RE.match(line)
if not match:
continue
package_name = match.group(1).lower().replace("_", "-")
module_name = _PYTHON_REQUIREMENT_IMPORT_NAMES.get(package_name, package_name.replace("-", "_"))
if module_name:
imports.add(module_name)
return sorted(imports)
def _probe_python_tool_imports(
python_path: Path,
required_imports: list[str],
*,
timeout_seconds: int,
) -> tuple[bool, list[str], str]:
if not required_imports:
return True, [], ""
probe_script = (
"import importlib, json, sys\n"
f"mods = {json.dumps(required_imports, ensure_ascii=True)}\n"
"missing = []\n"
"for mod in mods:\n"
" try:\n"
" importlib.import_module(mod)\n"
" except Exception as exc:\n"
" missing.append({'module': mod, 'error': exc.__class__.__name__ + ': ' + str(exc)[:160]})\n"
"print(json.dumps({'missing': missing}, ensure_ascii=False))\n"
"sys.exit(1 if missing else 0)\n"
)
try:
completed = _run_python_runtime_command(
[str(python_path), "-c", probe_script],
timeout_seconds=max(15, min(timeout_seconds, 120)),
)
except (OSError, subprocess.TimeoutExpired) as exc:
return False, required_imports, str(exc)
output = (completed.stdout or completed.stderr or "").strip()
missing_modules: list[str] = []
for line in reversed([item.strip() for item in output.splitlines() if item.strip()]):
try:
parsed = json.loads(line)
except json.JSONDecodeError:
continue
raw_missing = parsed.get("missing") if isinstance(parsed, dict) else None
if isinstance(raw_missing, list):
for item in raw_missing:
if isinstance(item, dict) and str(item.get("module") or "").strip():
missing_modules.append(str(item["module"]))
elif isinstance(item, str) and item.strip():
missing_modules.append(item.strip())
break
if completed.returncode == 0 and not missing_modules:
return True, [], output
if not missing_modules:
missing_modules = required_imports
return False, sorted(set(missing_modules)), output
def _read_python_tool_state(state_path: Path) -> dict:
try:
return json.loads(state_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
def _write_python_tool_state(state_path: Path, state: dict) -> None:
state_path.parent.mkdir(parents=True, exist_ok=True)
state_path.write_text(json.dumps(_normalize_tool_payload_value(state), ensure_ascii=False, indent=2), encoding="utf-8")
def _run_python_runtime_command(
command: list[str],
*,
timeout_seconds: int,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
command,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout_seconds,
env=env,
)
def _build_python_tool_runtime_env_patch(runtime: dict) -> dict[str, str]:
venv_dir = str(runtime.get("venv_dir") or "").strip()
if not venv_dir:
return {}
scripts_dir = Path(venv_dir) / ("Scripts" if os.name == "nt" else "bin")
path_value = os.environ.get("PATH") or ""
return {
"VIRTUAL_ENV": venv_dir,
"PATH": f"{scripts_dir}{os.pathsep}{path_value}" if path_value else str(scripts_dir),
"SHOTWRIGHT_PYTHON_RUNTIME_DIR": str(runtime.get("runtime_dir") or ""),
"SHOTWRIGHT_PYTHON_VENV_DIR": venv_dir,
"SHOTWRIGHT_PYTHON_REQUIREMENTS": os.pathsep.join(str(path) for path in runtime.get("requirements_paths") or []),
}
def _sync_python_tool_runtime() -> tuple[Path, dict, dict[str, str], str | None]:
runtime = {
"enabled": bool(settings.python_tool_auto_sync_dependencies),
"runtime_dir": str(_python_tool_runtime_root()),
"venv_dir": None,
"pip_cache_dir": None,
"requirements_paths": [],
"requirements_fingerprint": None,
"synced": False,
"sync_elapsed_ms": 0,
"using_system_site_packages": bool(settings.python_tool_system_site_packages),
}
if not settings.python_tool_auto_sync_dependencies:
return Path(sys.executable), runtime, {}, None
requirements_paths = _resolve_python_tool_requirements_paths()
missing_paths = [str(path) for path in requirements_paths if not path.is_file()]
if not requirements_paths:
runtime["enabled"] = False
return Path(sys.executable), runtime, {}, None
if missing_paths:
return Path(sys.executable), runtime, {}, f"Python requirements file not found: {', '.join(missing_paths)}"
venv_dir = _python_tool_venv_dir()
venv_python = _python_tool_venv_python(venv_dir)
pip_cache_dir = _python_tool_pip_cache_dir()
state_path = _python_tool_state_path(venv_dir)
fingerprint = _hash_python_tool_requirements(requirements_paths)
runtime.update(
{
"venv_dir": str(venv_dir),
"pip_cache_dir": str(pip_cache_dir),
"requirements_paths": [str(path) for path in requirements_paths],
"requirements_fingerprint": fingerprint,
}
)
started_at = datetime.now(timezone.utc)
try:
venv_dir.mkdir(parents=True, exist_ok=True)
pip_cache_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
return Path(sys.executable), runtime, {}, f"Could not prepare Python runtime directories: {exc}"
sync_timeout_seconds = max(30, int(settings.python_tool_dependency_sync_timeout_seconds or 1800))
if not venv_python.exists():
venv_command = [sys.executable, "-m", "venv"]
if settings.python_tool_system_site_packages:
venv_command.append("--system-site-packages")
venv_command.append(str(venv_dir))
try:
completed = _run_python_runtime_command(venv_command, timeout_seconds=sync_timeout_seconds)
except (OSError, subprocess.TimeoutExpired) as exc:
return Path(sys.executable), runtime, {}, f"Could not create Python tool venv: {exc}"
if completed.returncode != 0:
output = _truncate_text(_redact_sensitive_text((completed.stderr or completed.stdout or "").strip()), 4000)
return Path(sys.executable), runtime, {}, f"Could not create Python tool venv: {output}"
state = _read_python_tool_state(state_path)
required_imports = _parse_python_requirement_imports(requirements_paths)
runtime["required_imports"] = required_imports
runtime["import_probe"] = {
"checked": False,
"ok": None,
"missing_imports": [],
}
should_install = state.get("requirements_fingerprint") != fingerprint
if not should_install:
probe_ok, missing_imports, probe_output = _probe_python_tool_imports(
venv_python,
required_imports,
timeout_seconds=sync_timeout_seconds,
)
runtime["import_probe"] = {
"checked": True,
"ok": probe_ok,
"missing_imports": missing_imports,
}
if not probe_ok:
should_install = True
runtime["repair_reason"] = (
"missing_imports:" + ",".join(missing_imports)
if missing_imports
else _truncate_text(_redact_sensitive_text(probe_output), 1000)
)
if should_install:
pip_env = os.environ.copy()
pip_env.update(
{
"PYTHONIOENCODING": "utf-8",
"PIP_CACHE_DIR": str(pip_cache_dir),
"PIP_DISABLE_PIP_VERSION_CHECK": "1",
}
)
pip_timeout = str(os.environ.get("PIP_DEFAULT_TIMEOUT") or "120")
pip_command = [
str(venv_python),
"-m",
"pip",
"install",
"--disable-pip-version-check",
"--progress-bar",
"off",
"--retries",
"10",
"--timeout",
pip_timeout,
]
for requirements_path in requirements_paths:
pip_command.extend(["-r", str(requirements_path)])
try:
completed = _run_python_runtime_command(pip_command, timeout_seconds=sync_timeout_seconds, env=pip_env)
except (OSError, subprocess.TimeoutExpired) as exc:
return venv_python, runtime, _build_python_tool_runtime_env_patch(runtime), f"Could not sync Python packages: {exc}"
if completed.returncode != 0:
output = _truncate_text(_redact_sensitive_text((completed.stderr or completed.stdout or "").strip()), 4000)
return venv_python, runtime, _build_python_tool_runtime_env_patch(runtime), f"Could not sync Python packages: {output}"
probe_ok, missing_imports, probe_output = _probe_python_tool_imports(
venv_python,
required_imports,
timeout_seconds=sync_timeout_seconds,
)
runtime["import_probe"] = {
"checked": True,
"ok": probe_ok,
"missing_imports": missing_imports,
}
if not probe_ok:
output = _truncate_text(_redact_sensitive_text(probe_output), 2000)
missing = ", ".join(missing_imports) if missing_imports else "unknown modules"
return (
venv_python,
runtime,
_build_python_tool_runtime_env_patch(runtime),
f"Python runtime dependencies are still missing after sync: {missing}. {output}",
)
runtime["synced"] = True
_write_python_tool_state(
state_path,
{
"requirements_fingerprint": fingerprint,
"requirements_paths": [str(path) for path in requirements_paths],
"required_imports": required_imports,
"python_executable": str(venv_python),
"import_probe_ok": True,
"synced_at": datetime.now(timezone.utc),
},
)
runtime["sync_elapsed_ms"] = int((datetime.now(timezone.utc) - started_at).total_seconds() * 1000)
return venv_python, runtime, _build_python_tool_runtime_env_patch(runtime), None
async def _ensure_python_tool_runtime() -> tuple[Path, dict, dict[str, str], str | None]:
return await asyncio.to_thread(_ensure_python_tool_runtime_sync)
def _ensure_python_tool_runtime_sync() -> tuple[Path, dict, dict[str, str], str | None]:
with _PYTHON_TOOL_ENV_LOCK:
return _sync_python_tool_runtime()
def _sanitize_asset_file_name(value: str | None, fallback_stem: str, suffix: str) -> str:
raw_name = Path(value).name if value else ""
raw_stem = Path(raw_name).stem.strip() if raw_name else fallback_stem
safe_stem = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', '-', raw_stem).strip().strip('.') or fallback_stem
resolved_suffix = Path(raw_name).suffix.lower() if raw_name else suffix.lower()
if resolved_suffix and not resolved_suffix.startswith('.'):
resolved_suffix = f'.{resolved_suffix}'
return f"{safe_stem}{resolved_suffix or suffix}"
def _jsx_string(value: str) -> str:
return json.dumps(Path(value).as_posix())
def _should_reuse_generated_project_workspace(project: dict | None) -> bool:
if not isinstance(project, dict):
return False
if str(project.get("origin") or "").strip().lower() != "generated":
return False
workspace_dir = str(project.get("workspace_dir") or "").strip()
entry_aep_file = str(project.get("entry_aep_file") or project.get("filename") or "").strip()
if not workspace_dir or not entry_aep_file:
return False
aep_files = [str(path).strip() for path in (project.get("aep_files") or []) if str(path).strip()]
return not aep_files and Path(workspace_dir).exists()
def _tts_provider_needs_python_runtime(raw_provider: object) -> bool:
provider = str(raw_provider or settings.tts_provider or "").strip().lower().replace("-", "_")
return provider in {"edge", "edge_tts", "microsoft_edge"}
def _build_safe_after_effects_demo_script() -> str:
return r"""
(function () {
app.beginUndoGroup("Shotwright safe motion demo");
var proj = app.project;
if (!proj) { app.newProject(); proj = app.project; }
while (proj.items.length > 0) {
try { proj.items[1].remove(); } catch (clearError) { break; }
}
var W = 1920, H = 1080, FPS = 30, DUR = 7;
var comp = proj.items.addComp("Main", W, H, 1, DUR, FPS);
comp.bgColor = [0.002, 0.003, 0.012];
comp.motionBlur = true;
comp.shutterAngle = 180;
function p(group, name) { try { return group ? group.property(name) : null; } catch (error) { return null; } }
function t(layer) { return p(layer, "ADBE Transform Group"); }
function setv(prop, value) { try { if (prop) { prop.setValue(value); } } catch (error) {} }
function key(prop, time, value) { try { if (prop) { prop.setValueAtTime(time, value); } } catch (error) {} }
function set2d(layer, x, y) { setv(p(t(layer), "ADBE Position"), [x, y]); }
function set3d(layer, x, y, z) { layer.threeDLayer = true; setv(p(t(layer), "ADBE Position"), [x, y, z]); }
function root(layer) { return p(layer, "ADBE Root Vectors Group"); }
function glow(layer, radius, intensity) {
try {
var fx = p(layer, "ADBE Effect Parade").addProperty("ADBE Glow");
setv(p(fx, "ADBE Glow-0002"), radius);
setv(p(fx, "ADBE Glow-0003"), intensity);
} catch (error) {}
}
function addPath(layer, name, points, color, width, opacity) {
try {
var group = root(layer).addProperty("ADBE Vector Group");
group.name = name;
var contents = p(group, "ADBE Vectors Group");
var shapeGroup = contents.addProperty("ADBE Vector Shape - Group");
var shape = new Shape();
shape.vertices = points;
shape.inTangents = [];
shape.outTangents = [];
for (var i = 0; i < points.length; i += 1) { shape.inTangents.push([0, 0]); shape.outTangents.push([0, 0]); }
shape.closed = false;
p(shapeGroup, "ADBE Vector Shape").setValue(shape);
var stroke = contents.addProperty("ADBE Vector Graphic - Stroke");
setv(p(stroke, "ADBE Vector Stroke Color"), color);
setv(p(stroke, "ADBE Vector Stroke Width"), width);
setv(p(stroke, "ADBE Vector Stroke Opacity"), opacity);
return contents;
} catch (error) { return null; }
}
function addEllipse(layer, name, position, size, color, opacity, strokeWidth) {
try {
var group = root(layer).addProperty("ADBE Vector Group");
group.name = name;
var contents = p(group, "ADBE Vectors Group");
var ellipse = contents.addProperty("ADBE Vector Shape - Ellipse");
setv(p(ellipse, "ADBE Vector Ellipse Position"), position);
setv(p(ellipse, "ADBE Vector Ellipse Size"), size);
if (strokeWidth && strokeWidth > 0) {
var stroke = contents.addProperty("ADBE Vector Graphic - Stroke");
setv(p(stroke, "ADBE Vector Stroke Color"), color);
setv(p(stroke, "ADBE Vector Stroke Width"), strokeWidth);
setv(p(stroke, "ADBE Vector Stroke Opacity"), opacity);
} else {
var fill = contents.addProperty("ADBE Vector Graphic - Fill");
setv(p(fill, "ADBE Vector Fill Color"), color);
setv(p(fill, "ADBE Vector Fill Opacity"), opacity);
}
return contents;
} catch (error) { return null; }
}
var bg = comp.layers.addSolid([0.002, 0.003, 0.012], "Deep navy stage base", W, H, 1, DUR);
bg.moveToEnd();
function starLayer(name, count, z, seed, color, size, drift) {
var layer = comp.layers.addShape();
layer.name = name;
set3d(layer, 0, 0, z);
for (var i = 0; i < count; i += 1) {
var x = Math.sin((i + 1) * (12.9898 + seed)) * 43758.5453;
var y = Math.sin((i + 1) * (78.233 + seed)) * 24634.6345;
x = (x - Math.floor(x)) * W;
y = (y - Math.floor(y)) * H;
var s = size * (0.45 + ((i * 37) % 100) / 100);
addEllipse(layer, "star " + i, [x, y], [s, s], color, 35 + ((i * 11) % 55), 0);
}
p(t(layer), "ADBE Position").expression = "value + [Math.sin(time*0.21+" + seed + ")*" + drift + ", Math.cos(time*0.13+" + seed + ")*" + (drift * 0.5) + ", 0];";
glow(layer, 24, 0.8);
}
starLayer("Far cyan stardust parallax", 72, 900, 1.3, [0.25, 0.8, 1], 4, 18);
starLayer("Mid magenta stardust parallax", 58, 430, 3.7, [1, 0.25, 0.9], 5, 32);
starLayer("Near white spark dust", 38, -60, 5.2, [0.85, 1, 0.95], 6, 52);
var grid = comp.layers.addShape();
grid.name = "Neon perspective floor grid";
set3d(grid, 0, 0, 260);
for (var gy = 1; gy <= 12; gy += 1) {
var f = gy / 12;
var y = 540 + Math.pow(f, 1.7) * 620;
var half = 90 + f * 1240;
addPath(grid, "horizon row " + gy, [[960 - half, y], [960 + half, y]], [0, 0.8, 1], 2.2, 58);
}
for (var gx = -520; gx <= 2440; gx += 160) {
addPath(grid, "vanish ray " + gx, [[960, 430], [gx, 1240]], [0.7, 0.1, 1], 1.6, 46);
}
p(t(grid), "ADBE Position").expression = "value + [0, (time*24)%55, 0];";
glow(grid, 36, 1.1);
function orbit(name, size, color, z, rx, ry, rz, speed) {
var layer = comp.layers.addShape();
layer.name = name;
set3d(layer, W / 2, H / 2, z);
var contents = addEllipse(layer, "orbit stroke", [0, 0], size, color, 88, 4);
try {
var trim = contents.addProperty("ADBE Vector Filter - Trim");
p(trim, "ADBE Vector Trim End").setValue(72);
p(trim, "ADBE Vector Trim Offset").expression = "time*" + speed;
} catch (trimError) {}
setv(p(t(layer), "ADBE Rotate X"), rx);
setv(p(t(layer), "ADBE Rotate Y"), ry);
setv(p(t(layer), "ADBE Rotate Z"), rz);
p(t(layer), "ADBE Rotate Z").expression = "value + time*" + (speed * 0.12);
layer.motionBlur = true;
glow(layer, 48, 1.4);
}
orbit("Cyan orbit ring A", [650, 176], [0, 0.95, 1], -160, 68, 0, 0, 92);
orbit("Magenta orbit ring B", [520, 315], [1, 0.15, 0.88], -120, 54, 24, 16, -116);
orbit("Lime orbit ring C", [780, 120], [0.4, 1, 0.55], -210, 76, -20, -12, 156);
var hud = comp.layers.addShape();
hud.name = "HUD targeting frame";
set3d(hud, W / 2, H / 2, -130);
addPath(hud, "corner tl a", [[-380, -165], [-298, -165]], [0, 0.9, 1], 3, 78);
addPath(hud, "corner tl b", [[-380, -165], [-380, -83]], [0, 0.9, 1], 3, 78);
addPath(hud, "corner br a", [[380, 165], [298, 165]], [1, 0.15, 0.9], 3, 78);
addPath(hud, "corner br b", [[380, 165], [380, 83]], [1, 0.15, 0.9], 3, 78);
addPath(hud, "cross x", [[-78, 0], [78, 0]], [0.65, 1, 0.86], 1.5, 65);
addPath(hud, "cross y", [[0, -78], [0, 78]], [0.65, 1, 0.86], 1.5, 65);
addEllipse(hud, "inner reticle", [0, 0], [124, 124], [0.45, 1, 0.9], 62, 2);
p(t(hud), "ADBE Rotate Z").expression = "Math.sin(time*1.3)*2.5";
glow(hud, 38, 1.2);
function textDoc(layer, size, color, tracking) {
var docProp = p(p(layer, "ADBE Text Properties"), "ADBE Text Document");
var doc = docProp.value;
doc.fontSize = size;
doc.fillColor = color;
doc.justification = ParagraphJustification.CENTER_JUSTIFY;
try { doc.tracking = tracking; } catch (trackingError) {}
docProp.setValue(doc);
return docProp;
}
function revealText(label, start, y, size, color, tracking) {
var layer = comp.layers.addText(label);
layer.name = "Type reveal " + label;
set3d(layer, W / 2, y, -120);
var docProp = textDoc(layer, size, color, tracking);
docProp.expression = "var full='" + label + "'; var c=Math.floor(linear(time," + start + "," + (start + 0.82) + ",0,full.length)); c=Math.max(0,Math.min(full.length,c)); full.substr(0,c);";
key(p(t(layer), "ADBE Opacity"), start - 0.05, 0);
key(p(t(layer), "ADBE Opacity"), start + 0.16, 100);
p(t(layer), "ADBE Position").expression = "value + [Math.sin(time*17+index)*5, Math.sin(time*23+index)*2, 0];";
layer.motionBlur = true;
glow(layer, 58, 1.5);
}
revealText("SHOTWRIGHT", 0.35, 240, 118, [0.55, 0.95, 1], 150);
revealText("CODEX", 1.12, 350, 104, [1, 0.28, 0.95], 205);
revealText("AE SKILL", 1.82, 456, 76, [0.42, 1, 0.72], 130);
function countText(label, t0, t1, size) {
var layer = comp.layers.addText(label);
layer.name = "Countdown " + label;
set3d(layer, W / 2, 620, -145);
textDoc(layer, size, label === "LAUNCH" ? [0.95, 1, 0.72] : [0.72, 0.98, 1], label === "LAUNCH" ? 70 : 20);
key(p(t(layer), "ADBE Opacity"), t0 - 0.04, 0);
key(p(t(layer), "ADBE Opacity"), t0 + 0.08, 100);
key(p(t(layer), "ADBE Opacity"), t1 - 0.12, 100);
key(p(t(layer), "ADBE Opacity"), t1, 0);
p(t(layer), "ADBE Position").expression = "value + [Math.sin(time*19+index)*4, Math.cos(time*29+index)*2, 0];";
glow(layer, 64, 1.7);
}
countText("03", 0.52, 2.0, 218);
countText("02", 2.0, 3.5, 218);
countText("01", 3.5, 5.0, 218);
countText("LAUNCH", 5.0, 7.0, 132);
function burst(time, index, color) {
var wave = comp.layers.addShape();
wave.name = "Radial shockwave " + index;
set3d(wave, W / 2, H / 2, -105);
addEllipse(wave, "impact wave", [0, 0], [420, 420], color, 95, 4);
key(p(t(wave), "ADBE Scale"), time, [18, 18, 18]);
key(p(t(wave), "ADBE Scale"), time + 0.5, [190, 190, 190]);
key(p(t(wave), "ADBE Opacity"), time, 92);
key(p(t(wave), "ADBE Opacity"), time + 0.5, 0);
glow(wave, 70, 1.6);
var scan = comp.layers.addShape();
scan.name = "Scanline burst " + index;
for (var sy = 0; sy < H; sy += 28) {
addPath(scan, "scan " + sy, [[0, sy], [W, sy]], color, 1.2, 32);
}
key(p(t(scan), "ADBE Opacity"), time - 0.03, 0);
key(p(t(scan), "ADBE Opacity"), time + 0.03, 70);
key(p(t(scan), "ADBE Opacity"), time + 0.34, 0);
glow(scan, 32, 1.1);
}
burst(0.52, 1, [0, 0.9, 1]);
burst(2.0, 2, [1, 0.12, 0.9]);
burst(3.5, 3, [0.45, 1, 0.55]);
burst(5.0, 4, [1, 0.9, 0.25]);
var cam = comp.layers.addCamera("Drift push camera", [W / 2, H / 2]);
key(p(t(cam), "ADBE Position"), 0, [940, 548, -1740]);
key(p(t(cam), "ADBE Position"), DUR, [1040, 526, -1240]);
key(p(t(cam), "ADBE Point of Interest"), 0, [960, 545, 0]);
key(p(t(cam), "ADBE Point of Interest"), DUR, [960, 560, 80]);
p(t(cam), "ADBE Position").expression = "value + [Math.sin(time*0.73)*18, Math.sin(time*0.41)*7, 0];";
try { p(p(cam, "ADBE Camera Options Group"), "ADBE Camera Zoom").setValue(1450); } catch (zoomError) {}
comp.openInViewer();
var savePath = $.getenv("SHOTWRIGHT_PROJECT_FILE");
if (savePath) { proj.save(new File(savePath)); }
app.endUndoGroup();
}());
""".strip()
async def _list_session_image_attachments(session_id: str, *, limit: int = 8) -> list[dict]:
attachments: list[dict] = []
seen_paths: set[str] = set()
cursor = get_message_collection().find(
{"session_id": session_id},
{"metadata.attachments": 1, "created_at": 1},
).sort("created_at", -1)
async for message_doc in cursor:
metadata = message_doc.get("metadata") or {}
for attachment in metadata.get("attachments") or []:
if not isinstance(attachment, dict) or attachment.get("type") != "image":
continue
file_path = str(attachment.get("file_path") or "").strip()
if not file_path:
continue
resolved_path = Path(file_path)
if not resolved_path.exists():
continue
dedupe_key = str(resolved_path).lower()
if dedupe_key in seen_paths:
continue
seen_paths.add(dedupe_key)
attachments.append(
{
"file_path": str(resolved_path),
"display_name": attachment.get("display_name") or resolved_path.name,
"mime_type": attachment.get("mime_type"),
"shared_relative_path": attachment.get("shared_relative_path"),
"workspace_relative_path": attachment.get("workspace_relative_path"),
"width": attachment.get("width"),
"height": attachment.get("height"),
"size_bytes": attachment.get("size_bytes"),
"created_at": message_doc.get("created_at"),
}
)
if len(attachments) >= limit:
return attachments
return attachments
async def list_session_image_attachments(session_id: str, *, limit: int = 8) -> list[dict]:
return await _list_session_image_attachments(session_id, limit=limit)
def _copy_asset_into_project(
project: dict,
source_path: Path,
*,
display_name: str | None = None,
asset_name: str | None = None,
target_directory: Path = _REFERENCE_ASSET_DIRECTORY,
) -> dict:
if not source_path.exists():
raise FileNotFoundError(f"Reference asset not found at {source_path}")
project_root = Path(project["workspace_dir"])
destination_dir = project_root / target_directory
destination_dir.mkdir(parents=True, exist_ok=True)
suffix = source_path.suffix.lower() or ".bin"
destination_name = _sanitize_asset_file_name(asset_name or display_name, "reference-image", suffix)
destination_path = destination_dir / destination_name
if str(source_path.resolve()).lower() != str(destination_path.resolve()).lower():
shutil.copy2(source_path, destination_path)
return {
"source_path": str(source_path),
"project_asset_path": str(destination_path),
"project_relative_path": destination_path.relative_to(project_root).as_posix(),
"display_name": display_name or source_path.name,
}
async def _stage_session_image_attachments(
session_id: str,
project: dict,
*,
latest_only: bool = True,
asset_name: str | None = None,
) -> list[dict]:
image_attachments = await _list_session_image_attachments(session_id, limit=1 if latest_only else 8)
if not image_attachments:
return []
staged_assets: list[dict] = []
total = len(image_attachments)
for index, attachment in enumerate(image_attachments, start=1):
source_path = Path(str(attachment["file_path"]))
desired_name = asset_name
if not latest_only and total > 1 and desired_name:
suffix = source_path.suffix.lower() or ".bin"
desired_name = f"{Path(desired_name).stem}-{index:02d}{suffix}"
staged_assets.append(
_copy_asset_into_project(
project,
source_path,
display_name=str(attachment.get("display_name") or source_path.name),
asset_name=desired_name,
)
)
return staged_assets
def _build_empty_project_jsx() -> str:
return "\n".join(
[
"app.beginSuppressDialogs();",
"if (typeof CloseOptions !== \"undefined\" && app.project && typeof app.project.close === \"function\") {",
" app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES);",
"}",
]
)
def _build_reference_composition_jsx(
*,
reference_asset_path: str,
composition_name: str,
width: int,
height: int,
duration_seconds: float,
frame_rate: float,
fit_mode: str,
reset_existing: bool,
) -> str:
normalized_fit_mode = "contain" if fit_mode == "contain" else "cover"
return "\n".join(
[
"app.beginSuppressDialogs();",
"function normalizePath(value) {",
" if (!value) { return \"\"; }",
" return value.toString().replace(/\\\\/g, \"/\").toLowerCase();",
"}",
"function findCompByName(name) {",