videobook 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (565) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/bin/videobook.js +7 -0
  5. package/dist/acestep/client.js +203 -0
  6. package/dist/acestep/config.js +62 -0
  7. package/dist/acestep/errors.js +8 -0
  8. package/dist/acestep/process.js +175 -0
  9. package/dist/alive-captions/analyze.js +117 -0
  10. package/dist/alive-captions/audio.js +179 -0
  11. package/dist/alive-captions/frames.js +59 -0
  12. package/dist/alive-captions/model.js +37 -0
  13. package/dist/alive-captions/schema.js +49 -0
  14. package/dist/alive-captions/track.js +9 -0
  15. package/dist/api-key.js +33 -0
  16. package/dist/app-state.js +56 -0
  17. package/dist/app.js +257 -0
  18. package/dist/archive-b2.js +332 -0
  19. package/dist/archive-store.js +169 -0
  20. package/dist/artifact-label.js +36 -0
  21. package/dist/artifact-refs.js +49 -0
  22. package/dist/asset-tag-extraction.js +169 -0
  23. package/dist/asset-tags.js +228 -0
  24. package/dist/asset-usage.js +23 -0
  25. package/dist/audio-cue.js +71 -0
  26. package/dist/audio-encoding.js +32 -0
  27. package/dist/audio-sync-request.js +1 -0
  28. package/dist/audio-sync.js +223 -0
  29. package/dist/audio-trim-range.js +31 -0
  30. package/dist/book-context.js +31 -0
  31. package/dist/book-manager.js +374 -0
  32. package/dist/catalog-gc.js +26 -0
  33. package/dist/chain-executor.js +815 -0
  34. package/dist/chain-generation.js +115 -0
  35. package/dist/chain-plan.js +746 -0
  36. package/dist/chain-step-review.js +60 -0
  37. package/dist/character-name.js +25 -0
  38. package/dist/chat-generation-routing.js +73 -0
  39. package/dist/chat-generation-settings.js +78 -0
  40. package/dist/chat-models.js +44 -0
  41. package/dist/chat-prompt-rewrite.js +67 -0
  42. package/dist/chat-router.js +628 -0
  43. package/dist/chat-view-actions.js +49 -0
  44. package/dist/cli/args.js +242 -0
  45. package/dist/cli/config-command.js +103 -0
  46. package/dist/cli/doctor-command.js +289 -0
  47. package/dist/cli/entry.js +2 -0
  48. package/dist/cli/key-report.js +16 -0
  49. package/dist/cli/main.js +104 -0
  50. package/dist/cli/mcp-command.js +88 -0
  51. package/dist/cli/mcp-relay.js +51 -0
  52. package/dist/cli/open-browser.js +14 -0
  53. package/dist/cli/run-command.js +231 -0
  54. package/dist/cli/serve-command.js +62 -0
  55. package/dist/cli/setup-command.js +60 -0
  56. package/dist/cli/stdio-guard.js +8 -0
  57. package/dist/cold-open-model.js +7 -0
  58. package/dist/cold-open.js +79 -0
  59. package/dist/command-reference.js +95 -0
  60. package/dist/content-store.js +74 -0
  61. package/dist/cost.js +8 -0
  62. package/dist/crop-geometry.js +23 -0
  63. package/dist/dancing-workflow.js +447 -0
  64. package/dist/data-home.js +44 -0
  65. package/dist/diagnostics.js +109 -0
  66. package/dist/dialog-quality.js +34 -0
  67. package/dist/downloads-dest.js +56 -0
  68. package/dist/editing-moments.js +194 -0
  69. package/dist/elevenlabs-audio-extension.js +66 -0
  70. package/dist/engine.js +54 -0
  71. package/dist/env-file.js +91 -0
  72. package/dist/env-secrets.js +148 -0
  73. package/dist/ffmpeg-binary.js +12 -0
  74. package/dist/ffmpeg.js +425 -0
  75. package/dist/ffprobe-binary.js +77 -0
  76. package/dist/forget-asset.js +216 -0
  77. package/dist/frame-utils.js +27 -0
  78. package/dist/generation-credit-error.js +11 -0
  79. package/dist/generation-input-mentions.js +117 -0
  80. package/dist/generation-input-policy.js +68 -0
  81. package/dist/generation-reference-mentions.js +97 -0
  82. package/dist/goal-characters.js +49 -0
  83. package/dist/goal-plan-v3.js +273 -0
  84. package/dist/goal-plan.js +220 -0
  85. package/dist/goal-planner-prompt.js +28 -0
  86. package/dist/goal-prompt-budget.js +4 -0
  87. package/dist/goal-reference-images.js +25 -0
  88. package/dist/goal-state.js +261 -0
  89. package/dist/goal-stills.js +153 -0
  90. package/dist/goal-store.js +144 -0
  91. package/dist/goal-styles.js +144 -0
  92. package/dist/goal-v3-runtime.js +157 -0
  93. package/dist/guides/character_schema_guide.md +70 -0
  94. package/dist/guides/gpt_image_2_5_prompting_guide.md +21 -0
  95. package/dist/guides/grok_imagine_prompting_guide.md +72 -0
  96. package/dist/guides/image_reproduction_guide.md +84 -0
  97. package/dist/guides/kling_3_0_prompting_guide.md +136 -0
  98. package/dist/guides/nano_banana_pro_prompting_guide.md +28 -0
  99. package/dist/guides/seedance_2_prompting_guide.md +172 -0
  100. package/dist/http-access.js +49 -0
  101. package/dist/http-byte-range.js +31 -0
  102. package/dist/hydration.js +56 -0
  103. package/dist/image-compress.js +77 -0
  104. package/dist/image-edit-default.js +1 -0
  105. package/dist/image-edit-models.js +41 -0
  106. package/dist/image-edit-settings.js +11 -0
  107. package/dist/image-region-edit.js +32 -0
  108. package/dist/image-subject-map.js +523 -0
  109. package/dist/image.js +46 -0
  110. package/dist/index.js +12 -0
  111. package/dist/job-deadline.js +60 -0
  112. package/dist/jobs/_alibaba-upload.js +30 -0
  113. package/dist/jobs/_audio-chunks.js +31 -0
  114. package/dist/jobs/_download-into-asset.js +15 -0
  115. package/dist/jobs/_fal-shared.js +22 -0
  116. package/dist/jobs/_fal-upload.js +35 -0
  117. package/dist/jobs/_image-edit-adapter.js +213 -0
  118. package/dist/jobs/_kie-poll.js +119 -0
  119. package/dist/jobs/_kie-upload.js +32 -0
  120. package/dist/jobs/_lease.js +163 -0
  121. package/dist/jobs/_persist-output.js +19 -0
  122. package/dist/jobs/_storage-retry.js +21 -0
  123. package/dist/jobs/_transcribe.js +245 -0
  124. package/dist/jobs/_translate-transcript.js +270 -0
  125. package/dist/jobs/analyze-alive-captions.js +10 -0
  126. package/dist/jobs/analyze-editing-moments.js +104 -0
  127. package/dist/jobs/analyze-jokes.js +143 -0
  128. package/dist/jobs/analyze-keyword-placement.js +155 -0
  129. package/dist/jobs/analyze-music.js +14 -0
  130. package/dist/jobs/analyze-video.js +282 -0
  131. package/dist/jobs/apply-cuts.js +83 -0
  132. package/dist/jobs/apply-sfx.js +107 -0
  133. package/dist/jobs/archive-clip.js +458 -0
  134. package/dist/jobs/assemble-goal.js +98 -0
  135. package/dist/jobs/audio-boost.js +71 -0
  136. package/dist/jobs/audio-mix.js +161 -0
  137. package/dist/jobs/backfill-asset-tags.js +144 -0
  138. package/dist/jobs/burn-watermark.js +316 -0
  139. package/dist/jobs/change-video-speed.js +176 -0
  140. package/dist/jobs/clean-video-audio.js +207 -0
  141. package/dist/jobs/cold-open.js +166 -0
  142. package/dist/jobs/combine-goal.js +108 -0
  143. package/dist/jobs/complete-provider-task.js +185 -0
  144. package/dist/jobs/copy-library-asset.js +33 -0
  145. package/dist/jobs/cost-estimate-assessment.js +113 -0
  146. package/dist/jobs/crop-image.js +47 -0
  147. package/dist/jobs/crop-video.js +71 -0
  148. package/dist/jobs/describe-image.js +181 -0
  149. package/dist/jobs/detect-scenes.js +33 -0
  150. package/dist/jobs/doctor-fix.js +100 -0
  151. package/dist/jobs/download-video.js +427 -0
  152. package/dist/jobs/enqueue-search-index.js +24 -0
  153. package/dist/jobs/even-split.js +122 -0
  154. package/dist/jobs/export-sequence.js +365 -0
  155. package/dist/jobs/extend-audio.js +229 -0
  156. package/dist/jobs/extract-audio.js +72 -0
  157. package/dist/jobs/extract-frame.js +58 -0
  158. package/dist/jobs/extract-notebook-audio.js +82 -0
  159. package/dist/jobs/extract-notebook-frame.js +93 -0
  160. package/dist/jobs/extract-video-clip.js +8 -0
  161. package/dist/jobs/extract-video-poster.js +55 -0
  162. package/dist/jobs/extract-waveform.js +25 -0
  163. package/dist/jobs/finish-goal.js +255 -0
  164. package/dist/jobs/forget-asset.js +11 -0
  165. package/dist/jobs/generate-acestep-cover.js +219 -0
  166. package/dist/jobs/generate-media.js +70 -0
  167. package/dist/jobs/image-subjects.js +1059 -0
  168. package/dist/jobs/index.js +18 -0
  169. package/dist/jobs/inject-first-frame.js +175 -0
  170. package/dist/jobs/isolate-vocals.js +69 -0
  171. package/dist/jobs/kie-paygate.js +177 -0
  172. package/dist/jobs/label-music-sections.js +5 -0
  173. package/dist/jobs/osg-placement.js +135 -0
  174. package/dist/jobs/pad-video.js +72 -0
  175. package/dist/jobs/plan-goal.js +97 -0
  176. package/dist/jobs/post-record.js +21 -0
  177. package/dist/jobs/post-to-x.js +21 -0
  178. package/dist/jobs/prepare-search-reference.js +190 -0
  179. package/dist/jobs/prepare-temporal-search.js +16 -0
  180. package/dist/jobs/process-audio.js +67 -0
  181. package/dist/jobs/process-image.js +58 -0
  182. package/dist/jobs/process-upload.js +166 -0
  183. package/dist/jobs/process-video.js +438 -0
  184. package/dist/jobs/register-all.js +161 -0
  185. package/dist/jobs/relayout-notebook.js +78 -0
  186. package/dist/jobs/remove-sound.js +299 -0
  187. package/dist/jobs/render-project.js +380 -0
  188. package/dist/jobs/render-qr-outro.js +138 -0
  189. package/dist/jobs/render-timeline.js +283 -0
  190. package/dist/jobs/repair-search-indexes.js +42 -0
  191. package/dist/jobs/replace-video-audio.js +64 -0
  192. package/dist/jobs/restore-archive-clip.js +53 -0
  193. package/dist/jobs/reverse-video.js +53 -0
  194. package/dist/jobs/rewrite-script.js +173 -0
  195. package/dist/jobs/run-notebook.js +3335 -0
  196. package/dist/jobs/semantic-index.js +797 -0
  197. package/dist/jobs/smooth-scene-concat.js +257 -0
  198. package/dist/jobs/splice-video.js +280 -0
  199. package/dist/jobs/split-video.js +127 -0
  200. package/dist/jobs/suggest-cuts.js +149 -0
  201. package/dist/jobs/suggest-sfx.js +135 -0
  202. package/dist/jobs/sync-video-to-audio.js +329 -0
  203. package/dist/jobs/tag-asset.js +266 -0
  204. package/dist/jobs/task-failure.js +16 -0
  205. package/dist/jobs/timewarp-video.js +152 -0
  206. package/dist/jobs/transcribe-video-audio.js +117 -0
  207. package/dist/jobs/transcribe.js +35 -0
  208. package/dist/jobs/translate-transcript.js +55 -0
  209. package/dist/jobs/trim-audio.js +133 -0
  210. package/dist/jobs/trim-video.js +291 -0
  211. package/dist/jobs/xai-paygate.js +26 -0
  212. package/dist/keyword-placement-cache.js +74 -0
  213. package/dist/lazy-render.js +142 -0
  214. package/dist/library-browse.js +78 -0
  215. package/dist/lightning-defaults.js +206 -0
  216. package/dist/load-env.js +12 -0
  217. package/dist/local-search-models.js +206 -0
  218. package/dist/local-upload.js +318 -0
  219. package/dist/logger.js +69 -0
  220. package/dist/media/adapters/alibaba.js +20 -0
  221. package/dist/media/adapters/elevenlabs.js +58 -0
  222. package/dist/media/adapters/fal.js +45 -0
  223. package/dist/media/adapters/index.js +26 -0
  224. package/dist/media/adapters/kie.js +120 -0
  225. package/dist/media/adapters/pending.js +21 -0
  226. package/dist/media/adapters/types.js +5 -0
  227. package/dist/media/adapters/xai.js +18 -0
  228. package/dist/media/catalog.js +236 -0
  229. package/dist/media/complete.js +191 -0
  230. package/dist/media/cost.js +45 -0
  231. package/dist/media/descriptor.js +157 -0
  232. package/dist/media/endpoints.js +11 -0
  233. package/dist/media/frame-options.js +18 -0
  234. package/dist/media/insert-video-timing.js +17 -0
  235. package/dist/media/json-schema.js +75 -0
  236. package/dist/media/legacy-task-types.js +129 -0
  237. package/dist/media/listing.js +24 -0
  238. package/dist/media/model-id.js +14 -0
  239. package/dist/media/preview.js +86 -0
  240. package/dist/media/prompt-dialects.js +65 -0
  241. package/dist/media/ref-fields.js +106 -0
  242. package/dist/media/refs.js +131 -0
  243. package/dist/media/request.js +188 -0
  244. package/dist/media/types.js +6 -0
  245. package/dist/media/wire.js +161 -0
  246. package/dist/media-library.js +535 -0
  247. package/dist/media-output-path.js +33 -0
  248. package/dist/multyculty-workflow.js +757 -0
  249. package/dist/notebook-action-catalog.js +608 -0
  250. package/dist/notebook-cell-outputs.js +726 -0
  251. package/dist/notebook-credit-retry.js +45 -0
  252. package/dist/notebook-fixtures.js +8 -0
  253. package/dist/notebook-generation-contract.js +77 -0
  254. package/dist/notebook-generation-controls.js +145 -0
  255. package/dist/notebook-goal-layout.js +40 -0
  256. package/dist/notebook-graph.js +37 -0
  257. package/dist/notebook-image-edit.js +84 -0
  258. package/dist/notebook-initial-generation-prompt.js +222 -0
  259. package/dist/notebook-live-analysis.js +941 -0
  260. package/dist/notebook-media-ops.js +579 -0
  261. package/dist/notebook-mutations.js +20 -0
  262. package/dist/notebook-placement.js +41 -0
  263. package/dist/notebook-provider-failure.js +87 -0
  264. package/dist/notebook-published-post.js +26 -0
  265. package/dist/notebook-reference-resolver.js +227 -0
  266. package/dist/notebook-relayout.js +270 -0
  267. package/dist/notebook-run-plan.js +519 -0
  268. package/dist/notebook-shots.js +162 -0
  269. package/dist/notebook-workflow.js +856 -0
  270. package/dist/one-password.js +200 -0
  271. package/dist/openai-intelligence.js +99 -0
  272. package/dist/original-media-file.js +12 -0
  273. package/dist/osg-assets.js +36 -0
  274. package/dist/osg-placement-cache.js +64 -0
  275. package/dist/osg-settings.js +27 -0
  276. package/dist/paid-tools.js +22 -0
  277. package/dist/platform-guidance.js +26 -0
  278. package/dist/posts/dropbox-auth.js +91 -0
  279. package/dist/posts/dropbox-upload.js +132 -0
  280. package/dist/posts/icloud-drive.js +134 -0
  281. package/dist/posts/icloud-status.js +64 -0
  282. package/dist/posts/post-contract.js +2 -0
  283. package/dist/posts/post-copy-format.js +43 -0
  284. package/dist/posts/post-copy.js +193 -0
  285. package/dist/posts/post-folder.js +18 -0
  286. package/dist/posts/post-metrics.js +119 -0
  287. package/dist/posts/post-store.js +340 -0
  288. package/dist/posts/x-post-target.js +43 -0
  289. package/dist/preview-payload.js +90 -0
  290. package/dist/prompt-surfaces.js +22 -0
  291. package/dist/provider-prompt-transform.js +77 -0
  292. package/dist/provider-status-link.js +21 -0
  293. package/dist/provider-task-record.js +78 -0
  294. package/dist/provider-task-status.js +47 -0
  295. package/dist/provider-usage.js +294 -0
  296. package/dist/queue.js +810 -0
  297. package/dist/reference-video-duration.js +17 -0
  298. package/dist/remotion/BlurFillVideo.js +51 -0
  299. package/dist/remotion/KeywordGraphicsOverlay.js +68 -0
  300. package/dist/remotion/OsgOverlay.js +30 -0
  301. package/dist/remotion/QrOutroComposition.js +47 -0
  302. package/dist/remotion/RenderComposition.js +11 -0
  303. package/dist/remotion/browser.js +59 -0
  304. package/dist/remotion/constants.js +35 -0
  305. package/dist/remotion/index.js +66 -0
  306. package/dist/remotion/keyword-graphics.js +151 -0
  307. package/dist/remotion/keyword-placement.js +182 -0
  308. package/dist/remotion/osg-spec.js +198 -0
  309. package/dist/remotion/public/qr-outro-impact.wav +0 -0
  310. package/dist/remotion/qr-outro-audio.js +1 -0
  311. package/dist/remotion/qr-outro-spec.js +211 -0
  312. package/dist/remotion/shared-bundle.js +37 -0
  313. package/dist/remotion/subtitles/AliveCaptions.js +83 -0
  314. package/dist/remotion/subtitles/Highlight.js +58 -0
  315. package/dist/remotion/subtitles/Impact.js +67 -0
  316. package/dist/remotion/subtitles/SubtitleOverlay.js +9 -0
  317. package/dist/remotion/subtitles/alive-layout.js +321 -0
  318. package/dist/remotion/subtitles/alive-types.js +17 -0
  319. package/dist/remotion/subtitles/chunker.js +68 -0
  320. package/dist/remotion/subtitles/segments.js +42 -0
  321. package/dist/remotion/subtitles/styles.js +4 -0
  322. package/dist/remotion/subtitles/types.js +1 -0
  323. package/dist/remotion/util.js +18 -0
  324. package/dist/remotion-cancellation.js +15 -0
  325. package/dist/rename-helpers.js +204 -0
  326. package/dist/rhythm/analyze.js +128 -0
  327. package/dist/rhythm/contract.js +14 -0
  328. package/dist/rhythm/draft-model.js +19 -0
  329. package/dist/rhythm/energy.js +133 -0
  330. package/dist/rhythm/fft.js +44 -0
  331. package/dist/rhythm/model.js +71 -0
  332. package/dist/rhythm/music-analysis.js +124 -0
  333. package/dist/rhythm/music-draft.js +261 -0
  334. package/dist/rhythm/onset.js +101 -0
  335. package/dist/rhythm/run-worker.js +51 -0
  336. package/dist/rhythm/score.js +47 -0
  337. package/dist/rhythm/section-labels.js +168 -0
  338. package/dist/rhythm/sequence-rhythm.js +67 -0
  339. package/dist/rhythm/synthesize.js +103 -0
  340. package/dist/rhythm/timing.js +98 -0
  341. package/dist/rhythm/track.js +320 -0
  342. package/dist/rhythm/visual-fit.js +4 -0
  343. package/dist/rhythm/worker.js +25 -0
  344. package/dist/scene-detect.js +200 -0
  345. package/dist/scene-transition.js +12 -0
  346. package/dist/scheduled-posts.js +200 -0
  347. package/dist/search-index-coverage.js +13 -0
  348. package/dist/search-index-media.js +71 -0
  349. package/dist/search-reference-store.js +60 -0
  350. package/dist/search-scoring.js +17 -0
  351. package/dist/serve.js +125 -0
  352. package/dist/server-lock.js +143 -0
  353. package/dist/server.js +42 -0
  354. package/dist/srt.js +16 -0
  355. package/dist/tag-backfill-state.js +121 -0
  356. package/dist/tag-settings.js +30 -0
  357. package/dist/tag-vocabulary.js +237 -0
  358. package/dist/test-queue-cleanup.js +1 -0
  359. package/dist/time-parse.js +50 -0
  360. package/dist/timeline-helpers.js +554 -0
  361. package/dist/timewarp.js +87 -0
  362. package/dist/tools/_image-inputs.js +9 -0
  363. package/dist/tools/_media-refs.js +84 -0
  364. package/dist/tools/_shared.js +59 -0
  365. package/dist/tools/_suggest-shared.js +279 -0
  366. package/dist/tools/add-timeline-audio.js +73 -0
  367. package/dist/tools/alive-captions.js +157 -0
  368. package/dist/tools/analyze-jokes.js +56 -0
  369. package/dist/tools/analyze-video.js +66 -0
  370. package/dist/tools/animate-keywords.js +217 -0
  371. package/dist/tools/api-status.js +42 -0
  372. package/dist/tools/application-commands.js +34 -0
  373. package/dist/tools/apply-cuts.js +112 -0
  374. package/dist/tools/apply-sfx.js +152 -0
  375. package/dist/tools/apply-watermark.js +670 -0
  376. package/dist/tools/archive-clip.js +74 -0
  377. package/dist/tools/asset-history.js +61 -0
  378. package/dist/tools/asset-manifest.js +24 -0
  379. package/dist/tools/asset-tags.js +151 -0
  380. package/dist/tools/assign-slot.js +97 -0
  381. package/dist/tools/audio-boost.js +107 -0
  382. package/dist/tools/audio-mix.js +121 -0
  383. package/dist/tools/book-usage.js +16 -0
  384. package/dist/tools/chain.js +136 -0
  385. package/dist/tools/change-video-speed.js +105 -0
  386. package/dist/tools/chat-history.js +5 -0
  387. package/dist/tools/chat.js +848 -0
  388. package/dist/tools/clean-video-audio.js +97 -0
  389. package/dist/tools/clear-failed-tasks.js +66 -0
  390. package/dist/tools/cold-open.js +114 -0
  391. package/dist/tools/command-plan.js +1680 -0
  392. package/dist/tools/commands.js +1666 -0
  393. package/dist/tools/concat-images.js +236 -0
  394. package/dist/tools/connect-service.js +55 -0
  395. package/dist/tools/copy-file-to-clipboard.js +58 -0
  396. package/dist/tools/create-character.js +114 -0
  397. package/dist/tools/create-qart.js +253 -0
  398. package/dist/tools/create-qr-outro.js +149 -0
  399. package/dist/tools/create-qrbtf.js +215 -0
  400. package/dist/tools/create-watermark.js +97 -0
  401. package/dist/tools/crop-asset.js +18 -0
  402. package/dist/tools/crop-image.js +120 -0
  403. package/dist/tools/crop-video.js +97 -0
  404. package/dist/tools/delete-asset.js +104 -0
  405. package/dist/tools/describe-image.js +69 -0
  406. package/dist/tools/detect-scenes.js +44 -0
  407. package/dist/tools/doctor.js +126 -0
  408. package/dist/tools/download-video.js +114 -0
  409. package/dist/tools/duplicate-asset.js +184 -0
  410. package/dist/tools/edit-timeline.js +59 -0
  411. package/dist/tools/editing-moments.js +105 -0
  412. package/dist/tools/estimate-cost.js +171 -0
  413. package/dist/tools/even-split.js +295 -0
  414. package/dist/tools/export-asset-file.js +22 -0
  415. package/dist/tools/export-asset.js +140 -0
  416. package/dist/tools/export-sequence.js +250 -0
  417. package/dist/tools/export-to-downloads.js +54 -0
  418. package/dist/tools/export-transcript-srt.js +79 -0
  419. package/dist/tools/extend-audio.js +100 -0
  420. package/dist/tools/extract-audio.js +174 -0
  421. package/dist/tools/extract-frame.js +108 -0
  422. package/dist/tools/extract-notebook-audio.js +173 -0
  423. package/dist/tools/extract-notebook-frame.js +160 -0
  424. package/dist/tools/extract-video-clip.js +101 -0
  425. package/dist/tools/generate-media.js +157 -0
  426. package/dist/tools/generation-payload.js +48 -0
  427. package/dist/tools/get-timeline.js +12 -0
  428. package/dist/tools/get-watermark-config.js +38 -0
  429. package/dist/tools/goal.js +644 -0
  430. package/dist/tools/image-subjects.js +711 -0
  431. package/dist/tools/index.js +323 -0
  432. package/dist/tools/inject-first-frame.js +154 -0
  433. package/dist/tools/invert-image.js +70 -0
  434. package/dist/tools/isolate-vocals.js +66 -0
  435. package/dist/tools/list-assets.js +98 -0
  436. package/dist/tools/list-cell-generations.js +225 -0
  437. package/dist/tools/list-elevenlabs-voices.js +163 -0
  438. package/dist/tools/log-wrapper.js +29 -0
  439. package/dist/tools/make-cover-song.js +95 -0
  440. package/dist/tools/mark-asset-seen.js +23 -0
  441. package/dist/tools/media-library.js +245 -0
  442. package/dist/tools/move-timeline-audio.js +35 -0
  443. package/dist/tools/music-analysis.js +60 -0
  444. package/dist/tools/music-draft.js +29 -0
  445. package/dist/tools/pad-video.js +87 -0
  446. package/dist/tools/post-record.js +83 -0
  447. package/dist/tools/post.js +168 -0
  448. package/dist/tools/prompt-history.js +164 -0
  449. package/dist/tools/provider-key-status.js +248 -0
  450. package/dist/tools/qrbtf-render.js +849 -0
  451. package/dist/tools/read-asset-metadata.js +26 -0
  452. package/dist/tools/read-file-at-commit.js +29 -0
  453. package/dist/tools/read-transcript.js +41 -0
  454. package/dist/tools/reconcile-project-work.js +1452 -0
  455. package/dist/tools/recover-asset.js +28 -0
  456. package/dist/tools/remove-sound.js +72 -0
  457. package/dist/tools/remove-timeline-audio.js +34 -0
  458. package/dist/tools/remove-timeline-slot.js +40 -0
  459. package/dist/tools/rename-all.js +434 -0
  460. package/dist/tools/rename-asset.js +34 -0
  461. package/dist/tools/render-settings.js +47 -0
  462. package/dist/tools/render-timeline.js +120 -0
  463. package/dist/tools/render.js +384 -0
  464. package/dist/tools/reorder-character-images.js +45 -0
  465. package/dist/tools/replace-video-audio.js +133 -0
  466. package/dist/tools/restore-archive-clips.js +209 -0
  467. package/dist/tools/restore-asset-version.js +37 -0
  468. package/dist/tools/retry-generation.js +54 -0
  469. package/dist/tools/reverse-video.js +74 -0
  470. package/dist/tools/rewrite-prompt.js +388 -0
  471. package/dist/tools/rewrite-script.js +67 -0
  472. package/dist/tools/schema-from-apicity.js +66 -0
  473. package/dist/tools/search-archive.js +150 -0
  474. package/dist/tools/semantic-search.js +1214 -0
  475. package/dist/tools/sequence-rhythm.js +43 -0
  476. package/dist/tools/set-character-metadata.js +84 -0
  477. package/dist/tools/set-env-secret.js +40 -0
  478. package/dist/tools/set-osg.js +143 -0
  479. package/dist/tools/show-folder.js +37 -0
  480. package/dist/tools/smooth-scene-concat.js +122 -0
  481. package/dist/tools/splice-video.js +149 -0
  482. package/dist/tools/split-video.js +202 -0
  483. package/dist/tools/suggest-cuts.js +45 -0
  484. package/dist/tools/suggest-sfx.js +43 -0
  485. package/dist/tools/sync-video-to-audio.js +115 -0
  486. package/dist/tools/tag-backfill.js +177 -0
  487. package/dist/tools/timewarp-video.js +85 -0
  488. package/dist/tools/tool-def.js +1 -0
  489. package/dist/tools/tool-json-schema.js +116 -0
  490. package/dist/tools/transcribe.js +90 -0
  491. package/dist/tools/translate-subtitles.js +59 -0
  492. package/dist/tools/trim-audio.js +139 -0
  493. package/dist/tools/trim-video.js +168 -0
  494. package/dist/tools/update-script.js +25 -0
  495. package/dist/tools/update-timeline-audio.js +40 -0
  496. package/dist/tools/upload-file.js +41 -0
  497. package/dist/tools/verify-x-mentions.js +141 -0
  498. package/dist/tools/video-editing-command-contract.js +291 -0
  499. package/dist/tools/video-source-reference.js +30 -0
  500. package/dist/tools/video-time-input.js +18 -0
  501. package/dist/tools/videobook-domain.js +2021 -0
  502. package/dist/tools/wait-for-asset-ready.js +143 -0
  503. package/dist/tools/workspace-actions.js +54 -0
  504. package/dist/transcript-projection.js +202 -0
  505. package/dist/transcript-srt.js +33 -0
  506. package/dist/upload.js +76 -0
  507. package/dist/usage-providers.js +25 -0
  508. package/dist/video-analysis-projection.js +46 -0
  509. package/dist/video-poster.js +33 -0
  510. package/dist/video-proxy.js +99 -0
  511. package/dist/vision-regions.js +111 -0
  512. package/dist/voice-actions.js +90 -0
  513. package/dist/voice-audio.js +55 -0
  514. package/dist/voice-config.js +122 -0
  515. package/dist/voice-continuation.js +54 -0
  516. package/dist/voice-contract.js +1 -0
  517. package/dist/voice-http.js +145 -0
  518. package/dist/voice-reply-progress.js +55 -0
  519. package/dist/voice-session.js +992 -0
  520. package/dist/watermark-badge.js +259 -0
  521. package/dist/watermark-config.js +111 -0
  522. package/dist/watermark-handle-position.js +55 -0
  523. package/dist/watermark-platform.js +15 -0
  524. package/dist/watermark-timing.js +16 -0
  525. package/dist/workspace-action-catalog.js +315 -0
  526. package/dist/workspace-action-contract.js +21 -0
  527. package/dist/workspace-action-groups.js +98 -0
  528. package/dist/workspace-action-surfaces.js +7 -0
  529. package/dist/x/account.js +88 -0
  530. package/dist/x/authenticated-handle.js +30 -0
  531. package/dist/x/oauth-flow.js +191 -0
  532. package/dist/x/post-contract.js +1 -0
  533. package/dist/x/post-metadata.js +44 -0
  534. package/dist/x/post-to-x.js +456 -0
  535. package/dist/x/published-post-cell.js +90 -0
  536. package/dist/x/x-tokens.js +69 -0
  537. package/dist/ytdlp-binary.js +65 -0
  538. package/dist/zod-slots.js +334 -0
  539. package/package.json +84 -4
  540. package/ui/assets/alive-captions-BWb5nLKj.css +1 -0
  541. package/ui/assets/alive-captions-DPEr1nKM.js +1 -0
  542. package/ui/assets/confirm-bodies-D8ouHXKy.js +1 -0
  543. package/ui/assets/confirm-bodies-DrMhaXC6.css +1 -0
  544. package/ui/assets/fullscreen-B7nw4YbE.js +1 -0
  545. package/ui/assets/goal-ui-DK-xTCK0.js +2 -0
  546. package/ui/assets/goal-ui-DXdUM2KF.css +1 -0
  547. package/ui/assets/index-DzPAnCUj.css +1 -0
  548. package/ui/assets/index-kS1905s5.js +37 -0
  549. package/ui/assets/inspector-MlzQbTVo.js +1 -0
  550. package/ui/assets/jobs-ui-CoinOWx0.js +1 -0
  551. package/ui/assets/music-video-Cbe80kmQ.js +1 -0
  552. package/ui/assets/music-video-DPaiKKEq.css +1 -0
  553. package/ui/assets/ui-Oirr9VOf.css +1 -0
  554. package/ui/assets/ui-xo_Y1yQg.js +2 -0
  555. package/ui/assets/vendor-D2rfiZ5j.css +1 -0
  556. package/ui/assets/vendor-DfTCWgKm.js +19 -0
  557. package/ui/assets/vendor-flow-BXbeWxW7.js +7 -0
  558. package/ui/assets/vendor-flow-BnuhLJ6X.css +1 -0
  559. package/ui/assets/vendor-icons-CGqhCIXV.js +1 -0
  560. package/ui/assets/vendor-mcp-BTlEJcHV.js +67 -0
  561. package/ui/assets/vendor-react-Dj7D1fD4.js +9 -0
  562. package/ui/assets/vendor-remotion-CH1HXrlc.js +95 -0
  563. package/ui/assets/videobook-Qlp9HQFu.js +20 -0
  564. package/ui/favicon.svg +8 -0
  565. package/ui/index.html +126 -0
@@ -0,0 +1,1214 @@
1
+ import { notebookOccupiedSlots } from "videobook-engine/notebook-grid";
2
+ import { firstEmptyNotebookGridSlot, findAudioFile, findPrimaryMediaFile, findVideoFile, isNotebookGridSlot, MVP_CONTRACT_VERSION, NOTEBOOK_GRID_ROW_COUNT, NOTEBOOK_GRID_COLUMN_COUNT, sourceTicksToSequenceFrames, } from "videobook-engine";
3
+ import { v7 as uuidv7 } from "uuid";
4
+ import { z } from "zod";
5
+ import { mutateNotebook } from "../notebook-mutations.js";
6
+ import { registerLocalClapSearchProvider, registerLocalClipSearchProvider, } from "../local-search-models.js";
7
+ import { FFMPEG } from "../ffmpeg.js";
8
+ import { queue } from "../queue.js";
9
+ import { enqueueTemporalSearchPreparation } from "../jobs/prepare-temporal-search.js";
10
+ import { PLAIN_TRANSCRIPT_FILE } from "../transcript-projection.js";
11
+ import { comparableHitScore } from "../search-scoring.js";
12
+ import { searchReferenceStore } from "../search-reference-store.js";
13
+ import { extname, join } from "node:path";
14
+ import { advertisedAs } from "./tool-json-schema.js";
15
+ import { buildAssetList } from "./reconcile-project-work.js";
16
+ import { videoProxyMetadataMatches, } from "../video-proxy.js";
17
+ const bookSchema = { book_id: z.string().uuid() };
18
+ const rationalSchema = z.object({
19
+ numerator: z.number().int().positive(),
20
+ denominator: z.number().int().positive(),
21
+ });
22
+ const sourceRangeSchema = z.object({
23
+ streamId: z.string().min(1),
24
+ objectHash: z.string().min(1),
25
+ startTick: z.number().int().nonnegative(),
26
+ durationTicks: z.number().int().positive(),
27
+ timeBase: rationalSchema,
28
+ });
29
+ const sourcePointSchema = z.object({
30
+ streamId: z.string().min(1),
31
+ objectHash: z.string().min(1),
32
+ tick: z.number().int().nonnegative(),
33
+ timeBase: rationalSchema,
34
+ });
35
+ const searchReferenceSchema = z.discriminatedUnion("kind", [
36
+ z.object({ kind: z.literal("image"), artifact: z.string().min(1) }),
37
+ z.object({ kind: z.literal("frame"), source: sourcePointSchema }),
38
+ z.object({ kind: z.literal("video"), range: sourceRangeSchema }),
39
+ z.object({ kind: z.literal("audio"), range: sourceRangeSchema }),
40
+ ]);
41
+ const searchLocationSchema = z.discriminatedUnion("kind", [
42
+ z.object({
43
+ kind: z.literal("still"),
44
+ artifactId: z.string().uuid(),
45
+ sourcePath: z.string().min(1),
46
+ objectHash: z.string().min(1),
47
+ }),
48
+ z.object({
49
+ kind: z.literal("timed"),
50
+ artifactId: z.string().uuid(),
51
+ range: sourceRangeSchema,
52
+ }),
53
+ z.object({
54
+ kind: z.literal("document"),
55
+ artifactId: z.string().uuid(),
56
+ sourcePath: z.string().min(1),
57
+ objectHash: z.string().min(1),
58
+ startUtf8Byte: z.number().int().nonnegative(),
59
+ endUtf8Byte: z.number().int().positive(),
60
+ }),
61
+ ]);
62
+ const searchSignalSchema = z.object({
63
+ kind: z.enum(["visual", "speech", "ocr", "audio", "metadata", "exact", "near"]),
64
+ rank: z.number().int().positive(),
65
+ score: z.number().optional(),
66
+ explanation: z.string().optional(),
67
+ });
68
+ const searchQuerySchema = z.object({
69
+ text: z.string().optional(),
70
+ reference: searchReferenceSchema.optional(),
71
+ modalities: z.array(z.enum([
72
+ "auto",
73
+ "visual",
74
+ "speech",
75
+ "ocr",
76
+ "audio",
77
+ "metadata",
78
+ ])).optional(),
79
+ artifactKinds: z.array(z.enum([
80
+ "video",
81
+ "image",
82
+ "audio",
83
+ "script",
84
+ "character",
85
+ "prompt",
86
+ "scene",
87
+ "final",
88
+ ])).optional(),
89
+ durationMs: z.object({
90
+ min: z.number().nonnegative().optional(),
91
+ max: z.number().nonnegative().optional(),
92
+ }).optional(),
93
+ orientations: z.array(z.enum(["landscape", "portrait", "square"])).optional(),
94
+ labels: z.array(z.string().min(1)).optional(),
95
+ sourceArtifactIds: z.array(z.string().uuid()).optional(),
96
+ indexingStates: z.array(z.enum([
97
+ "not-indexed",
98
+ "partial",
99
+ "ready",
100
+ "stale",
101
+ "failed",
102
+ "unsupported",
103
+ ])).optional(),
104
+ createdAfter: z.number().int().nonnegative().optional(),
105
+ createdBefore: z.number().int().nonnegative().optional(),
106
+ minScore: z.number().min(0).max(1).optional(),
107
+ limit: z.number().int().positive().max(100).optional(),
108
+ cursor: z.string().min(1).optional(),
109
+ });
110
+ const preparedReferenceFields = {
111
+ reference_id: z.string().uuid().optional(),
112
+ reference_range: z.object({
113
+ start_seconds: z.number().nonnegative(),
114
+ duration_seconds: z.number().positive().optional(),
115
+ }).optional(),
116
+ };
117
+ const searchHitSchema = advertisedAs(z.object({
118
+ artifactId: z.string().uuid(),
119
+ artifactLabel: z.string().min(1).optional(),
120
+ artifactKind: z.enum([
121
+ "video",
122
+ "image",
123
+ "audio",
124
+ "script",
125
+ "character",
126
+ "prompt",
127
+ "scene",
128
+ "final",
129
+ ]),
130
+ location: searchLocationSchema,
131
+ representativeTick: z.number().int().nonnegative().optional(),
132
+ score: z.number(),
133
+ signals: z.array(searchSignalSchema),
134
+ excerpt: z.string().optional(),
135
+ indexManifestIds: z.array(z.string().min(1)),
136
+ }), {
137
+ type: "object",
138
+ description: "One hit copied unchanged from a search_moments result",
139
+ });
140
+ const roughCutBeatSchema = z.object({
141
+ beat_id: z.string().min(1),
142
+ text: z.string().min(1),
143
+ timeline_start_frame: z.number().int().nonnegative(),
144
+ duration_frames: z.number().int().positive(),
145
+ });
146
+ const indexManifestSchema = z.object({
147
+ manifestId: z.string().min(1),
148
+ provider: z.string().min(1),
149
+ modelId: z.string().min(1),
150
+ modelRevision: z.string().min(1),
151
+ license: z.string().min(1).optional(),
152
+ embeddingSpace: z.string().min(1),
153
+ dimensions: z.number().int().positive(),
154
+ modalities: z.array(z.enum([
155
+ "visual",
156
+ "speech",
157
+ "ocr",
158
+ "audio",
159
+ "metadata",
160
+ ])).min(1),
161
+ supportedLanguages: z.array(z.string().min(1)),
162
+ preprocessingVersion: z.string().min(1),
163
+ extractorVersion: z.string().min(1),
164
+ createdAt: z.number().int().nonnegative(),
165
+ });
166
+ function json(value) {
167
+ return { content: [{ type: "text", text: JSON.stringify(value) }] };
168
+ }
169
+ function failure(message) {
170
+ return { isError: true, content: [{ type: "text", text: message }] };
171
+ }
172
+ function ingestReadiness(kind, phases, hasAudio) {
173
+ const required = kind === "image"
174
+ ? ["source", "proxy", "visual", "ocr"]
175
+ : kind === "audio"
176
+ ? ["source", "probe", "waveform", "transcript", "audio"]
177
+ : [
178
+ "source",
179
+ "probe",
180
+ "proxy",
181
+ ...(hasAudio ? ["waveform", "transcript", "audio"] : []),
182
+ "visual",
183
+ "ocr",
184
+ ];
185
+ const failed = required.filter((name) => phases[name] === "failed");
186
+ const missingOutputs = required.filter((name) => phases[name] !== "ready" && phases[name] !== "not-applicable");
187
+ return {
188
+ state: failed.length > 0
189
+ ? "failed"
190
+ : missingOutputs.length === 0 ? "ready" : "partial",
191
+ missingOutputs,
192
+ };
193
+ }
194
+ function isDotfilePath(name) {
195
+ return name.split("/").some((segment) => segment.startsWith("."));
196
+ }
197
+ export function semanticSearchDefs(engine, books) {
198
+ return [
199
+ {
200
+ name: "list_ingest_status",
201
+ description: "List independent ingest and search-index phase states",
202
+ scope: "book",
203
+ schema: {
204
+ ...bookSchema,
205
+ limit: z.number().int().positive().max(500).optional(),
206
+ },
207
+ handler: async (args) => engine.withLocalMedia(async () => {
208
+ const limit = Number(args.limit) || 200;
209
+ const artifacts = engine.artifacts.list().slice(-limit).reverse();
210
+ const statuses = await Promise.all(artifacts.map(async (artifact) => {
211
+ const [manifest, streams, waveform, transcripts, coverage, proxyMetadata] = await Promise.all([
212
+ engine.files.manifest(artifact.artifactId, { includeDotfiles: true }),
213
+ Promise.resolve(engine.streams.list(artifact.artifactId)),
214
+ engine.metadata.waveforms.exists(artifact.artifactId),
215
+ Promise.resolve(engine.transcripts.list(artifact.artifactId)),
216
+ Promise.resolve(engine.temporalSearch.coverage(artifact.artifactId)),
217
+ engine.metadata.artifacts.read(artifact.artifactId, "proxy"),
218
+ ]);
219
+ const allFiles = manifest.ok ? manifest.value.files : [];
220
+ // The legacy transcript is a dotfile beside the media, so the
221
+ // manifest already answers whether it exists; no object read needed.
222
+ const legacyTranscript = allFiles.some((file) => file.name === PLAIN_TRANSCRIPT_FILE);
223
+ const files = allFiles.filter((file) => !isDotfilePath(file.name));
224
+ const sourceFile = artifact.kind === "video"
225
+ ? findVideoFile(files.filter((file) => file.name !== "proxy.mp4"))
226
+ : findPrimaryMediaFile(files, artifact.kind);
227
+ const proxyFile = files.find((file) => file.name === "proxy.mp4");
228
+ const hasValidVideoProxy = sourceFile !== null
229
+ && proxyFile !== undefined
230
+ && proxyMetadata.ok
231
+ && videoProxyMetadataMatches(proxyMetadata.value, sourceFile, proxyFile);
232
+ const modalities = coverage.ok ? coverage.value.modalities : [];
233
+ const phase = (name) => modalities.find((item) => item.modality === name)?.state ?? "not-indexed";
234
+ const hasAudio = streams.ok && streams.value.some((stream) => stream.kind === "audio");
235
+ const phases = {
236
+ source: files.length > 0 ? "ready" : "failed",
237
+ probe: streams.ok && streams.value.length > 0
238
+ ? "ready"
239
+ : artifact.kind === "image" ? "not-applicable" : "not-indexed",
240
+ proxy: (artifact.kind === "video"
241
+ ? hasValidVideoProxy
242
+ : files.some((file) => /^original\.(?:jpe?g|png|webp|gif|svg|mp3|wav|m4a|weba|ogg|aac|flac)$/i
243
+ .test(file.name)))
244
+ ? "ready"
245
+ : "not-indexed",
246
+ waveform: waveform.ok && waveform.value
247
+ ? "ready"
248
+ : artifact.kind === "image" || !hasAudio ? "not-applicable" : "not-indexed",
249
+ transcript: transcripts.ok && transcripts.value.length > 0
250
+ || legacyTranscript
251
+ ? "ready"
252
+ : artifact.kind === "image" || !hasAudio ? "not-applicable" : "not-indexed",
253
+ visual: phase("visual"),
254
+ audio: artifact.kind === "image" || !hasAudio ? "not-applicable" : phase("audio"),
255
+ ocr: phase("ocr"),
256
+ };
257
+ const readiness = ingestReadiness(artifact.kind, phases, hasAudio);
258
+ return {
259
+ artifactId: artifact.artifactId,
260
+ ...(artifact.label ? { label: artifact.label } : {}),
261
+ kind: artifact.kind,
262
+ state: readiness.state,
263
+ missingOutputs: readiness.missingOutputs,
264
+ phases,
265
+ ...(coverage.ok ? { coverage: coverage.value } : {}),
266
+ };
267
+ }));
268
+ return json(statuses);
269
+ }),
270
+ },
271
+ {
272
+ name: "retry_ingest",
273
+ description: "Retry derivation jobs without uploading source bytes again",
274
+ scope: "book",
275
+ schema: { ...bookSchema, artifact_id: z.string().uuid() },
276
+ handler: async (args) => {
277
+ const artifact = engine.artifacts.get(String(args.artifact_id));
278
+ if (!artifact.ok)
279
+ return failure(artifact.error.message);
280
+ const manifest = await engine.withLocalMedia(() => engine.files.manifest(artifact.value.artifactId));
281
+ if (!manifest.ok)
282
+ return failure(manifest.error.message);
283
+ const source = artifact.value.kind === "video"
284
+ ? findVideoFile(manifest.value.files)
285
+ : artifact.value.kind === "audio"
286
+ ? findAudioFile(manifest.value.files, artifact.value.kind)
287
+ : manifest.value.files.find((file) => /^original\.(?:jpe?g|png|webp|gif|svg)$/i.test(file.name))
288
+ ?? manifest.value.files.find((file) => /^original\.(?:heic|heif)$/i.test(file.name));
289
+ if (!source)
290
+ return failure("No source file is available for retry");
291
+ const activeTask = await engine.jobs.pending.read(artifact.value.artifactId);
292
+ if (!activeTask.ok)
293
+ return failure(activeTask.error.message);
294
+ const work = engine.jobs.artifactWork.read(artifact.value.artifactId);
295
+ if (!work.ok)
296
+ return failure(work.error.message);
297
+ if (activeTask.value || work.value?.status === "pending" || work.value?.status === "working") {
298
+ return failure("This asset already has work in progress");
299
+ }
300
+ const cleared = await engine.jobs.failures.clear(artifact.value.artifactId);
301
+ if (!cleared.ok)
302
+ return failure(cleared.error.message);
303
+ const jobId = `retry-ingest-${artifact.value.artifactId}-${Date.now()}`;
304
+ const common = {
305
+ assetId: artifact.value.artifactId,
306
+ assetDir: artifact.value.path,
307
+ bookId: engine.book.get().bookId,
308
+ provenance: { origin: "retry-ingest" },
309
+ };
310
+ const payload = artifact.value.kind === "video"
311
+ ? {
312
+ type: "process_video",
313
+ videoPath: join(artifact.value.path, source.name),
314
+ force: true,
315
+ preserveAudioArtifacts: true,
316
+ ...common,
317
+ }
318
+ : artifact.value.kind === "audio"
319
+ ? {
320
+ type: "process_audio",
321
+ audioPath: join(artifact.value.path, source.name),
322
+ sourceFilename: source.name,
323
+ ...common,
324
+ }
325
+ : {
326
+ type: "process_image",
327
+ extension: extname(source.name).toLowerCase(),
328
+ ...common,
329
+ };
330
+ const queued = await queue.enqueue(jobId, payload);
331
+ return json({
332
+ jobId: queued.id,
333
+ operationId: queued.operationId,
334
+ requestId: jobId,
335
+ artifactId: artifact.value.artifactId,
336
+ });
337
+ },
338
+ },
339
+ {
340
+ name: "search_moments",
341
+ description: "Search indexed moments with text, media references and filters in this book, or in every book with scope library",
342
+ scope: "book",
343
+ schema: {
344
+ ...bookSchema,
345
+ scope: z.enum(["book", "library"]).optional(),
346
+ query: searchQuerySchema,
347
+ ...preparedReferenceFields,
348
+ },
349
+ handler: async (args) => {
350
+ if (args.scope === "library") {
351
+ return books ? searchLibraryMoments(books, args) : failure("Library search is unavailable");
352
+ }
353
+ registerLocalClipSearchProvider(engine);
354
+ registerLocalClapSearchProvider(engine, FFMPEG);
355
+ const query = args.query;
356
+ const referenceId = typeof args.reference_id === "string"
357
+ ? args.reference_id
358
+ : undefined;
359
+ const result = referenceId
360
+ ? await engine.temporalSearch.queryPrepared(query, searchReferenceStore.get(referenceId).reference, preparedSearchOptions(args.reference_range))
361
+ : await engine.temporalSearch.query(query);
362
+ if (!result.ok) {
363
+ if (result.error.code !== "NOT_READY" || !result.error.details?.requiresIndexPreparation) {
364
+ return failure(result.error.message);
365
+ }
366
+ return json({
367
+ hits: [],
368
+ coverage: { state: "partial", partialResults: true, indexedArtifactCount: 0, totalArtifactCount: 0 },
369
+ preparationJobs: [await enqueueTemporalSearchPreparation(String(args.book_id))],
370
+ });
371
+ }
372
+ return json({
373
+ ...result.value,
374
+ hits: result.value.hits.map((hit) => ({
375
+ ...hit,
376
+ score: comparableHitScore(hit),
377
+ })),
378
+ });
379
+ },
380
+ },
381
+ {
382
+ name: "suggest_sequence_coverage",
383
+ description: "Rank existing visual moments for a sequence range before offering generation",
384
+ scope: "book",
385
+ schema: {
386
+ ...bookSchema,
387
+ text: z.string().min(1),
388
+ timeline_start_frame: z.number().int().nonnegative(),
389
+ duration_frames: z.number().int().positive(),
390
+ exclude_artifact_ids: z.array(z.string().uuid()).optional(),
391
+ limit: z.number().int().positive().max(20).optional(),
392
+ },
393
+ handler: async (args) => {
394
+ registerLocalClipSearchProvider(engine);
395
+ const excluded = new Set(Array.isArray(args.exclude_artifact_ids)
396
+ ? args.exclude_artifact_ids.map(String)
397
+ : []);
398
+ const result = await engine.temporalSearch.query({
399
+ text: String(args.text),
400
+ modalities: ["visual", "metadata"],
401
+ artifactKinds: ["video", "image"],
402
+ limit: Math.min(100, (Number(args.limit) || 5) + excluded.size),
403
+ });
404
+ if (!result.ok)
405
+ return failure(result.error.message);
406
+ const hits = result.value.hits
407
+ .filter((hit) => !excluded.has(hit.artifactId))
408
+ .slice(0, Number(args.limit) || 5);
409
+ return json({
410
+ kind: "coverage-suggestions",
411
+ existingFirst: true,
412
+ query: { text: String(args.text) },
413
+ destination: {
414
+ sequenceId: engine.sequences.getPrimary().sequenceId,
415
+ timelineStartFrame: Number(args.timeline_start_frame),
416
+ durationFrames: Number(args.duration_frames),
417
+ },
418
+ hits,
419
+ coverage: result.value.coverage,
420
+ generationFallback: hits.length === 0
421
+ ? {
422
+ offered: true,
423
+ reason: "No indexed existing moment met the coverage request",
424
+ }
425
+ : { offered: false },
426
+ });
427
+ },
428
+ },
429
+ {
430
+ name: "plan_notebook_rough_cut",
431
+ description: "Map narration beats to non-repeating indexed visuals as a reviewable CommandPlan",
432
+ scope: "book",
433
+ schema: {
434
+ ...bookSchema,
435
+ notebook_id: z.string().uuid(),
436
+ source_surface: z.enum(["ui", "slash", "chat"]),
437
+ actor: z.string().min(1),
438
+ beats: z.array(roughCutBeatSchema).min(1).max(20),
439
+ track_id: z.string().uuid().optional(),
440
+ min_shot_frames: z.number().int().positive().optional(),
441
+ max_shot_frames: z.number().int().positive().optional(),
442
+ max_repeats_per_artifact: z.number().int().positive().max(3).optional(),
443
+ },
444
+ handler: async (args) => {
445
+ const notebook = engine.notebooks.read(String(args.notebook_id));
446
+ if (!notebook.ok)
447
+ return failure(notebook.error.message);
448
+ const sequence = engine.sequences.getPrimary();
449
+ const requestedTrackId = typeof args.track_id === "string"
450
+ ? args.track_id
451
+ : undefined;
452
+ const videoTracks = sequence.tracks
453
+ .filter((track) => track.kind === "video" && track.enabled && !track.locked)
454
+ .sort((left, right) => left.ordinal - right.ordinal);
455
+ const track = requestedTrackId
456
+ ? videoTracks.find((candidate) => candidate.trackId === requestedTrackId)
457
+ : videoTracks[1] ?? videoTracks[0];
458
+ if (!track)
459
+ return failure("No editable video track is available");
460
+ const minShotFrames = Number(args.min_shot_frames) || 1;
461
+ const maxShotFrames = Number(args.max_shot_frames) || 120;
462
+ if (maxShotFrames < minShotFrames) {
463
+ return failure("Maximum shot duration must be at least the minimum");
464
+ }
465
+ const maxRepeats = Number(args.max_repeats_per_artifact) || 1;
466
+ const beats = args.beats;
467
+ const usage = new Map();
468
+ const selected = [];
469
+ const uncovered = [];
470
+ registerLocalClipSearchProvider(engine);
471
+ for (const beat of beats) {
472
+ const search = await engine.temporalSearch.query({
473
+ text: beat.text,
474
+ modalities: ["visual", "metadata"],
475
+ artifactKinds: ["video", "image"],
476
+ limit: 20,
477
+ });
478
+ if (!search.ok)
479
+ return failure(search.error.message);
480
+ const hit = search.value.hits.find((candidate) => (usage.get(candidate.artifactId) ?? 0) < maxRepeats);
481
+ if (!hit) {
482
+ uncovered.push({
483
+ beatId: beat.beat_id,
484
+ text: beat.text,
485
+ reason: "No unused indexed visual moment is available",
486
+ });
487
+ continue;
488
+ }
489
+ usage.set(hit.artifactId, (usage.get(hit.artifactId) ?? 0) + 1);
490
+ const durationFrames = Math.max(minShotFrames, Math.min(maxShotFrames, beat.duration_frames));
491
+ const sourceDurationFrames = hit.location.kind === "timed"
492
+ ? hitDurationFrames(hit, sequence.frameRate, durationFrames)
493
+ : durationFrames;
494
+ selected.push({
495
+ beat,
496
+ hit,
497
+ operation: {
498
+ kind: "insert-clip",
499
+ mode: "overwrite",
500
+ placement: {
501
+ trackId: track.trackId,
502
+ timelineStartFrame: beat.timeline_start_frame,
503
+ durationFrames,
504
+ source: hit.location.kind === "timed"
505
+ ? {
506
+ kind: "timed",
507
+ artifactId: hit.artifactId,
508
+ range: hit.location.range,
509
+ }
510
+ : {
511
+ kind: "still",
512
+ artifactId: hit.artifactId,
513
+ sourcePath: hit.location.sourcePath,
514
+ objectHash: hit.location.objectHash,
515
+ },
516
+ ...(hit.location.kind === "timed"
517
+ ? {
518
+ speed: {
519
+ numerator: sourceDurationFrames,
520
+ denominator: durationFrames,
521
+ },
522
+ reverse: false,
523
+ audioPolicy: "mute",
524
+ }
525
+ : {}),
526
+ },
527
+ },
528
+ });
529
+ }
530
+ if (selected.length === 0) {
531
+ return json({
532
+ kind: "rough-cut-uncovered",
533
+ existingFirst: true,
534
+ uncoveredBeats: uncovered,
535
+ generationFallback: {
536
+ offered: true,
537
+ reason: "No indexed existing moments can cover these beats",
538
+ },
539
+ });
540
+ }
541
+ const planId = uuidv7();
542
+ const intent = {
543
+ intentVersion: MVP_CONTRACT_VERSION,
544
+ commandId: planId,
545
+ sequenceId: sequence.sequenceId,
546
+ baseRevision: engine.head,
547
+ actor: String(args.actor),
548
+ sourceSurface: args.source_surface,
549
+ confirmationPolicy: "always",
550
+ operations: selected.map((item) => item.operation),
551
+ };
552
+ return json({
553
+ planVersion: 1,
554
+ planId,
555
+ sourceSurface: args.source_surface,
556
+ actor: String(args.actor),
557
+ bookId: engine.book.get().bookId,
558
+ summary: `Cover ${selected.length} narration beats with existing media`,
559
+ normalizedReferences: [{
560
+ kind: "notebook",
561
+ targetId: notebook.value.id,
562
+ revision: engine.head,
563
+ }, {
564
+ kind: "sequence",
565
+ targetId: sequence.sequenceId,
566
+ revision: engine.head,
567
+ }],
568
+ suggestions: selected.map((item) => ({
569
+ suggestionId: item.beat.beat_id,
570
+ label: item.beat.text,
571
+ beatId: item.beat.beat_id,
572
+ query: item.beat.text,
573
+ destination: {
574
+ timelineStartFrame: item.operation.placement.timelineStartFrame,
575
+ durationFrames: item.operation.placement.durationFrames,
576
+ },
577
+ hit: item.hit,
578
+ included: true,
579
+ operation: item.operation,
580
+ })),
581
+ uncoveredBeats: uncovered,
582
+ generationFallback: {
583
+ offered: uncovered.length > 0,
584
+ reason: uncovered.length > 0
585
+ ? "Some beats have no unused indexed visual coverage"
586
+ : undefined,
587
+ },
588
+ stages: [{
589
+ stageId: `${planId}:edit:0`,
590
+ kind: "edit",
591
+ summary: `Overwrite ${selected.length} coverage ranges`,
592
+ intent,
593
+ }],
594
+ confirmation: {
595
+ required: true,
596
+ policy: "always",
597
+ reason: "Review every selected source moment before applying the rough cut",
598
+ },
599
+ });
600
+ },
601
+ },
602
+ {
603
+ name: "plan_sequence_sound_effects",
604
+ description: "Suggest existing indexed audio moments for timed story beats as a selectable CommandPlan",
605
+ scope: "book",
606
+ schema: {
607
+ ...bookSchema,
608
+ source_surface: z.enum(["ui", "slash", "chat"]),
609
+ actor: z.string().min(1),
610
+ moments: z.array(roughCutBeatSchema).min(1).max(20),
611
+ track_id: z.string().uuid().optional(),
612
+ max_repeats_per_artifact: z.number().int().positive().max(3).optional(),
613
+ },
614
+ handler: async (args) => {
615
+ const sequence = engine.sequences.getPrimary();
616
+ const requestedTrackId = typeof args.track_id === "string"
617
+ ? args.track_id
618
+ : undefined;
619
+ const audioTracks = sequence.tracks
620
+ .filter((track) => track.kind === "audio" && track.enabled && !track.locked)
621
+ .sort((left, right) => left.ordinal - right.ordinal);
622
+ const track = requestedTrackId
623
+ ? audioTracks.find((candidate) => candidate.trackId === requestedTrackId)
624
+ : audioTracks[1] ?? audioTracks[0];
625
+ if (!track)
626
+ return failure("No editable audio track is available");
627
+ const maxRepeats = Number(args.max_repeats_per_artifact) || 1;
628
+ const usage = new Map();
629
+ const selected = [];
630
+ const uncovered = [];
631
+ registerLocalClapSearchProvider(engine, FFMPEG);
632
+ for (const moment of args.moments) {
633
+ const search = await engine.temporalSearch.query({
634
+ text: moment.text,
635
+ modalities: ["audio", "metadata"],
636
+ artifactKinds: ["audio"],
637
+ limit: 20,
638
+ });
639
+ if (!search.ok)
640
+ return failure(search.error.message);
641
+ const hit = search.value.hits.find((candidate) => candidate.location.kind === "timed"
642
+ && (usage.get(candidate.artifactId) ?? 0) < maxRepeats);
643
+ if (!hit || hit.location.kind !== "timed") {
644
+ uncovered.push({
645
+ beatId: moment.beat_id,
646
+ text: moment.text,
647
+ reason: "No unused indexed sound moment is available",
648
+ });
649
+ continue;
650
+ }
651
+ usage.set(hit.artifactId, (usage.get(hit.artifactId) ?? 0) + 1);
652
+ const durationFrames = Math.max(1, Math.min(moment.duration_frames, hitDurationFrames(hit, sequence.frameRate, moment.duration_frames)));
653
+ const operation = {
654
+ kind: "insert-clip",
655
+ mode: "overwrite",
656
+ placement: {
657
+ trackId: track.trackId,
658
+ timelineStartFrame: moment.timeline_start_frame,
659
+ durationFrames,
660
+ source: {
661
+ kind: "timed",
662
+ artifactId: hit.artifactId,
663
+ range: hit.location.range,
664
+ },
665
+ speed: { numerator: 1, denominator: 1 },
666
+ reverse: false,
667
+ audioPolicy: "preserve-pitch",
668
+ audio: {
669
+ gainDb: -6,
670
+ muted: false,
671
+ fadeInFrames: Math.min(3, durationFrames - 1),
672
+ fadeOutFrames: Math.min(3, durationFrames - 1),
673
+ },
674
+ },
675
+ };
676
+ selected.push({ moment, hit, operation });
677
+ }
678
+ if (selected.length === 0) {
679
+ return json({
680
+ kind: "sound-effects-uncovered",
681
+ existingFirst: true,
682
+ uncoveredBeats: uncovered,
683
+ generationFallback: {
684
+ offered: true,
685
+ reason: "No indexed existing sound can cover these beats",
686
+ },
687
+ });
688
+ }
689
+ const planId = uuidv7();
690
+ const actor = String(args.actor);
691
+ const sourceSurface = args.source_surface;
692
+ const intent = {
693
+ intentVersion: MVP_CONTRACT_VERSION,
694
+ commandId: planId,
695
+ sequenceId: sequence.sequenceId,
696
+ baseRevision: engine.head,
697
+ actor,
698
+ sourceSurface,
699
+ confirmationPolicy: "always",
700
+ operations: selected.map((item) => item.operation),
701
+ };
702
+ return json({
703
+ planVersion: 1,
704
+ planId,
705
+ sourceSurface,
706
+ actor,
707
+ bookId: engine.book.get().bookId,
708
+ summary: `Review ${selected.length} existing sound-effect suggestions`,
709
+ normalizedReferences: [{
710
+ kind: "sequence",
711
+ targetId: sequence.sequenceId,
712
+ revision: engine.head,
713
+ }],
714
+ suggestions: selected.map((item) => ({
715
+ suggestionId: item.moment.beat_id,
716
+ label: item.moment.text,
717
+ detail: item.hit.artifactLabel ?? item.hit.artifactId,
718
+ category: "sound-effect",
719
+ included: true,
720
+ hit: item.hit,
721
+ operation: item.operation,
722
+ })),
723
+ uncoveredBeats: uncovered,
724
+ generationFallback: {
725
+ offered: uncovered.length > 0,
726
+ reason: uncovered.length > 0
727
+ ? "Some beats have no unused indexed sound coverage"
728
+ : undefined,
729
+ },
730
+ stages: [{
731
+ stageId: `${planId}:edit:0`,
732
+ kind: "edit",
733
+ summary: `Overwrite ${selected.length} sound-effect ranges`,
734
+ intent,
735
+ }],
736
+ confirmation: {
737
+ required: true,
738
+ policy: "always",
739
+ reason: "Review each sound and mix placement before applying",
740
+ },
741
+ });
742
+ },
743
+ },
744
+ {
745
+ name: "get_search_coverage",
746
+ description: "Read progressive semantic-index coverage for a book or artifact",
747
+ scope: "book",
748
+ schema: { ...bookSchema, artifact_id: z.string().uuid().optional() },
749
+ handler: async (args) => {
750
+ const artifact = typeof args.artifact_id === "string"
751
+ ? args.artifact_id
752
+ : undefined;
753
+ const result = engine.temporalSearch.coverage(artifact);
754
+ return result.ok ? json(result.value) : failure(result.error.message);
755
+ },
756
+ },
757
+ {
758
+ name: "get_search_index_status",
759
+ description: "Read temporal search manifests, providers, and index statistics",
760
+ scope: "book",
761
+ schema: bookSchema,
762
+ handler: async () => json({
763
+ manifests: engine.temporalSearch.manifests.list(),
764
+ providers: engine.temporalSearch.providers.list(),
765
+ stats: engine.temporalSearch.stats(),
766
+ }),
767
+ },
768
+ {
769
+ name: "list_media_streams",
770
+ description: "List typed media streams for a source artifact",
771
+ scope: "book",
772
+ schema: { ...bookSchema, artifact_id: z.string().uuid() },
773
+ handler: async (args) => {
774
+ const result = engine.streams.list(String(args.artifact_id));
775
+ return result.ok ? json(result.value) : failure(result.error.message);
776
+ },
777
+ },
778
+ {
779
+ name: "register_search_manifest",
780
+ description: "Register an immutable semantic-index model manifest",
781
+ scope: "book",
782
+ schema: { ...bookSchema, manifest: indexManifestSchema },
783
+ handler: async (args) => {
784
+ const result = engine.temporalSearch.manifests.register(args.manifest);
785
+ return result.ok ? json(result.value) : failure(result.error.message);
786
+ },
787
+ },
788
+ {
789
+ name: "pin_search_moment",
790
+ description: "Pin a revision-stable search moment into a notebook media selection cell",
791
+ scope: "book",
792
+ schema: {
793
+ ...bookSchema,
794
+ notebook_id: z.string().uuid(),
795
+ cell_id: z.string().uuid().optional(),
796
+ cell_label: z.string().min(1).optional()
797
+ .describe("Optional free-text display label for a newly created cell"),
798
+ slot: z.object({
799
+ row: z.number().int().min(0).max(NOTEBOOK_GRID_ROW_COUNT - 1),
800
+ column: z.number().int().min(0).max(NOTEBOOK_GRID_COLUMN_COUNT - 1),
801
+ }).optional(),
802
+ query: advertisedAs(searchQuerySchema.describe("search_moments query"), {
803
+ type: "object",
804
+ description: "The search_moments query that returned hit, copied unchanged",
805
+ }),
806
+ hit: searchHitSchema,
807
+ },
808
+ handler: async (args) => {
809
+ const hit = args.hit;
810
+ const query = args.query;
811
+ const cellId = typeof args.cell_id === "string"
812
+ ? args.cell_id
813
+ : uuidv7();
814
+ const pinnedResult = {
815
+ id: uuidv7(),
816
+ artifactId: hit.artifactId,
817
+ objectHash: objectHashForHit(hit),
818
+ location: hit.location,
819
+ ...(hit.representativeTick === undefined
820
+ ? {}
821
+ : { representativeTick: hit.representativeTick }),
822
+ query,
823
+ signals: hit.signals,
824
+ selectedRevision: engine.head,
825
+ ordinal: 0,
826
+ createdAt: Date.now(),
827
+ };
828
+ let pinnedCell;
829
+ const result = await mutateNotebook(engine, String(args.notebook_id), "pin_search_moment", (notebook) => {
830
+ const existing = notebook.cells.find((cell) => cell.id === cellId);
831
+ if (existing) {
832
+ const pinnedResults = [
833
+ ...(existing.pinnedResults ?? []),
834
+ {
835
+ ...pinnedResult,
836
+ ordinal: existing.pinnedResults?.length ?? 0,
837
+ },
838
+ ];
839
+ pinnedCell = { ...existing, pinnedResults };
840
+ return {
841
+ ...notebook,
842
+ cells: notebook.cells.map((cell) => cell.id === cellId ? pinnedCell : cell),
843
+ };
844
+ }
845
+ const created = {
846
+ id: cellId,
847
+ type: hit.artifactKind === "audio"
848
+ ? "audio"
849
+ : hit.location.kind === "timed"
850
+ ? "video"
851
+ : "image",
852
+ ...(typeof args.cell_label === "string" && args.cell_label.trim()
853
+ ? { label: args.cell_label.trim() }
854
+ : {}),
855
+ slot: isSlot(args.slot)
856
+ ? args.slot
857
+ : firstEmptyNotebookSlot(notebook),
858
+ references: [{
859
+ id: uuidv7(),
860
+ kind: "artifact",
861
+ targetId: hit.artifactId,
862
+ snapshot: {
863
+ objectHash: pinnedResult.objectHash,
864
+ ...(hit.artifactLabel
865
+ ? { artifactLabel: hit.artifactLabel }
866
+ : {}),
867
+ },
868
+ ordinal: 0,
869
+ }],
870
+ pinnedResults: [pinnedResult],
871
+ inputs: {
872
+ selectionKind: "semantic-search",
873
+ ...(hit.location.kind === "timed"
874
+ ? {
875
+ startSeconds: hit.location.range.startTick
876
+ * hit.location.range.timeBase.numerator
877
+ / hit.location.range.timeBase.denominator,
878
+ endSeconds: (hit.location.range.startTick
879
+ + hit.location.range.durationTicks) * hit.location.range.timeBase.numerator
880
+ / hit.location.range.timeBase.denominator,
881
+ }
882
+ : {}),
883
+ },
884
+ };
885
+ pinnedCell = created;
886
+ return {
887
+ ...notebook,
888
+ cells: [...notebook.cells, created],
889
+ };
890
+ }, { cellId, artifactId: hit.artifactId });
891
+ return result.ok
892
+ ? json({ cell: pinnedCell, revision: result.value.hash })
893
+ : failure(result.error.message);
894
+ },
895
+ },
896
+ {
897
+ name: "send_search_moment_to_sequence",
898
+ description: "Append one search moment to the primary sequence as a reversible edit",
899
+ scope: "book",
900
+ schema: {
901
+ ...bookSchema,
902
+ hit: searchHitSchema,
903
+ timeline_start_frame: z.number().int().nonnegative().optional(),
904
+ still_duration_frames: z.number().int().positive().optional(),
905
+ },
906
+ handler: async (args) => {
907
+ const hit = args.hit;
908
+ const sequence = engine.sequences.getPrimary();
909
+ const trackKind = hit.artifactKind === "audio" ? "audio" : "video";
910
+ const track = sequence.tracks.find((candidate) => candidate.kind === trackKind && candidate.enabled && !candidate.locked);
911
+ if (!track)
912
+ return failure(`No editable ${trackKind} track is available`);
913
+ const durationFrames = hit.location.kind === "timed"
914
+ ? sourceTicksToSequenceFrames(hit.location.range.durationTicks, hit.location.range.timeBase, sequence.frameRate, "ceil")
915
+ : typeof args.still_duration_frames === "number"
916
+ ? args.still_duration_frames
917
+ : 90;
918
+ const timelineStartFrame = typeof args.timeline_start_frame === "number"
919
+ ? args.timeline_start_frame
920
+ : sequence.clips
921
+ .filter((clip) => clip.trackId === track.trackId)
922
+ .reduce((end, clip) => Math.max(end, clip.timelineStartFrame + clip.durationFrames), 0);
923
+ const intent = {
924
+ intentVersion: MVP_CONTRACT_VERSION,
925
+ commandId: uuidv7(),
926
+ sequenceId: sequence.sequenceId,
927
+ baseRevision: engine.head,
928
+ actor: "videobook-ui",
929
+ sourceSurface: "ui",
930
+ confirmationPolicy: "reversible-single-step",
931
+ operations: [{
932
+ kind: "insert-clip",
933
+ mode: "insert",
934
+ placement: {
935
+ trackId: track.trackId,
936
+ timelineStartFrame,
937
+ durationFrames,
938
+ source: hit.location.kind === "timed"
939
+ ? {
940
+ kind: "timed",
941
+ artifactId: hit.artifactId,
942
+ range: hit.location.range,
943
+ }
944
+ : {
945
+ kind: "still",
946
+ artifactId: hit.artifactId,
947
+ sourcePath: hit.location.sourcePath,
948
+ objectHash: hit.location.objectHash,
949
+ },
950
+ ...(hit.location.kind === "timed"
951
+ ? {
952
+ speed: { numerator: 1, denominator: 1 },
953
+ reverse: false,
954
+ audioPolicy: "preserve-pitch",
955
+ }
956
+ : {}),
957
+ },
958
+ }],
959
+ };
960
+ const preview = engine.edits.preview(intent);
961
+ if (!preview.ok)
962
+ return failure(preview.error.message);
963
+ if (!preview.value.valid)
964
+ return json({ preview: preview.value });
965
+ const committed = await engine.edits.commit(intent, preview.value.previewHash);
966
+ return committed.ok
967
+ ? json({ preview: preview.value, commit: committed.value })
968
+ : failure(committed.error.message);
969
+ },
970
+ },
971
+ {
972
+ name: "list_sequence_replace_targets",
973
+ description: "List clips that a search moment can explicitly replace",
974
+ scope: "book",
975
+ schema: bookSchema,
976
+ handler: async () => {
977
+ const sequence = engine.sequences.getPrimary();
978
+ const tracks = new Map(sequence.tracks.map((track) => [track.trackId, track]));
979
+ return json({
980
+ sequenceId: sequence.sequenceId,
981
+ revision: sequence.revision,
982
+ targets: sequence.clips.map((clip) => ({
983
+ clipId: clip.clipId,
984
+ trackId: clip.trackId,
985
+ trackKind: tracks.get(clip.trackId)?.kind ?? "unknown",
986
+ timelineStartFrame: clip.timelineStartFrame,
987
+ durationFrames: clip.durationFrames,
988
+ artifactId: clip.source.artifactId,
989
+ })),
990
+ });
991
+ },
992
+ },
993
+ {
994
+ name: "replace_sequence_clip_with_search_moment",
995
+ description: "Preview, then confirm, replacing one explicit sequence clip with a search moment",
996
+ scope: "book",
997
+ schema: {
998
+ ...bookSchema,
999
+ hit: searchHitSchema,
1000
+ clip_id: z.string().uuid(),
1001
+ command_id: z.string().uuid().optional(),
1002
+ base_revision: z.string().min(1).optional(),
1003
+ preview_hash: z.string().min(1).optional(),
1004
+ },
1005
+ handler: async (args) => {
1006
+ const hit = args.hit;
1007
+ const sequence = engine.sequences.getPrimary();
1008
+ const target = sequence.clips.find((clip) => clip.clipId === args.clip_id);
1009
+ if (!target)
1010
+ return failure(`Sequence clip not found: ${String(args.clip_id)}`);
1011
+ const track = sequence.tracks.find((candidate) => candidate.trackId === target.trackId);
1012
+ if (!track || track.locked || !track.enabled) {
1013
+ return failure("The target clip is not on an editable track");
1014
+ }
1015
+ const expectedKind = hit.artifactKind === "audio" ? "audio" : "video";
1016
+ if (track.kind !== expectedKind) {
1017
+ return failure(`A ${hit.artifactKind} result cannot replace a ${track.kind} clip`);
1018
+ }
1019
+ const durationFrames = hitDurationFrames(hit, sequence.frameRate, target.durationFrames);
1020
+ const commandId = typeof args.command_id === "string"
1021
+ ? args.command_id
1022
+ : uuidv7();
1023
+ const intent = {
1024
+ intentVersion: MVP_CONTRACT_VERSION,
1025
+ commandId,
1026
+ sequenceId: sequence.sequenceId,
1027
+ baseRevision: typeof args.base_revision === "string"
1028
+ ? args.base_revision
1029
+ : engine.head,
1030
+ actor: "videobook-ui",
1031
+ sourceSurface: "ui",
1032
+ confirmationPolicy: "always",
1033
+ operations: [{
1034
+ kind: "batch-replace-range",
1035
+ range: {
1036
+ sequenceId: sequence.sequenceId,
1037
+ startFrame: target.timelineStartFrame,
1038
+ durationFrames: target.durationFrames,
1039
+ },
1040
+ trackIds: [target.trackId],
1041
+ placements: [{
1042
+ trackId: target.trackId,
1043
+ timelineStartFrame: target.timelineStartFrame,
1044
+ durationFrames,
1045
+ source: hit.location.kind === "timed"
1046
+ ? {
1047
+ kind: "timed",
1048
+ artifactId: hit.artifactId,
1049
+ range: hit.location.range,
1050
+ }
1051
+ : {
1052
+ kind: "still",
1053
+ artifactId: hit.artifactId,
1054
+ sourcePath: hit.location.sourcePath,
1055
+ objectHash: hit.location.objectHash,
1056
+ },
1057
+ ...(hit.location.kind === "timed"
1058
+ ? {
1059
+ speed: { numerator: 1, denominator: 1 },
1060
+ reverse: false,
1061
+ audioPolicy: "preserve-pitch",
1062
+ }
1063
+ : {}),
1064
+ }],
1065
+ ripple: false,
1066
+ }],
1067
+ };
1068
+ const preview = engine.edits.preview(intent);
1069
+ if (!preview.ok)
1070
+ return failure(preview.error.message);
1071
+ if (typeof args.preview_hash !== "string") {
1072
+ return json({
1073
+ confirmationRequired: true,
1074
+ commandId,
1075
+ baseRevision: intent.baseRevision,
1076
+ preview: preview.value,
1077
+ });
1078
+ }
1079
+ if (args.preview_hash !== preview.value.previewHash) {
1080
+ return failure("The replacement preview changed; review the latest preview");
1081
+ }
1082
+ if (!preview.value.valid) {
1083
+ return json({
1084
+ confirmationRequired: true,
1085
+ commandId,
1086
+ baseRevision: intent.baseRevision,
1087
+ preview: preview.value,
1088
+ });
1089
+ }
1090
+ const committed = await engine.edits.commit(intent, preview.value.previewHash);
1091
+ return committed.ok
1092
+ ? json({ preview: preview.value, commit: committed.value })
1093
+ : failure(committed.error.message);
1094
+ },
1095
+ },
1096
+ ];
1097
+ }
1098
+ async function searchLibraryMoments(books, args) {
1099
+ await books.ready();
1100
+ const query = args.query;
1101
+ const referenceId = typeof args.reference_id === "string"
1102
+ ? args.reference_id
1103
+ : undefined;
1104
+ const prepared = referenceId
1105
+ ? searchReferenceStore.get(referenceId).reference
1106
+ : undefined;
1107
+ const preparedOptions = preparedSearchOptions(args.reference_range);
1108
+ const pages = await Promise.all(books.list().map(async (summary) => {
1109
+ const managed = books.get(summary.bookId);
1110
+ if (!managed.ok) {
1111
+ return { summary, error: managed.error.message };
1112
+ }
1113
+ registerLocalClipSearchProvider(managed.value.engine);
1114
+ registerLocalClapSearchProvider(managed.value.engine, FFMPEG);
1115
+ const bookQuery = {
1116
+ ...query,
1117
+ cursor: undefined,
1118
+ limit: Math.min(query.limit ?? 30, 100),
1119
+ };
1120
+ const result = prepared
1121
+ ? await managed.value.engine.temporalSearch.queryPrepared(bookQuery, prepared, preparedOptions)
1122
+ : await managed.value.engine.temporalSearch.query(bookQuery);
1123
+ if (!result.ok) {
1124
+ const preparationJob = result.error.code === "NOT_READY" && result.error.details?.requiresIndexPreparation
1125
+ ? await enqueueTemporalSearchPreparation(summary.bookId)
1126
+ : undefined;
1127
+ return { summary, error: result.error.message, preparationJob };
1128
+ }
1129
+ const assets = await managed.value.engine.withLocalMedia(() => buildAssetList(managed.value.engine, summary.bookId, "newest")).catch(() => []);
1130
+ const assetById = new Map(assets.map((asset) => [asset.artifact_id, asset]));
1131
+ return {
1132
+ summary,
1133
+ page: {
1134
+ ...result.value,
1135
+ hits: result.value.hits.map((hit) => {
1136
+ const asset = assetById.get(hit.artifactId);
1137
+ return {
1138
+ ...hit,
1139
+ mediaUrl: asset?.media_url ?? null,
1140
+ thumbnailUrl: asset?.thumbnail_url ?? null,
1141
+ };
1142
+ }),
1143
+ },
1144
+ };
1145
+ }));
1146
+ const hits = pages.flatMap((entry) => entry.page?.hits.map((hit) => ({
1147
+ ...hit,
1148
+ score: comparableHitScore(hit),
1149
+ owningBookId: entry.summary.bookId,
1150
+ owningBookName: entry.summary.name,
1151
+ })) ?? []);
1152
+ hits.sort((left, right) => right.score - left.score
1153
+ || left.owningBookName.localeCompare(right.owningBookName)
1154
+ || left.artifactId.localeCompare(right.artifactId)
1155
+ || JSON.stringify(left.location).localeCompare(JSON.stringify(right.location)));
1156
+ const limit = Math.min(query.limit ?? 30, 100);
1157
+ return json({
1158
+ hits: hits.slice(0, limit),
1159
+ preparationJobs: pages.flatMap((entry) => entry.preparationJob ? [entry.preparationJob] : []),
1160
+ coverage: {
1161
+ state: pages.some((entry) => entry.error || entry.page?.coverage.partialResults)
1162
+ ? "partial"
1163
+ : "ready",
1164
+ partialResults: pages.some((entry) => Boolean(entry.error || entry.page?.coverage.partialResults)),
1165
+ indexedArtifactCount: pages.reduce((sum, entry) => sum + (entry.page?.coverage.indexedArtifactCount ?? 0), 0),
1166
+ totalArtifactCount: pages.reduce((sum, entry) => sum + (entry.page?.coverage.totalArtifactCount ?? 0), 0),
1167
+ books: pages.map((entry) => ({
1168
+ bookId: entry.summary.bookId,
1169
+ name: entry.summary.name,
1170
+ ...(entry.page ? { coverage: entry.page.coverage } : {}),
1171
+ ...(entry.error ? { error: entry.error } : {}),
1172
+ })),
1173
+ },
1174
+ });
1175
+ }
1176
+ function preparedSearchOptions(value) {
1177
+ if (typeof value !== "object" || value === null)
1178
+ return {};
1179
+ const range = value;
1180
+ if (typeof range.start_seconds !== "number")
1181
+ return {};
1182
+ return {
1183
+ range: {
1184
+ startMs: range.start_seconds * 1_000,
1185
+ ...(typeof range.duration_seconds === "number"
1186
+ ? { durationMs: range.duration_seconds * 1_000 }
1187
+ : {}),
1188
+ },
1189
+ };
1190
+ }
1191
+ function objectHashForHit(hit) {
1192
+ return hit.location.kind === "timed"
1193
+ ? hit.location.range.objectHash
1194
+ : hit.location.objectHash;
1195
+ }
1196
+ function hitDurationFrames(hit, frameRate, stillDurationFrames) {
1197
+ return hit.location.kind === "timed"
1198
+ ? sourceTicksToSequenceFrames(hit.location.range.durationTicks, hit.location.range.timeBase, frameRate, "ceil")
1199
+ : stillDurationFrames;
1200
+ }
1201
+ function isSlot(value) {
1202
+ if (typeof value !== "object" || value === null)
1203
+ return false;
1204
+ const slot = value;
1205
+ return Number.isSafeInteger(slot.row)
1206
+ && Number.isSafeInteger(slot.column)
1207
+ && isNotebookGridSlot({
1208
+ row: Number(slot.row),
1209
+ column: Number(slot.column),
1210
+ });
1211
+ }
1212
+ function firstEmptyNotebookSlot(notebook) {
1213
+ return firstEmptyNotebookGridSlot(notebookOccupiedSlots(notebook.cells));
1214
+ }