kasaframe 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +148 -0
  3. package/README.md +92 -2
  4. package/app/package.json +12 -0
  5. package/app/server/engine.ts +533 -0
  6. package/app/server/main.ts +209 -0
  7. package/app/web/env.d.ts +2 -0
  8. package/app/web/icons.ts +31 -0
  9. package/app/web/index.html +21 -0
  10. package/app/web/main.ts +1195 -0
  11. package/app/web/style.css +463 -0
  12. package/bin/hooks.mjs +64 -0
  13. package/bin/kf.mjs +32 -0
  14. package/docs/AGENTS.md +286 -0
  15. package/music/README.md +37 -0
  16. package/package.json +44 -4
  17. package/packages/adapters/package.json +36 -0
  18. package/packages/adapters/src/css.ts +11 -0
  19. package/packages/adapters/src/gsap.ts +26 -0
  20. package/packages/adapters/src/index.ts +9 -0
  21. package/packages/adapters/src/lottie.ts +22 -0
  22. package/packages/adapters/src/media.ts +59 -0
  23. package/packages/adapters/src/page.ts +229 -0
  24. package/packages/adapters/src/project.ts +214 -0
  25. package/packages/adapters/src/react.ts +36 -0
  26. package/packages/adapters/src/svelte.ts +22 -0
  27. package/packages/adapters/src/three.ts +18 -0
  28. package/packages/adapters/src/vue.ts +27 -0
  29. package/packages/check/package.json +19 -0
  30. package/packages/check/src/check.ts +280 -0
  31. package/packages/check/src/cli.ts +70 -0
  32. package/packages/check/src/image.ts +146 -0
  33. package/packages/check/src/index.ts +9 -0
  34. package/packages/check/src/ocr.swift +37 -0
  35. package/packages/check/src/probe.ts +328 -0
  36. package/packages/check/src/report.ts +44 -0
  37. package/packages/check/src/rules/assets.ts +45 -0
  38. package/packages/check/src/rules/beats.ts +212 -0
  39. package/packages/check/src/rules/camera.ts +217 -0
  40. package/packages/check/src/rules/captions.ts +49 -0
  41. package/packages/check/src/rules/flash.ts +235 -0
  42. package/packages/check/src/rules/frames.ts +136 -0
  43. package/packages/check/src/rules/layout.ts +281 -0
  44. package/packages/check/src/rules/page.ts +87 -0
  45. package/packages/check/src/rules/runs.ts +20 -0
  46. package/packages/check/src/rules/text.ts +326 -0
  47. package/packages/check/src/scan.ts +240 -0
  48. package/packages/check/src/serve.ts +67 -0
  49. package/packages/check/src/types.ts +80 -0
  50. package/packages/check/src/video.ts +137 -0
  51. package/packages/cli/package.json +30 -0
  52. package/packages/cli/src/blur.ts +80 -0
  53. package/packages/cli/src/browser.ts +203 -0
  54. package/packages/cli/src/command.ts +44 -0
  55. package/packages/cli/src/commands/app.ts +25 -0
  56. package/packages/cli/src/commands/beats.ts +36 -0
  57. package/packages/cli/src/commands/bench.ts +123 -0
  58. package/packages/cli/src/commands/blender.ts +293 -0
  59. package/packages/cli/src/commands/check.ts +25 -0
  60. package/packages/cli/src/commands/direct.ts +210 -0
  61. package/packages/cli/src/commands/doctor.ts +30 -0
  62. package/packages/cli/src/commands/gen.ts +173 -0
  63. package/packages/cli/src/commands/look.ts +46 -0
  64. package/packages/cli/src/commands/lyrics.ts +157 -0
  65. package/packages/cli/src/commands/make.ts +1121 -0
  66. package/packages/cli/src/commands/music.ts +78 -0
  67. package/packages/cli/src/commands/narrate.ts +238 -0
  68. package/packages/cli/src/commands/new.ts +185 -0
  69. package/packages/cli/src/commands/preview.ts +43 -0
  70. package/packages/cli/src/commands/render.ts +250 -0
  71. package/packages/cli/src/commands/series.ts +110 -0
  72. package/packages/cli/src/commands/setup.ts +102 -0
  73. package/packages/cli/src/commands/sheet.ts +114 -0
  74. package/packages/cli/src/commands/skill.ts +43 -0
  75. package/packages/cli/src/commands/still.ts +40 -0
  76. package/packages/cli/src/commands/theme.ts +172 -0
  77. package/packages/cli/src/commands/transitions.ts +40 -0
  78. package/packages/cli/src/deps.ts +122 -0
  79. package/packages/cli/src/ffmpeg.ts +81 -0
  80. package/packages/cli/src/index.ts +8 -0
  81. package/packages/cli/src/kf.ts +64 -0
  82. package/packages/cli/src/lock.ts +72 -0
  83. package/packages/cli/src/mix.ts +131 -0
  84. package/packages/cli/src/out.ts +13 -0
  85. package/packages/cli/src/pool.ts +34 -0
  86. package/packages/cli/src/segments.ts +402 -0
  87. package/packages/cli/src/serve.ts +124 -0
  88. package/packages/clock/package.json +14 -0
  89. package/packages/clock/src/index.ts +25 -0
  90. package/packages/clock/src/install.ts +351 -0
  91. package/packages/clock/src/types.ts +45 -0
  92. package/packages/core/package.json +9 -0
  93. package/packages/core/src/beats.ts +283 -0
  94. package/packages/core/src/ease.ts +87 -0
  95. package/packages/core/src/frame.ts +99 -0
  96. package/packages/core/src/index.ts +27 -0
  97. package/packages/core/src/project.ts +157 -0
  98. package/packages/core/src/rand.ts +56 -0
  99. package/packages/core/src/spring.ts +52 -0
  100. package/packages/core/src/style.ts +100 -0
  101. package/packages/core/src/time.ts +88 -0
  102. package/packages/director/package.json +23 -0
  103. package/packages/director/src/assemble.ts +361 -0
  104. package/packages/director/src/brief.ts +122 -0
  105. package/packages/director/src/catalog.ts +49 -0
  106. package/packages/director/src/content.ts +343 -0
  107. package/packages/director/src/fallback.ts +58 -0
  108. package/packages/director/src/index.ts +13 -0
  109. package/packages/director/src/pattern.ts +90 -0
  110. package/packages/director/src/patterns/fill/cells.ts +115 -0
  111. package/packages/director/src/patterns/formula/stack.ts +93 -0
  112. package/packages/director/src/patterns/util.ts +58 -0
  113. package/packages/director/src/scene.ts +62 -0
  114. package/packages/director/src/select.ts +163 -0
  115. package/packages/director/src/transitions.ts +115 -0
  116. package/packages/gen/PROVIDERS.md +90 -0
  117. package/packages/gen/package.json +9 -0
  118. package/packages/gen/src/ask.ts +132 -0
  119. package/packages/gen/src/audio.ts +91 -0
  120. package/packages/gen/src/blender.ts +54 -0
  121. package/packages/gen/src/capabilities.ts +151 -0
  122. package/packages/gen/src/generate.ts +206 -0
  123. package/packages/gen/src/image/codex.ts +117 -0
  124. package/packages/gen/src/image/og.ts +133 -0
  125. package/packages/gen/src/index.ts +26 -0
  126. package/packages/gen/src/keys.ts +86 -0
  127. package/packages/gen/src/media.ts +150 -0
  128. package/packages/gen/src/music/elevenlabs.ts +41 -0
  129. package/packages/gen/src/music/index.ts +120 -0
  130. package/packages/gen/src/music/library.ts +73 -0
  131. package/packages/gen/src/music/lyria.ts +52 -0
  132. package/packages/gen/src/music/types.ts +28 -0
  133. package/packages/gen/src/plan.ts +106 -0
  134. package/packages/gen/src/registry.ts +54 -0
  135. package/packages/gen/src/seam.ts +103 -0
  136. package/packages/gen/src/tts/dashscope.ts +64 -0
  137. package/packages/gen/src/tts/elevenlabs.ts +84 -0
  138. package/packages/gen/src/tts/gemini.ts +73 -0
  139. package/packages/gen/src/tts/index.ts +241 -0
  140. package/packages/gen/src/tts/local.ts +42 -0
  141. package/packages/gen/src/tts/types.ts +44 -0
  142. package/packages/gen/src/types.ts +90 -0
  143. package/packages/gen/src/video/fal.ts +140 -0
  144. package/packages/gen/src/video/h3.ts +112 -0
  145. package/packages/gen/src/video/http.ts +44 -0
  146. package/packages/gen/src/video/ltx.ts +60 -0
  147. package/packages/gen/src/video/minimax.ts +55 -0
  148. package/packages/gen/src/video/veo.ts +71 -0
  149. package/packages/jizura/package.json +16 -0
  150. package/packages/jizura/src/deny.ts +73 -0
  151. package/packages/jizura/src/index.ts +7 -0
  152. package/packages/jizura/src/install.ts +269 -0
  153. package/packages/jizura/src/layer.ts +325 -0
  154. package/packages/jizura/src/lyrics.ts +81 -0
  155. package/packages/jizura/src/pin.ts +8 -0
  156. package/packages/jizura/src/vendor.ts +140 -0
  157. package/packages/jizura/src/vite.ts +63 -0
  158. package/packages/jizura/vendor/JIZURA_LICENSE.txt +21 -0
  159. package/packages/jizura/vendor/NOTICE +43 -0
  160. package/packages/jizura/vendor/engine.json +47 -0
  161. package/packages/jizura/vendor/fonts/BlackHanSans-Regular.woff2 +0 -0
  162. package/packages/jizura/vendor/fonts/DotGothic16-Regular.woff2 +0 -0
  163. package/packages/jizura/vendor/fonts/GowunBatang-Bold.woff2 +0 -0
  164. package/packages/jizura/vendor/fonts/IBMPlexMono-Medium.ttf +0 -0
  165. package/packages/jizura/vendor/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  166. package/packages/jizura/vendor/fonts/NotoSansKR-VF.woff2 +0 -0
  167. package/packages/jizura/vendor/fonts/NotoSerifKR-VF.woff2 +0 -0
  168. package/packages/jizura/vendor/fonts/OFL-blackhansans.txt +93 -0
  169. package/packages/jizura/vendor/fonts/OFL-dotgothic16.txt +93 -0
  170. package/packages/jizura/vendor/fonts/OFL-gowunbatang.txt +94 -0
  171. package/packages/jizura/vendor/fonts/OFL-ibmplexmono.txt +93 -0
  172. package/packages/jizura/vendor/fonts/OFL-notosanskr.txt +93 -0
  173. package/packages/jizura/vendor/fonts/OFL-notoserifkr.txt +94 -0
  174. package/packages/jizura/vendor/fonts/fonts.json +52 -0
  175. package/packages/jizura/vendor/jizura_engine.js +35024 -0
  176. package/packages/motion/README.md +153 -0
  177. package/packages/motion/package.json +30 -0
  178. package/packages/motion/src/camera.ts +97 -0
  179. package/packages/motion/src/captions.ts +487 -0
  180. package/packages/motion/src/enter.ts +128 -0
  181. package/packages/motion/src/hangul.ts +129 -0
  182. package/packages/motion/src/impact.ts +100 -0
  183. package/packages/motion/src/index.ts +17 -0
  184. package/packages/motion/src/moves/brushWipe.ts +103 -0
  185. package/packages/motion/src/moves/cloneArray.ts +111 -0
  186. package/packages/motion/src/moves/curtains.ts +81 -0
  187. package/packages/motion/src/moves/dress.ts +191 -0
  188. package/packages/motion/src/moves/echoStack.ts +70 -0
  189. package/packages/motion/src/moves/fit.ts +70 -0
  190. package/packages/motion/src/moves/flood.ts +61 -0
  191. package/packages/motion/src/moves/ghostStack.ts +88 -0
  192. package/packages/motion/src/moves/gridFloor.ts +100 -0
  193. package/packages/motion/src/moves/imageSwarm.ts +113 -0
  194. package/packages/motion/src/moves/index.ts +38 -0
  195. package/packages/motion/src/moves/irisBlades.ts +113 -0
  196. package/packages/motion/src/moves/karaokeLine.ts +108 -0
  197. package/packages/motion/src/moves/ledBoard.ts +94 -0
  198. package/packages/motion/src/moves/liquidTab.ts +72 -0
  199. package/packages/motion/src/moves/markerWrite.ts +63 -0
  200. package/packages/motion/src/moves/menu.ts +138 -0
  201. package/packages/motion/src/moves/morphBox.ts +96 -0
  202. package/packages/motion/src/moves/neonSign.ts +78 -0
  203. package/packages/motion/src/moves/panelPop.ts +78 -0
  204. package/packages/motion/src/moves/paperTear.ts +75 -0
  205. package/packages/motion/src/moves/path.ts +64 -0
  206. package/packages/motion/src/moves/pathText.ts +107 -0
  207. package/packages/motion/src/moves/pointSphere.ts +109 -0
  208. package/packages/motion/src/moves/ransomLetters.ts +73 -0
  209. package/packages/motion/src/moves/shapeMorph.ts +143 -0
  210. package/packages/motion/src/moves/slamWords.ts +96 -0
  211. package/packages/motion/src/moves/sparkTrail.ts +130 -0
  212. package/packages/motion/src/moves/speedLines.ts +91 -0
  213. package/packages/motion/src/moves/splitFlap.ts +149 -0
  214. package/packages/motion/src/moves/stepWords.ts +128 -0
  215. package/packages/motion/src/moves/strikeOut.ts +98 -0
  216. package/packages/motion/src/moves/sunburst.ts +58 -0
  217. package/packages/motion/src/moves/tickerRows.ts +91 -0
  218. package/packages/motion/src/moves/tokenPicker.ts +115 -0
  219. package/packages/motion/src/moves/truchet.ts +85 -0
  220. package/packages/motion/src/moves/wordWall.ts +78 -0
  221. package/packages/motion/src/moves/worldRoll.ts +32 -0
  222. package/packages/motion/src/particles.ts +102 -0
  223. package/packages/motion/src/react/index.tsx +21 -0
  224. package/packages/motion/src/react/parts.tsx +431 -0
  225. package/packages/motion/src/react/time.tsx +97 -0
  226. package/packages/motion/src/text.ts +103 -0
  227. package/packages/motion/src/transition.ts +82 -0
  228. package/packages/motion/src/transition3d/cards.ts +65 -0
  229. package/packages/motion/src/transition3d/chain.ts +84 -0
  230. package/packages/motion/src/transition3d/dive.ts +181 -0
  231. package/packages/motion/src/transition3d/fold.ts +110 -0
  232. package/packages/motion/src/transition3d/gl.ts +219 -0
  233. package/packages/motion/src/transition3d/index.ts +235 -0
  234. package/packages/motion/src/transition3d/live.ts +70 -0
  235. package/packages/motion/src/transition3d/portal.ts +115 -0
  236. package/packages/motion/src/transition3d/react.tsx +29 -0
  237. package/packages/motion/src/transition3d/rig.ts +600 -0
  238. package/packages/motion/src/transition3d/shatter.ts +104 -0
  239. package/packages/motion/src/transition3d/space.ts +173 -0
  240. package/packages/motion/src/transition3d/whip.ts +78 -0
  241. package/packages/motion/src/transition3d/world.ts +737 -0
  242. package/packages/motion/src/transition3d/zoomOut.ts +114 -0
  243. package/packages/motion/src/transitions2d/catalog.ts +127 -0
  244. package/packages/motion/src/transitions2d/css.d.ts +2 -0
  245. package/packages/motion/src/transitions2d/cult-ui/LICENSE.md +9 -0
  246. package/packages/motion/src/transitions2d/cult-ui/RollingNumber.tsx +43 -0
  247. package/packages/motion/src/transitions2d/gl-transitions/LICENSE +25 -0
  248. package/packages/motion/src/transitions2d/gl-transitions/shaders.ts +1931 -0
  249. package/packages/motion/src/transitions2d/index.ts +2 -0
  250. package/packages/motion/src/transitions2d/kokonutui/LICENSE +21 -0
  251. package/packages/motion/src/transitions2d/kokonutui/MatrixText.css +16 -0
  252. package/packages/motion/src/transitions2d/kokonutui/MatrixText.tsx +94 -0
  253. package/packages/motion/src/transitions2d/magicui/HyperText.css +15 -0
  254. package/packages/motion/src/transitions2d/magicui/HyperText.tsx +115 -0
  255. package/packages/motion/src/transitions2d/magicui/LICENSE.md +21 -0
  256. package/packages/motion/src/transitions2d/magicui/MorphingText.css +25 -0
  257. package/packages/motion/src/transitions2d/magicui/MorphingText.tsx +130 -0
  258. package/packages/motion/src/transitions2d/magicui/WordRotate.tsx +42 -0
  259. package/packages/motion/src/transitions2d/react.ts +13 -0
  260. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.css +39 -0
  261. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.tsx +32 -0
  262. package/packages/motion/src/transitions2d/smoothui/LICENSE +21 -0
  263. package/packages/motion/src/transitions2d/smoothui/SharedAxisY.tsx +50 -0
  264. package/packages/motion/src/transitions2d/smoothui/TextMorph.tsx +90 -0
  265. package/packages/motion/src/transitions2d/smoothui/shaders.ts +223 -0
  266. package/packages/motion/src/transitions2d/unlumen/LICENSE +21 -0
  267. package/packages/motion/src/transitions2d/unlumen/ScrambleText.tsx +114 -0
  268. package/packages/motion/src/transitions2d/vengeance-ui/LICENSE +21 -0
  269. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.css +69 -0
  270. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.tsx +45 -0
  271. package/packages/motion/src/type.ts +131 -0
  272. package/packages/motion/src/ui.ts +172 -0
  273. package/packages/patterns/package.json +15 -0
  274. package/packages/patterns/src/bars/rank.ts +119 -0
  275. package/packages/patterns/src/before-after/shrink.ts +127 -0
  276. package/packages/patterns/src/before-after/strike.ts +125 -0
  277. package/packages/patterns/src/code/terminal.ts +133 -0
  278. package/packages/patterns/src/compare/bars.ts +142 -0
  279. package/packages/patterns/src/compare/duel.ts +103 -0
  280. package/packages/patterns/src/end/lockup.ts +85 -0
  281. package/packages/patterns/src/end/slam.ts +91 -0
  282. package/packages/patterns/src/flow/graph.ts +250 -0
  283. package/packages/patterns/src/hook-number/counter.ts +101 -0
  284. package/packages/patterns/src/hook-number/roll.ts +179 -0
  285. package/packages/patterns/src/hook-number/slam.ts +91 -0
  286. package/packages/patterns/src/index.ts +38 -0
  287. package/packages/patterns/src/kit.ts +449 -0
  288. package/packages/patterns/src/limit/gauge.ts +117 -0
  289. package/packages/patterns/src/list/cards.ts +131 -0
  290. package/packages/patterns/src/list/cycle.ts +22 -0
  291. package/packages/patterns/src/media/panels.ts +100 -0
  292. package/packages/patterns/src/objects.ts +234 -0
  293. package/packages/patterns/src/quote/karaoke.ts +126 -0
  294. package/packages/patterns/src/quote/slam.ts +22 -0
  295. package/packages/patterns/src/screen/focus.ts +85 -0
  296. package/packages/patterns/src/steps/path.ts +137 -0
  297. package/packages/patterns/src/steps/stack.ts +111 -0
  298. package/packages/patterns/src/term-reveal/chips.ts +92 -0
  299. package/packages/patterns/src/term-reveal/expand.ts +127 -0
  300. package/packages/patterns/src/timeline/axis.ts +144 -0
  301. package/packages/patterns/src/title/mask.ts +85 -0
  302. package/packages/patterns/src/title/slam.ts +23 -0
  303. package/packages/patterns/src/toggle-sim/switch.ts +92 -0
  304. package/packages/patterns/src/trend/columns.ts +108 -0
  305. package/packages/patterns/src/trend/draw.ts +140 -0
  306. package/packages/patterns/src/types.ts +67 -0
  307. package/packages/patterns/src/words/moves.ts +42 -0
  308. package/packages/patterns/src/words/slam.ts +4 -0
  309. package/packages/plan/package.json +15 -0
  310. package/packages/plan/src/asks.ts +256 -0
  311. package/packages/plan/src/brief.ts +383 -0
  312. package/packages/plan/src/captions.ts +78 -0
  313. package/packages/plan/src/detect.ts +93 -0
  314. package/packages/plan/src/index.ts +27 -0
  315. package/packages/plan/src/layout.ts +176 -0
  316. package/packages/plan/src/llm.ts +172 -0
  317. package/packages/plan/src/look.ts +222 -0
  318. package/packages/plan/src/plan.ts +179 -0
  319. package/packages/plan/src/request.ts +55 -0
  320. package/packages/plan/src/series.ts +76 -0
  321. package/packages/plan/src/studio.ts +53 -0
  322. package/packages/plan/src/templates.ts +42 -0
  323. package/packages/plan/src/themes.ts +48 -0
  324. package/packages/plan/src/types.ts +157 -0
  325. package/packages/studio/package.json +12 -0
  326. package/packages/studio/src/index.ts +1 -0
  327. package/packages/studio/src/plugin.ts +236 -0
  328. package/packages/studio/src/ui/main.ts +503 -0
  329. package/packages/studio/src/ui/studio.css +165 -0
  330. package/packages/studio/src/ui/timeline.ts +317 -0
  331. package/packages/themes/kit/THEME-MAKE.md +68 -0
  332. package/packages/themes/kit/THEME.md +30 -0
  333. package/packages/themes/kit/briefs/og-intro-15s/brief.json +16 -0
  334. package/packages/themes/kit/briefs/og-intro-15s/facts.ts +29 -0
  335. package/packages/themes/kit/briefs/og-intro-15s/logo.svg +12 -0
  336. package/packages/themes/kit/effects.ts +5 -0
  337. package/packages/themes/kit/sample/index.html +11 -0
  338. package/packages/themes/kit/sample/main.ts +9 -0
  339. package/packages/themes/kit/sample/scenes/scene.ts +15 -0
  340. package/packages/themes/package.json +19 -0
  341. package/packages/themes/src/factory.ts +296 -0
  342. package/packages/themes/src/fx.ts +14 -0
  343. package/packages/themes/src/index.ts +114 -0
  344. package/packages/themes/src/slotkit.ts +79 -0
  345. package/packages/themes/src/slots.ts +46 -0
  346. package/packages/themes/src/stage3d.ts +197 -0
  347. package/packages/themes/src/types.ts +58 -0
  348. package/presets/kawaii-pastel.json +94 -0
  349. package/presets/neutral-dark.json +82 -0
  350. package/presets/og.json +98 -0
  351. package/series/og-shorts.json +14 -0
  352. package/skills/kasaframe/SKILL.md +33 -0
  353. package/templates/_shared/project/index.html +11 -0
  354. package/templates/_shared/project/lib/react.ts +22 -0
  355. package/templates/_shared/project/lib/stage.ts +292 -0
  356. package/templates/_shared/project/main.ts +9 -0
  357. package/templates/_shared/scenes/default.ts +21 -0
  358. package/templates/_shared/scenes/drop.ts +33 -0
  359. package/templates/_shared/scenes/end.ts +26 -0
  360. package/templates/_shared/scenes/hook.ts +18 -0
  361. package/templates/_shared/scenes/seam.ts +41 -0
  362. package/templates/_shared/scenes/step.ts +49 -0
  363. package/templates/ad/preview.png +0 -0
  364. package/templates/ad/template.json +151 -0
  365. package/templates/demo/preview.png +0 -0
  366. package/templates/demo/template.json +141 -0
  367. package/templates/explainer/preview.png +0 -0
  368. package/templates/explainer/template.json +193 -0
  369. package/templates/launch/preview.png +0 -0
  370. package/templates/launch/template.json +163 -0
  371. package/templates/mv/preview.png +0 -0
  372. package/templates/mv/scenes/default.ts +98 -0
  373. package/templates/mv/template.json +178 -0
  374. package/templates/promo/preview.png +0 -0
  375. package/templates/promo/template.json +185 -0
  376. package/templates/shorts/preview.png +0 -0
  377. package/templates/shorts/scenes/hook.ts +37 -0
  378. package/templates/shorts/template.json +196 -0
  379. package/templates/square/preview.png +0 -0
  380. package/templates/square/template.json +133 -0
  381. package/themes/debug-hud/THEME.md +39 -0
  382. package/themes/debug-hud/effects.ts +389 -0
  383. package/themes/debug-hud/sample/assets/og/logo.svg +12 -0
  384. package/themes/debug-hud/sample/beats.json +1 -0
  385. package/themes/debug-hud/sample/index.html +11 -0
  386. package/themes/debug-hud/sample/kf.json +59 -0
  387. package/themes/debug-hud/sample/lib/hudkit.ts +49 -0
  388. package/themes/debug-hud/sample/lib/og.ts +29 -0
  389. package/themes/debug-hud/sample/main.ts +9 -0
  390. package/themes/debug-hud/sample/scenes/end.ts +62 -0
  391. package/themes/debug-hud/sample/scenes/gather.ts +67 -0
  392. package/themes/debug-hud/sample/scenes/models.ts +70 -0
  393. package/themes/debug-hud/sample/scenes/price.ts +79 -0
  394. package/themes/debug-hud/sample/style.json +91 -0
  395. package/themes/debug-hud/slots.ts +99 -0
  396. package/themes/debug-hud/still.png +0 -0
  397. package/themes/debug-hud/style.json +91 -0
  398. package/themes/debug-hud/theme.json +68 -0
  399. package/themes/og-measure/THEME.md +47 -0
  400. package/themes/og-measure/effects.ts +432 -0
  401. package/themes/og-measure/sample/assets/brand/og-logo-full.svg +12 -0
  402. package/themes/og-measure/sample/assets/brand/og-logo.svg +12 -0
  403. package/themes/og-measure/sample/assets/data/measure.json +353 -0
  404. package/themes/og-measure/sample/beats.json +1 -0
  405. package/themes/og-measure/sample/index.html +11 -0
  406. package/themes/og-measure/sample/kf.json +66 -0
  407. package/themes/og-measure/sample/lib/data.ts +62 -0
  408. package/themes/og-measure/sample/main.ts +9 -0
  409. package/themes/og-measure/sample/measure.ts +78 -0
  410. package/themes/og-measure/sample/scenes/end.ts +47 -0
  411. package/themes/og-measure/sample/scenes/gather.ts +51 -0
  412. package/themes/og-measure/sample/scenes/models.ts +34 -0
  413. package/themes/og-measure/sample/scenes/one.ts +39 -0
  414. package/themes/og-measure/sample/scenes/price.ts +56 -0
  415. package/themes/og-measure/sample/style.json +97 -0
  416. package/themes/og-measure/slots.ts +88 -0
  417. package/themes/og-measure/still.png +0 -0
  418. package/themes/og-measure/style.json +97 -0
  419. package/themes/og-measure/theme.json +79 -0
  420. package/themes/riso-zine/THEME.md +43 -0
  421. package/themes/riso-zine/effects.ts +321 -0
  422. package/themes/riso-zine/sample/assets/og/logo.svg +12 -0
  423. package/themes/riso-zine/sample/beats.json +1 -0
  424. package/themes/riso-zine/sample/index.html +11 -0
  425. package/themes/riso-zine/sample/kf.json +59 -0
  426. package/themes/riso-zine/sample/lib/og.ts +29 -0
  427. package/themes/riso-zine/sample/lib/shot.ts +86 -0
  428. package/themes/riso-zine/sample/lib/zine.ts +42 -0
  429. package/themes/riso-zine/sample/main.ts +9 -0
  430. package/themes/riso-zine/sample/scenes/end.ts +61 -0
  431. package/themes/riso-zine/sample/scenes/gather.ts +62 -0
  432. package/themes/riso-zine/sample/scenes/models.ts +52 -0
  433. package/themes/riso-zine/sample/scenes/price.ts +82 -0
  434. package/themes/riso-zine/sample/style.json +99 -0
  435. package/themes/riso-zine/slots.ts +81 -0
  436. package/themes/riso-zine/still.png +0 -0
  437. package/themes/riso-zine/style.json +99 -0
  438. package/themes/riso-zine/theme.json +75 -0
  439. package/tools/beats/beats.py +372 -0
  440. package/tools/beats/requirements.txt +3 -0
  441. package/tools/lyrics/align.py +164 -0
  442. package/tools/lyrics/requirements.txt +9 -0
@@ -0,0 +1,533 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { basename, extname, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { checkContent } from "@kasaframe/director";
7
+ import { capabilities } from "@kasaframe/gen";
8
+ import { listTemplates, makePlan, type Plan, type Purpose, planQuestions, suggestThemes } from "@kasaframe/plan";
9
+ import { loadTheme, themeCards, type ThemeStatus } from "@kasaframe/themes";
10
+ import { captionMode } from "@kasaframe/motion/captions";
11
+
12
+ // 화면과 상관없는 엔진 — HTTP 서버든 Electron 이든 컨테이너든 이걸 감싸기만 한다. 일은 전부 kf 명령을 자식 프로세스로 돌린다.
13
+
14
+ const repo = fileURLToPath(new URL("../../", import.meta.url));
15
+ const kfBin = join(repo, "packages/cli/src/kf.ts");
16
+ export const dataDir = resolve(process.env.KF_APP_DIR ?? join(repo, "out", "app"));
17
+ export const templatePreview = (id: string) => join(repo, "templates", id, "preview.png");
18
+ // 5159 는 작업실 화면의 HMR 자리
19
+ const PREVIEW_PORTS = [5151, 5152, 5153, 5154, 5155, 5156, 5157, 5158];
20
+
21
+ export type Phase = "plan" | "scaffold" | "gen" | "scenes" | "render" | "check" | "done" | "waiting" | "failed";
22
+
23
+ // 장면마다 따로 흐르는 상태 — kf make·direct·render 가 찍는 「장면 <id>: <상태>」 줄에서 읽는다
24
+ export type SceneState = "writing" | "written" | "assets" | "render" | "rendered" | "reused" | "check" | "done" | "failed";
25
+ const SCENE_WORDS: Record<string, SceneState> = { "쓰는 중": "writing", 씀: "written", 재료: "assets", 렌더: "render", 구움: "rendered", 그대로: "reused", 검사: "check", 끝: "done", 실패: "failed" };
26
+ const SCENE_LINE = /^장면 (\S+): (쓰는 중|씀|재료|렌더|구움|그대로|검사|끝|실패)(?:\s*(?:—\s*)?(.*))?$/;
27
+
28
+ export interface JobInput {
29
+ request: string;
30
+ purpose?: Purpose | "auto";
31
+ music?: string;
32
+ assets?: string[]; // /api/upload 로 올린 파일 경로들 — 일 폴더 in/ 에 모아 kf make --assets 로 넘긴다
33
+ theme?: string; // 테마 id 나 "auto"
34
+ model?: string;
35
+ approve?: boolean;
36
+ title?: string;
37
+ captions?: "on" | "off"; // 화면 자막 — 안 주면 틀 기본
38
+ answers?: Record<string, string>; // 계획의 asks 에 고른 답 { 질문 id: 값 } — kf make --<id> <값> 로 넘겨 묻지 않고 간다
39
+ }
40
+
41
+ export interface Job {
42
+ id: string;
43
+ external?: boolean; // 말로 시작한 kf make 가 스스로 등록한 일 — 서버가 돌리지 않고 진행만 받는다
44
+ input: JobInput;
45
+ dir: string;
46
+ phase: Phase;
47
+ progress: number; // 렌더 진행 0..1
48
+ running: boolean;
49
+ createdAt: number;
50
+ previewUrl?: string;
51
+ log: string[];
52
+ error?: string;
53
+ checkPassed?: boolean;
54
+ scenes?: Record<string, { state: SceneState; note?: string; at: number }>;
55
+ // 사람이 고쳐 다시 굽는 장면 — 다 되면 화면이 그 장면 시각부터 튼다
56
+ focus?: string;
57
+ }
58
+
59
+ export interface JobView extends Omit<Job, "log"> {
60
+ plan?: Plan;
61
+ kf?: unknown;
62
+ // alt — 자막을 반대로 다시 구운 판(video-자막.mp4 · video-자막없음.mp4). captions — 들릴 말(captions.json)이 있다
63
+ files: { video?: string; cover?: string; check?: string; alt?: string; captions?: string; videoAt?: number };
64
+ }
65
+
66
+ export interface SceneDetail {
67
+ scene: Record<string, unknown> & { id: string; from: number; dur: number; role?: string; idea?: string };
68
+ direct: boolean;
69
+ model: string | null;
70
+ content: Record<string, unknown> | null;
71
+ pattern: string | null;
72
+ candidates: { id: string; score: number; why: string[] }[];
73
+ pinned: { pattern?: string; seed?: string } | null;
74
+ assets: { path: string; url: string; kind: "image" | "video" }[];
75
+ }
76
+
77
+ const PHASES: [RegExp, Phase][] = [
78
+ [/^용도 /, "scaffold"],
79
+ [/^생성 자산/, "gen"],
80
+ [/^계획 다듬/, "scaffold"],
81
+ [/^장면 \S+: 쓰는 중/, "scenes"],
82
+ [/^장면 \S+: 재료/, "gen"],
83
+ [/^장면 \S+: 렌더/, "render"],
84
+ [/^장면 \S+: 검사/, "check"],
85
+ [/^\s+\S+ \d+번째/, "scenes"],
86
+ [/^\s+\d+\/\d+ \(\d+%\)/, "render"],
87
+ [/^고치기 /, "scenes"],
88
+ [/^그림 검사/, "check"],
89
+ ];
90
+
91
+ export class Engine extends EventEmitter {
92
+ jobs = new Map<string, Job>();
93
+ private procs = new Map<string, ChildProcess>();
94
+ private previews = new Map<string, { proc: ChildProcess; port: number }>();
95
+
96
+ constructor() {
97
+ super();
98
+ mkdirSync(join(dataDir, "jobs"), { recursive: true });
99
+ for (const id of readdirSync(join(dataDir, "jobs"))) {
100
+ const f = join(dataDir, "jobs", id, "job.json");
101
+ if (!existsSync(f)) continue;
102
+ const job: Job = { ...JSON.parse(readFileSync(f, "utf8")), running: false, previewUrl: undefined };
103
+ if (!["done", "failed", "waiting"].includes(job.phase)) job.phase = "failed";
104
+ this.jobs.set(id, job);
105
+ }
106
+ }
107
+
108
+ // 틀 고르는 화면용. still 은 templates/_shared/previews.ts 가 뽑아 둔 대표 한 장
109
+ templates() {
110
+ return listTemplates().map((t) => ({
111
+ id: t.id,
112
+ label: t.label,
113
+ summary: t.summary,
114
+ aspect: t.aspect,
115
+ aspects: [t.aspect, ...Object.keys(t.variants ?? {})],
116
+ width: t.width,
117
+ height: t.height,
118
+ duration: t.duration,
119
+ music: t.music,
120
+ captions: t.captions,
121
+ deliverables: t.deliverables,
122
+ scenes: t.scenes.map((s) => s.id),
123
+ still: existsSync(templatePreview(t.id)) ? `/api/templates/${t.id}/still.png` : null,
124
+ }));
125
+ }
126
+
127
+ // 만들기 전에 보여 줄 계획 — 곡 분석 없이 길이·장면 비율만. 사람이 용도를 고르면 판별을 건너뛰고, "auto" 거나 비우면 판별한다.
128
+ // asks 는 돈이 들거나 없는 생성 능력만(kf make 와 같은 질문) — 페이지가 고른 답을 일에 실어 보낸다
129
+ async plan(request: string, purpose?: Purpose | "auto", theme?: string): Promise<Plan> {
130
+ const plan = makePlan({ request, purpose: purpose && purpose !== "auto" ? purpose : undefined, theme });
131
+ const { questions, auto } = planQuestions(plan, await capabilities({ probe: true }));
132
+ return { ...plan, asks: questions, answers: auto };
133
+ }
134
+
135
+ // 목록은 approved 만(SPEC 9). all 이면 review·draft 도 — 테마 만드는 사람이 견본을 보는 자리
136
+ themes(o: { all?: boolean; purpose?: string; aspect?: string } = {}) {
137
+ const status: ThemeStatus[] = o.all ? ["approved", "review", "draft"] : ["approved"];
138
+ return themeCards({ status, ...(o.purpose ? { purpose: o.purpose } : {}), ...(o.aspect ? { aspect: o.aspect } : {}) }).map((c) => ({
139
+ ...c,
140
+ still: c.still ? `/api/themes/${c.id}/still` : null,
141
+ sample: c.sample ? `/api/themes/${c.id}/sample` : null,
142
+ }));
143
+ }
144
+
145
+ themeFile(id: string, which: "still" | "sample"): string | null {
146
+ return loadTheme(id).files[which];
147
+ }
148
+
149
+ suggest(request: string, purpose: Purpose) {
150
+ return { candidates: suggestThemes(request, purpose) };
151
+ }
152
+
153
+ // 테마 공장(kf theme) — new 는 뼈대·지시서까지 만들고 그 지시서를 받을 세션 명령을 돌려준다(테마는 그 세션이 만든다).
154
+ // review 는 굽기라 무겁다 — 하나씩, 진행은 themeTask 로. approve 는 사람이 화면에서 견본을 보고 누를 때만
155
+ private themeTasks = new Map<string, { running: boolean; log: string[]; code: number | null }>();
156
+
157
+ async themeNew(o: { id: string; refs: string[]; name?: string; like?: string; threeD?: boolean }): Promise<{ ok: boolean; command: string | null; log: string[] }> {
158
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(o.id)) throw Object.assign(new Error("테마 id 는 영문 소문자·숫자·- 만"), { status: 400 });
159
+ if (!o.refs?.length) throw Object.assign(new Error("참고 자료(refs)가 하나는 있어야 한다"), { status: 400 });
160
+ const args = ["theme", "new", o.id, ...o.refs.flatMap((r) => ["--ref", r])];
161
+ if (o.name) args.push("--name", o.name);
162
+ if (o.like) args.push("--like", o.like);
163
+ if (o.threeD) args.push("--3d");
164
+ const { code, log } = await this.kf(args);
165
+ const at = log.findIndex((l) => l.includes("세션 열기"));
166
+ return { ok: code === 0, command: at >= 0 ? (log[at + 1]?.trim() ?? null) : null, log };
167
+ }
168
+
169
+ themeReview(id: string): { started: boolean } {
170
+ const cur = this.themeTasks.get(id);
171
+ if (cur?.running) throw Object.assign(new Error("이미 굽는 중"), { status: 409 });
172
+ const task = { running: true, log: [] as string[], code: null as number | null };
173
+ this.themeTasks.set(id, task);
174
+ void this.kf(["theme", "review", id, "--tabs", "2"], (l) => task.log.push(l)).then(({ code }) => {
175
+ task.running = false;
176
+ task.code = code;
177
+ });
178
+ return { started: true };
179
+ }
180
+
181
+ themeTask(id: string) {
182
+ const t = this.themeTasks.get(id);
183
+ return t ? { running: t.running, code: t.code, log: t.log.slice(-60) } : { running: false, code: null, log: [] };
184
+ }
185
+
186
+ async themeApprove(id: string) {
187
+ return this.kf(["theme", "approve", id]);
188
+ }
189
+
190
+ private kf(args: string[], onLine?: (l: string) => void): Promise<{ code: number; log: string[] }> {
191
+ return new Promise((done) => {
192
+ const log: string[] = [];
193
+ const proc = spawn(process.execPath, [kfBin, ...args], { cwd: repo, env: { ...process.env, CLAUDECODE: "" } });
194
+ for (const stream of [proc.stdout, proc.stderr]) {
195
+ let buf = "";
196
+ stream.setEncoding("utf8");
197
+ stream.on("data", (chunk: string) => {
198
+ buf += chunk;
199
+ const parts = buf.split(/\r?\n/);
200
+ buf = parts.pop() ?? "";
201
+ for (const l of parts) {
202
+ log.push(l);
203
+ onLine?.(l);
204
+ }
205
+ });
206
+ }
207
+ proc.on("close", (code) => done({ code: code ?? 1, log }));
208
+ });
209
+ }
210
+
211
+ create(input: JobInput): Job {
212
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
213
+ const job: Job = { id, input, dir: join(dataDir, "jobs", id, "project"), phase: "plan", progress: 0, running: false, createdAt: Date.now(), log: [] };
214
+ this.jobs.set(id, job);
215
+ mkdirSync(join(dataDir, "jobs", id), { recursive: true });
216
+ // 모델을 안 고르면 kf make 의 기본 — 고른 모델은 plan.json 에 남아 장면 다시 쓰기가 같은 모델을 부른다
217
+ const args = ["make", input.request, "--out", job.dir, ...(input.model ? ["--model", input.model] : [])];
218
+ if (input.purpose && input.purpose !== "auto") args.push("--purpose", input.purpose);
219
+ if (input.music) args.push("--music", input.music);
220
+ const given = (input.assets ?? []).filter((a) => existsSync(a));
221
+ if (given.length) {
222
+ const inDir = join(dataDir, "jobs", id, "in");
223
+ mkdirSync(inDir, { recursive: true });
224
+ for (const a of given) copyFileSync(a, join(inDir, basename(a).replace(/^[a-z0-9]+-/, "")));
225
+ args.push("--assets", inDir);
226
+ }
227
+ if (input.title) args.push("--title", input.title);
228
+ if (input.theme) args.push("--theme", input.theme);
229
+ if (input.approve) args.push("--yes");
230
+ if (input.captions) args.push("--captions", input.captions);
231
+ // 질문 id 가 곧 kf make 플래그 이름이다(image·video·blender·voice·music)
232
+ for (const [id, v] of Object.entries(input.answers ?? {})) if (/^[a-z]+$/.test(id) && v) args.push(`--${id}`, v);
233
+ this.run(job, args);
234
+ return job;
235
+ }
236
+
237
+ // 장면 카드에서 고친 뒤: 고른 장면만 다시 쓰고(감독 프로젝트는 다시 짓고) 그 조각만 다시 굽고 그 구간만 검사.
238
+ // 모델은 그 일의 모델 그대로 — 안 정했으면 kf make 가 plan.json 에 남은 모델을 쓴다. pattern·seed 는 감독 후보 고르기
239
+ rewrite(id: string, scenes: string[], o: { pattern?: Record<string, string>; seed?: Record<string, string> } = {}): Job {
240
+ const job = this.must(id);
241
+ if (!scenes.length) throw Object.assign(new Error("다시 쓸 장면이 없다"), { status: 400 });
242
+ const pairs = (m?: Record<string, string>) => Object.entries(m ?? {}).filter(([k, v]) => scenes.includes(k) && v).map(([k, v]) => `${k}=${v}`).join(",");
243
+ const args = ["make", "--rewrite", job.dir, "--scenes", scenes.join(",")];
244
+ if (job.input.model) args.push("--model", job.input.model);
245
+ if (pairs(o.pattern)) args.push("--pattern", pairs(o.pattern));
246
+ if (pairs(o.seed)) args.push("--scene-seed", pairs(o.seed));
247
+ this.focusOn(job, scenes);
248
+ this.run(job, args);
249
+ return job;
250
+ }
251
+
252
+ // 장면 파일은 그대로, 바뀐 조각만 다시 굽고 그 구간만 검사 — 손으로 고친 장면·바꾼 자산
253
+ redo(id: string, scenes: string[]): Job {
254
+ const job = this.must(id);
255
+ if (!scenes.length) throw Object.assign(new Error("다시 구울 장면이 없다"), { status: 400 });
256
+ this.focusOn(job, scenes);
257
+ this.run(job, ["make", "--finish", job.dir, "--scenes", scenes.join(","), "--fix", "0"]);
258
+ return job;
259
+ }
260
+
261
+ // captions 를 주면 장면을 다시 쓰지 않고 자막만 켜고(끄고) 따로 굽는다 — 원본 video.mp4 는 그대로 두고 -자막 판을 옆에
262
+ rerender(id: string, o: { captions?: "on" | "off" } = {}): Job {
263
+ const job = this.must(id);
264
+ const caps = o.captions === "on" || o.captions === "off" ? ["--captions", o.captions, "--suffix"] : [];
265
+ this.run(job, ["make", "--finish", job.dir, "--fix", "0", ...caps]);
266
+ return job;
267
+ }
268
+
269
+ private focusOn(job: Job, scenes: string[]): void {
270
+ job.focus = scenes[0];
271
+ job.scenes = Object.fromEntries(Object.entries(job.scenes ?? {}).filter(([k]) => !scenes.includes(k)));
272
+ }
273
+
274
+ private sceneLine(job: Job, line: string): void {
275
+ const m = line.match(SCENE_LINE);
276
+ if (!m) return;
277
+ (job.scenes ??= {})[m[1]] = { state: SCENE_WORDS[m[2]], ...(m[3] ? { note: m[3].trim() } : {}), at: Date.now() };
278
+ }
279
+
280
+ // 장면 하나 고치는 자리 — 감독 프로젝트는 content.json 의 그 장면 칸·패턴 후보·씨앗, 아니면 할 일·장면 모델. 자산은 그 장면이 쓰는 그림·영상
281
+ sceneDetail(id: string, sid: string): SceneDetail {
282
+ const job = this.must(id);
283
+ const read = (f: string) => (existsSync(join(job.dir, f)) ? JSON.parse(readFileSync(join(job.dir, f), "utf8")) : null);
284
+ const kf = read("kf.json");
285
+ const scene = kf?.scenes?.find((s: { id: string }) => s.id === sid);
286
+ if (!scene) throw Object.assign(new Error(`장면 ${sid} 가 없다`), { status: 404 });
287
+ const plan = read("plan.json") ?? {};
288
+ const director = read("director.json");
289
+ const ds = director?.scenes?.find((s: { id: string }) => s.id === sid);
290
+ const file = join(job.dir, scene.file ?? `scenes/${sid}.ts`);
291
+ const src = existsSync(file) ? readFileSync(file, "utf8") : "";
292
+ const assetsDir = join(job.dir, "assets");
293
+ const walk = (d: string): string[] => (existsSync(d) ? readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)])) : []);
294
+ const assets = walk(assetsDir)
295
+ .filter((f) => /\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i.test(f))
296
+ .map((f) => relative(assetsDir, f).split(sep).join("/"))
297
+ .filter((rel) => src.includes(rel) || basename(rel).startsWith(`${sid}.`) || basename(rel).startsWith(`${sid}-`))
298
+ .map((rel) => ({ path: rel, url: `/api/jobs/${id}/files/assets/${rel}`, kind: (/\.(mp4|webm|mov)$/i.test(rel) ? "video" : "image") as "image" | "video" }));
299
+ return {
300
+ scene,
301
+ direct: plan.direct === true,
302
+ model: job.input.model ?? plan.model ?? null,
303
+ content: read("content.json")?.scenes?.find((s: { id: string }) => s.id === sid) ?? null,
304
+ pattern: ds?.pattern ?? null,
305
+ candidates: ds?.order ?? [],
306
+ pinned: director?.pinned?.[sid] ?? null,
307
+ assets,
308
+ };
309
+ }
310
+
311
+ // 사람이 올린 파일로 그 장면 자산 하나를 바꾼다 — 다음 굽기에서 그 자산을 쓰는 조각만 다시 찍힌다
312
+ replaceAsset(id: string, sid: string, o: { path: string; upload: string }): SceneDetail {
313
+ const job = this.must(id);
314
+ const detail = this.sceneDetail(id, sid);
315
+ if (!detail.assets.some((a) => a.path === o.path)) throw Object.assign(new Error(`장면 ${sid} 가 쓰는 자산이 아니다: ${o.path}`), { status: 400 });
316
+ if (!existsSync(o.upload)) throw Object.assign(new Error("올린 파일이 없다"), { status: 400 });
317
+ if (extname(o.upload).toLowerCase() !== extname(o.path).toLowerCase()) throw Object.assign(new Error(`같은 꼴(${extname(o.path)})로 올린다`), { status: 400 });
318
+ copyFileSync(o.upload, join(job.dir, "assets", o.path));
319
+ return this.sceneDetail(id, sid);
320
+ }
321
+
322
+ // 말로 시작한 kf make(Claude Code 등)가 스스로 등록한다 — 같은 폴더면 같은 일(--finish 가 다시 붙는다)
323
+ attach(o: { dir: string; request: string; model?: string; purpose?: Purpose }): Job {
324
+ const dir = resolve(o.dir);
325
+ const had = [...this.jobs.values()].find((j) => j.dir === dir);
326
+ if (had) return had;
327
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
328
+ const job: Job = { id, external: true, input: { request: o.request, model: o.model, purpose: o.purpose }, dir, phase: "scaffold", progress: 0, running: true, createdAt: Date.now(), log: [] };
329
+ this.jobs.set(id, job);
330
+ mkdirSync(join(dataDir, "jobs", id), { recursive: true });
331
+ if (existsSync(join(dir, "kf.json"))) this.startPreview(job);
332
+ this.save(job);
333
+ this.emit("state", this.view(id));
334
+ return job;
335
+ }
336
+
337
+ progress(id: string, p: { lines?: string[]; phase?: Phase; done?: boolean; ok?: boolean }): void {
338
+ const job = this.must(id);
339
+ for (const line of p.lines ?? []) {
340
+ job.log.push(line);
341
+ this.sceneLine(job, line);
342
+ for (const [re, phase] of PHASES) if (re.test(line)) job.phase = phase;
343
+ const pct = line.match(/\((\d+)%\)/);
344
+ if (pct && job.phase === "render") job.progress = Number(pct[1]) / 100;
345
+ this.emit("log", id, line);
346
+ }
347
+ if (job.log.length > 800) job.log.splice(0, job.log.length - 800);
348
+ if (p.phase) job.phase = p.phase;
349
+ job.running = !p.done;
350
+ if (p.done) {
351
+ job.checkPassed = !!p.ok;
352
+ job.phase = p.phase ?? (existsSync(join(job.dir, "out", "video.mp4")) ? "done" : "failed");
353
+ this.stopPreview(job);
354
+ } else if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
355
+ this.save(job);
356
+ this.emit("state", this.view(id));
357
+ }
358
+
359
+ editScene(id: string, sceneId: string, patch: { idea?: string; dur?: number; content?: Record<string, unknown> }): unknown {
360
+ const job = this.must(id);
361
+ // 감독 프로젝트 — 화면에 보일 것은 content.json 이 정본이다. 칸이 틀리면 저장하지 않고 어느 칸인지 돌려준다
362
+ if (patch.content) {
363
+ const cPath = join(job.dir, "content.json");
364
+ if (!existsSync(cPath)) throw Object.assign(new Error("content.json 이 없다 — 감독 모드로 만든 일이 아니다"), { status: 400 });
365
+ const content = JSON.parse(readFileSync(cPath, "utf8"));
366
+ const at = content.scenes?.findIndex((s: { id: string }) => s.id === sceneId) ?? -1;
367
+ if (at < 0) throw Object.assign(new Error(`content.json 에 장면 ${sceneId} 가 없다`), { status: 404 });
368
+ content.scenes[at] = { ...patch.content, id: sceneId };
369
+ const c = checkContent(content);
370
+ if (c.errors.length) throw Object.assign(new Error(c.errors.map((e) => `${e.at}: ${e.msg}`).join("\n")), { status: 400 });
371
+ writeFileSync(cPath, `${JSON.stringify(content, null, 2)}\n`);
372
+ }
373
+ const kfPath = join(job.dir, "kf.json");
374
+ const kf = JSON.parse(readFileSync(kfPath, "utf8"));
375
+ const i = kf.scenes.findIndex((s: { id: string }) => s.id === sceneId);
376
+ if (i < 0) throw new Error(`장면 ${sceneId} 가 없다`);
377
+ if (patch.idea !== undefined) kf.scenes[i].idea = patch.idea;
378
+ // 시간표는 빈틈 없이 이어져야 한다(계약 6) — 길이를 바꾸면 다음 장면 시작이 따라 움직인다
379
+ if (patch.dur !== undefined && i < kf.scenes.length - 1) {
380
+ const next = kf.scenes[i + 1];
381
+ const end = next.from + next.dur;
382
+ const dur = Math.round(Math.max(0.5, Math.min(patch.dur, end - kf.scenes[i].from - 0.5)) * kf.fps) / kf.fps;
383
+ kf.scenes[i].dur = +dur.toFixed(4);
384
+ next.from = +(kf.scenes[i].from + dur).toFixed(4);
385
+ next.dur = +(end - next.from).toFixed(4);
386
+ }
387
+ writeFileSync(kfPath, `${JSON.stringify(kf, null, 2)}\n`);
388
+ const planPath = join(job.dir, "plan.json");
389
+ if (existsSync(planPath) && patch.idea !== undefined) {
390
+ const plan = JSON.parse(readFileSync(planPath, "utf8"));
391
+ const s = plan.scenes?.find((x: { id: string }) => x.id === sceneId);
392
+ if (s) s.idea = patch.idea;
393
+ writeFileSync(planPath, `${JSON.stringify(plan, null, 2)}\n`);
394
+ }
395
+ this.emit("state", this.view(id));
396
+ return kf;
397
+ }
398
+
399
+ view(id: string): JobView {
400
+ const job = this.must(id);
401
+ const read = (f: string) => (existsSync(join(job.dir, f)) ? JSON.parse(readFileSync(join(job.dir, f), "utf8")) : undefined);
402
+ const has = (f: string) => (existsSync(join(job.dir, f)) ? f : undefined);
403
+ const { log: _log, ...rest } = job;
404
+ const kf = read("kf.json");
405
+ const alt = has(captionMode(kf?.captions) === "on" ? "out/video-자막없음.mp4" : "out/video-자막.mp4");
406
+ const video = has("out/video.mp4");
407
+ // 같은 이름으로 다시 구워도 화면이 새 영상을 받게 — 고친 시각을 붙인다
408
+ const videoAt = video ? Math.round(statSync(join(job.dir, video)).mtimeMs) : undefined;
409
+ return { ...rest, plan: read("plan.json"), kf, files: { video, cover: has("out/cover.png"), check: has("out/check.json"), alt, captions: has("captions.json"), videoAt } };
410
+ }
411
+
412
+ list(): JobView[] {
413
+ return [...this.jobs.keys()].map((id) => this.view(id)).sort((a, b) => b.createdAt - a.createdAt);
414
+ }
415
+
416
+ logOf(id: string): string[] {
417
+ return this.must(id).log;
418
+ }
419
+
420
+ stop(id: string): void {
421
+ this.procs.get(id)?.kill("SIGTERM");
422
+ }
423
+
424
+ async close(): Promise<void> {
425
+ for (const p of this.procs.values()) p.kill("SIGTERM");
426
+ for (const p of this.previews.values()) p.proc.kill("SIGTERM");
427
+ }
428
+
429
+ private must(id: string): Job {
430
+ const job = this.jobs.get(id);
431
+ if (!job) throw Object.assign(new Error(`일 ${id} 가 없다`), { status: 404 });
432
+ return job;
433
+ }
434
+
435
+ private run(job: Job, args: string[]): void {
436
+ if (job.running) throw Object.assign(new Error("이미 돌고 있다"), { status: 409 });
437
+ job.running = true;
438
+ job.error = undefined;
439
+ job.progress = 0;
440
+ const proc = spawn(process.execPath, [kfBin, ...args], { cwd: repo, env: { ...process.env, CLAUDECODE: "" } });
441
+ this.procs.set(job.id, proc);
442
+ const onLine = (line: string) => {
443
+ if (!line.trim()) return;
444
+ job.log.push(line);
445
+ if (job.log.length > 800) job.log.splice(0, job.log.length - 800);
446
+ this.sceneLine(job, line);
447
+ for (const [re, phase] of PHASES) if (re.test(line)) job.phase = phase;
448
+ const pct = line.match(/\((\d+)%\)/);
449
+ if (pct && job.phase === "render") job.progress = Number(pct[1]) / 100;
450
+ if (/^검사:/.test(line)) job.phase = "check";
451
+ this.emit("log", job.id, line);
452
+ if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
453
+ this.emit("state", this.view(job.id));
454
+ };
455
+ for (const stream of [proc.stdout, proc.stderr]) {
456
+ let buf = "";
457
+ stream.setEncoding("utf8");
458
+ stream.on("data", (chunk: string) => {
459
+ buf += chunk;
460
+ const parts = buf.split(/\r?\n|\r/);
461
+ buf = parts.pop() ?? "";
462
+ parts.forEach(onLine);
463
+ });
464
+ }
465
+ proc.on("close", (code) => {
466
+ this.procs.delete(job.id);
467
+ job.running = false;
468
+ // 다 만들었으면 화면은 MP4 를 튼다 — 미리보기 서버는 꺼서 기계 부하를 줄인다(다시 보려면 /preview 가 다시 띄운다)
469
+ this.stopPreview(job);
470
+ job.checkPassed = code === 0;
471
+ if (code === 0) job.phase = "done";
472
+ else if (code === 3) job.phase = "waiting";
473
+ else {
474
+ job.phase = existsSync(join(job.dir, "out", "video.mp4")) ? "done" : "failed";
475
+ job.error = job.log.slice(-6).join("\n");
476
+ }
477
+ job.progress = job.phase === "done" ? 1 : job.progress;
478
+ this.save(job);
479
+ this.emit("state", this.view(job.id));
480
+ });
481
+ this.save(job);
482
+ }
483
+
484
+ // 만드는 동안 장면 파일이 쓰일 때마다 미리보기가 저절로 새로 고쳐진다(kf preview 의 감시)
485
+ private startPreview(job: Job): void {
486
+ if (this.previews.has(job.id)) return;
487
+ const used = new Set([...this.previews.values()].map((p) => p.port));
488
+ let port = PREVIEW_PORTS.find((p) => !used.has(p));
489
+ if (port === undefined) {
490
+ const [oldest] = this.previews.keys();
491
+ const old = this.previews.get(oldest)!;
492
+ old.proc.kill("SIGTERM");
493
+ this.previews.delete(oldest);
494
+ const j = this.jobs.get(oldest);
495
+ if (j) j.previewUrl = undefined;
496
+ port = old.port;
497
+ }
498
+ const proc = spawn(process.execPath, [kfBin, "preview", job.dir, "--port", String(port)], { cwd: repo, stdio: ["ignore", "pipe", "pipe"] });
499
+ this.previews.set(job.id, { proc, port });
500
+ job.previewUrl = `http://127.0.0.1:${port}/`;
501
+ const grab = (chunk: Buffer) => {
502
+ const m = chunk.toString().match(/https?:\/\/[^\s]+/);
503
+ if (m) {
504
+ job.previewUrl = m[0];
505
+ this.emit("state", this.view(job.id));
506
+ }
507
+ };
508
+ proc.stdout?.on("data", grab);
509
+ proc.stderr?.on("data", grab);
510
+ proc.on("close", () => {
511
+ if (this.previews.get(job.id)?.proc === proc) this.previews.delete(job.id);
512
+ });
513
+ }
514
+
515
+ private stopPreview(job: Job): void {
516
+ const p = this.previews.get(job.id);
517
+ if (!p) return;
518
+ p.proc.kill("SIGTERM");
519
+ this.previews.delete(job.id);
520
+ job.previewUrl = undefined;
521
+ }
522
+
523
+ previewFor(id: string): string | undefined {
524
+ const job = this.must(id);
525
+ if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
526
+ return job.previewUrl;
527
+ }
528
+
529
+ private save(job: Job): void {
530
+ const { previewUrl: _p, running: _r, ...rest } = job;
531
+ writeFileSync(join(dataDir, "jobs", job.id, "job.json"), `${JSON.stringify(rest, null, 2)}\n`);
532
+ }
533
+ }