@mountaya/studio 0.0.0-stage → 0.1.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 (524) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +917 -2
  5. package/dist/agent/index.cjs +2854 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1257 -0
  8. package/dist/agent/index.d.ts +1257 -0
  9. package/dist/agent/index.js +2818 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/bus-BwiNiXdH.d.ts +514 -0
  12. package/dist/bus-DzmhPwdK.d.cts +514 -0
  13. package/dist/chainModel-B23pEP_1.d.cts +127 -0
  14. package/dist/chainModel-B23pEP_1.d.ts +127 -0
  15. package/dist/chunk-2HFY7ETU.js +5721 -0
  16. package/dist/chunk-2HFY7ETU.js.map +1 -0
  17. package/dist/chunk-355TOXSB.js +72 -0
  18. package/dist/chunk-355TOXSB.js.map +1 -0
  19. package/dist/chunk-4ZCUZVSV.js +10275 -0
  20. package/dist/chunk-4ZCUZVSV.js.map +1 -0
  21. package/dist/chunk-6HEKY3NF.js +95 -0
  22. package/dist/chunk-6HEKY3NF.js.map +1 -0
  23. package/dist/chunk-7GFLGGBX.cjs +8 -0
  24. package/dist/chunk-7GFLGGBX.cjs.map +1 -0
  25. package/dist/chunk-7NBRCENN.cjs +19 -0
  26. package/dist/chunk-7NBRCENN.cjs.map +1 -0
  27. package/dist/chunk-AF5GCXE3.js +8 -0
  28. package/dist/chunk-AF5GCXE3.js.map +1 -0
  29. package/dist/chunk-CJDIFRGZ.cjs +2005 -0
  30. package/dist/chunk-CJDIFRGZ.cjs.map +1 -0
  31. package/dist/chunk-CNPZY7N3.js +349 -0
  32. package/dist/chunk-CNPZY7N3.js.map +1 -0
  33. package/dist/chunk-DZJHTWSF.cjs +45 -0
  34. package/dist/chunk-DZJHTWSF.cjs.map +1 -0
  35. package/dist/chunk-EABIHHWA.js +42 -0
  36. package/dist/chunk-EABIHHWA.js.map +1 -0
  37. package/dist/chunk-EKZWV6RS.cjs +415 -0
  38. package/dist/chunk-EKZWV6RS.cjs.map +1 -0
  39. package/dist/chunk-EOKRXXAC.cjs +24 -0
  40. package/dist/chunk-EOKRXXAC.cjs.map +1 -0
  41. package/dist/chunk-F73W2ZTJ.js +1126 -0
  42. package/dist/chunk-F73W2ZTJ.js.map +1 -0
  43. package/dist/chunk-H4DVOZ5O.js +1897 -0
  44. package/dist/chunk-H4DVOZ5O.js.map +1 -0
  45. package/dist/chunk-HI52PBFT.cjs +10314 -0
  46. package/dist/chunk-HI52PBFT.cjs.map +1 -0
  47. package/dist/chunk-IDBXFBLG.cjs +1225 -0
  48. package/dist/chunk-IDBXFBLG.cjs.map +1 -0
  49. package/dist/chunk-LBWTJZUJ.js +297 -0
  50. package/dist/chunk-LBWTJZUJ.js.map +1 -0
  51. package/dist/chunk-NCLA6DKD.cjs +310 -0
  52. package/dist/chunk-NCLA6DKD.cjs.map +1 -0
  53. package/dist/chunk-O4MC5DPD.js +19 -0
  54. package/dist/chunk-O4MC5DPD.js.map +1 -0
  55. package/dist/chunk-OP37FKW6.cjs +98 -0
  56. package/dist/chunk-OP37FKW6.cjs.map +1 -0
  57. package/dist/chunk-OQSYFH3Z.cjs +5945 -0
  58. package/dist/chunk-OQSYFH3Z.cjs.map +1 -0
  59. package/dist/chunk-PACIO4NS.cjs +26 -0
  60. package/dist/chunk-PACIO4NS.cjs.map +1 -0
  61. package/dist/chunk-PSZ2R3TC.cjs +75 -0
  62. package/dist/chunk-PSZ2R3TC.cjs.map +1 -0
  63. package/dist/chunk-QFO5CZG2.cjs +136 -0
  64. package/dist/chunk-QFO5CZG2.cjs.map +1 -0
  65. package/dist/chunk-QL63MUEW.cjs +140 -0
  66. package/dist/chunk-QL63MUEW.cjs.map +1 -0
  67. package/dist/chunk-RFUPPVZO.js +17 -0
  68. package/dist/chunk-RFUPPVZO.js.map +1 -0
  69. package/dist/chunk-RPG2LWMP.js +23 -0
  70. package/dist/chunk-RPG2LWMP.js.map +1 -0
  71. package/dist/chunk-TIBXK6B7.cjs +12 -0
  72. package/dist/chunk-TIBXK6B7.cjs.map +1 -0
  73. package/dist/chunk-UU65VNEV.js +381 -0
  74. package/dist/chunk-UU65VNEV.js.map +1 -0
  75. package/dist/chunk-VGX6TR2I.js +209 -0
  76. package/dist/chunk-VGX6TR2I.js.map +1 -0
  77. package/dist/chunk-WUTDDBVP.js +130 -0
  78. package/dist/chunk-WUTDDBVP.js.map +1 -0
  79. package/dist/chunk-WVQQLKCI.cjs +224 -0
  80. package/dist/chunk-WVQQLKCI.cjs.map +1 -0
  81. package/dist/chunk-WZYXG3SE.js +111 -0
  82. package/dist/chunk-WZYXG3SE.js.map +1 -0
  83. package/dist/chunk-XDI2X3KE.js +6 -0
  84. package/dist/chunk-XDI2X3KE.js.map +1 -0
  85. package/dist/chunk-XKHLRIC7.cjs +381 -0
  86. package/dist/chunk-XKHLRIC7.cjs.map +1 -0
  87. package/dist/context-DNtd2WUv.d.cts +11666 -0
  88. package/dist/context-DgB72Bur.d.ts +11666 -0
  89. package/dist/directorThreads-CqmvsV8b.d.cts +80 -0
  90. package/dist/directorThreads-CqmvsV8b.d.ts +80 -0
  91. package/dist/en-Bu4Ti9Ev.d.cts +2315 -0
  92. package/dist/en-Bu4Ti9Ev.d.ts +2315 -0
  93. package/dist/engines/index.cjs +3446 -0
  94. package/dist/engines/index.cjs.map +1 -0
  95. package/dist/engines/index.d.cts +2216 -0
  96. package/dist/engines/index.d.ts +2216 -0
  97. package/dist/engines/index.js +3416 -0
  98. package/dist/engines/index.js.map +1 -0
  99. package/dist/handlers/index.cjs +99 -0
  100. package/dist/handlers/index.cjs.map +1 -0
  101. package/dist/handlers/index.d.cts +445 -0
  102. package/dist/handlers/index.d.ts +445 -0
  103. package/dist/handlers/index.js +42 -0
  104. package/dist/handlers/index.js.map +1 -0
  105. package/dist/index.cjs +4562 -0
  106. package/dist/index.cjs.map +1 -0
  107. package/dist/index.d.cts +7297 -0
  108. package/dist/index.d.ts +7297 -0
  109. package/dist/index.js +3223 -0
  110. package/dist/index.js.map +1 -0
  111. package/dist/plugins/index.cjs +977 -0
  112. package/dist/plugins/index.cjs.map +1 -0
  113. package/dist/plugins/index.d.cts +313 -0
  114. package/dist/plugins/index.d.ts +313 -0
  115. package/dist/plugins/index.js +933 -0
  116. package/dist/plugins/index.js.map +1 -0
  117. package/dist/saveFile-j-1kkApx.d.cts +123 -0
  118. package/dist/saveFile-j-1kkApx.d.ts +123 -0
  119. package/dist/seams/index.cjs +152 -0
  120. package/dist/seams/index.cjs.map +1 -0
  121. package/dist/seams/index.d.cts +485 -0
  122. package/dist/seams/index.d.ts +485 -0
  123. package/dist/seams/index.js +79 -0
  124. package/dist/seams/index.js.map +1 -0
  125. package/dist/shareLink-B6hlt942.d.ts +144 -0
  126. package/dist/shareLink-C7rIMb7x.d.ts +527 -0
  127. package/dist/shareLink-CnTxxXjp.d.cts +144 -0
  128. package/dist/shareLink-DyZVYH2V.d.cts +527 -0
  129. package/dist/strings/fr/index.cjs +2121 -0
  130. package/dist/strings/fr/index.cjs.map +1 -0
  131. package/dist/strings/fr/index.d.cts +19 -0
  132. package/dist/strings/fr/index.d.ts +19 -0
  133. package/dist/strings/fr/index.js +2119 -0
  134. package/dist/strings/fr/index.js.map +1 -0
  135. package/dist/strings/index.cjs +2678 -0
  136. package/dist/strings/index.cjs.map +1 -0
  137. package/dist/strings/index.d.cts +731 -0
  138. package/dist/strings/index.d.ts +731 -0
  139. package/dist/strings/index.js +2644 -0
  140. package/dist/strings/index.js.map +1 -0
  141. package/dist/studioPlugin-C3C7VjMy.d.ts +847 -0
  142. package/dist/studioPlugin-Cf3OBNUv.d.cts +847 -0
  143. package/dist/tabs-B2nRO4p_.d.cts +15 -0
  144. package/dist/tabs-B2nRO4p_.d.ts +15 -0
  145. package/dist/testing/index.cjs +292 -0
  146. package/dist/testing/index.cjs.map +1 -0
  147. package/dist/testing/index.d.cts +306 -0
  148. package/dist/testing/index.d.ts +306 -0
  149. package/dist/testing/index.js +284 -0
  150. package/dist/testing/index.js.map +1 -0
  151. package/dist/time/index.cjs +28 -0
  152. package/dist/time/index.cjs.map +1 -0
  153. package/dist/time/index.d.cts +43 -0
  154. package/dist/time/index.d.ts +43 -0
  155. package/dist/time/index.js +26 -0
  156. package/dist/time/index.js.map +1 -0
  157. package/dist/types-BzJRV6UI.d.cts +845 -0
  158. package/dist/types-BzJRV6UI.d.ts +845 -0
  159. package/dist/zoneForm-CdYNtnnA.d.cts +320 -0
  160. package/dist/zoneForm-mG85yt5e.d.ts +320 -0
  161. package/package.json +225 -4
  162. package/src/agent/engines/agentThreads.ts +1601 -0
  163. package/src/agent/engines/directorChat.ts +500 -0
  164. package/src/agent/index.ts +67 -0
  165. package/src/agent/rules/agentEditLock.ts +115 -0
  166. package/src/agent/rules/agentErrorCopy.ts +44 -0
  167. package/src/agent/rules/copilotOrganization.ts +36 -0
  168. package/src/agent/rules/playbook.gen.ts +444 -0
  169. package/src/agent/rules/router.ts +518 -0
  170. package/src/agent/rules/stateDelta.ts +28 -0
  171. package/src/agent/rules/studioRouter.ts +123 -0
  172. package/src/agent/rules/surfaces.gen.ts +633 -0
  173. package/src/agent/rules/threadsUrl.ts +48 -0
  174. package/src/agent/rules/transcriptObserver.ts +90 -0
  175. package/src/agent/stores/agentThreads.ts +454 -0
  176. package/src/bus/contracts/noData.ts +18 -0
  177. package/src/bus/contracts/shared.ts +172 -0
  178. package/src/bus/contracts/studioTools.ts +224 -0
  179. package/src/bus/rules/bus.ts +858 -0
  180. package/src/bus/rules/confirmation.ts +22 -0
  181. package/src/bus/rules/defineRegistry.ts +26 -0
  182. package/src/bus/rules/errors.ts +401 -0
  183. package/src/bus/rules/handlerErrors.ts +103 -0
  184. package/src/bus/rules/handlerRegistry.ts +627 -0
  185. package/src/bus/rules/inputSchema.ts +232 -0
  186. package/src/bus/rules/invalidInput.ts +441 -0
  187. package/src/bus/rules/lateBoundTools.ts +100 -0
  188. package/src/bus/rules/studioRegistry.ts +324 -0
  189. package/src/bus/rules/studioToolBus.ts +73 -0
  190. package/src/bus/rules/types.ts +805 -0
  191. package/src/chrome/contracts/alert.ts +42 -0
  192. package/src/chrome/contracts/itinerary.ts +26 -0
  193. package/src/chrome/contracts/map.ts +23 -0
  194. package/src/chrome/contracts/overlay.ts +46 -0
  195. package/src/chrome/contracts/panel.ts +29 -0
  196. package/src/chrome/contracts/question.ts +52 -0
  197. package/src/chrome/contracts/selection.ts +26 -0
  198. package/src/chrome/contracts/sidenav.ts +23 -0
  199. package/src/chrome/contracts/snapshot.ts +319 -0
  200. package/src/chrome/contracts/state.ts +22 -0
  201. package/src/chrome/contracts/tabs.ts +56 -0
  202. package/src/chrome/handlers/alert.ts +91 -0
  203. package/src/chrome/handlers/introspection.ts +180 -0
  204. package/src/chrome/handlers/panels.ts +42 -0
  205. package/src/chrome/handlers/question.ts +24 -0
  206. package/src/chrome/handlers/sidenav.ts +116 -0
  207. package/src/chrome/handlers/snapshot.ts +451 -0
  208. package/src/chrome/handlers/stateDelta.ts +125 -0
  209. package/src/chrome/handlers/tabs.ts +143 -0
  210. package/src/chrome/handlers/timestamp.ts +19 -0
  211. package/src/chrome/rules/agentSelectors.ts +210 -0
  212. package/src/chrome/rules/mapAlert.ts +13 -0
  213. package/src/chrome/rules/question.ts +25 -0
  214. package/src/chrome/rules/tabs.ts +13 -0
  215. package/src/chrome/stores/activeDraftSession.ts +134 -0
  216. package/src/chrome/stores/chrome.ts +527 -0
  217. package/src/chrome/stores/uiStore.ts +573 -0
  218. package/src/collab/contracts/collab.ts +261 -0
  219. package/src/collab/handlers/collab.ts +468 -0
  220. package/src/collab/rules/toolNames.ts +33 -0
  221. package/src/collab/stores/collab.ts +899 -0
  222. package/src/collections/contracts/collection.ts +182 -0
  223. package/src/collections/handlers/collectionAttach.ts +141 -0
  224. package/src/collections/handlers/collections.ts +499 -0
  225. package/src/collections/handlers/heldCollection.ts +42 -0
  226. package/src/collections/handlers/restCollections.ts +386 -0
  227. package/src/collections/rules/collections.ts +138 -0
  228. package/src/collections/rules/entityCollections.ts +53 -0
  229. package/src/collections/stores/collections.ts +133 -0
  230. package/src/data/contracts/data.ts +233 -0
  231. package/src/data/contracts/itinerary.ts +71 -0
  232. package/src/data/handlers/activityResolve.ts +76 -0
  233. package/src/data/handlers/data.ts +200 -0
  234. package/src/data/handlers/graphql.ts +26 -0
  235. package/src/data/handlers/mutationSink.ts +1577 -0
  236. package/src/data/handlers/profile.ts +83 -0
  237. package/src/data/handlers/writeThrough.ts +417 -0
  238. package/src/data/rules/cache.ts +181 -0
  239. package/src/data/rules/dataTypes.ts +40 -0
  240. package/src/data/rules/keys.ts +106 -0
  241. package/src/data/rules/persistence.ts +1058 -0
  242. package/src/data/rules/requestBody.ts +43 -0
  243. package/src/data/rules/restErrors.ts +354 -0
  244. package/src/data/rules/sessionSurface.ts +156 -0
  245. package/src/data/rules/toolResultData.ts +73 -0
  246. package/src/data/rules/uuid.ts +24 -0
  247. package/src/edit/contracts/edit.ts +37 -0
  248. package/src/edit/contracts/itinerary.ts +57 -0
  249. package/src/edit/handlers/draftCommit.ts +257 -0
  250. package/src/edit/handlers/editDiscard.ts +34 -0
  251. package/src/edit/handlers/editLock.ts +949 -0
  252. package/src/edit/handlers/editor.ts +203 -0
  253. package/src/edit/handlers/formUnsaved.ts +24 -0
  254. package/src/edit/rules/draftMetadata.ts +117 -0
  255. package/src/edit/rules/editKeyboard.ts +222 -0
  256. package/src/edit/rules/editShortcuts.ts +102 -0
  257. package/src/edit/rules/editTooltip.ts +174 -0
  258. package/src/edit/rules/editorTaken.ts +49 -0
  259. package/src/edit/rules/history.ts +26 -0
  260. package/src/edit/rules/unsavedWork.ts +60 -0
  261. package/src/edit/stores/editorReservation.ts +70 -0
  262. package/src/edit/stores/formsUnsaved.ts +54 -0
  263. package/src/embed/contracts/embed.ts +48 -0
  264. package/src/embed/engines/embedFraming.ts +1329 -0
  265. package/src/embed/engines/embedReady.ts +353 -0
  266. package/src/embed/engines/framingPageSession.ts +169 -0
  267. package/src/embed/handlers/embed.ts +130 -0
  268. package/src/embed/rules/allowedDomains.ts +71 -0
  269. package/src/embed/rules/bridgeMessages.ts +224 -0
  270. package/src/embed/rules/defaults.ts +173 -0
  271. package/src/embed/rules/displaySeed.ts +115 -0
  272. package/src/embed/rules/embedAllowlist.ts +146 -0
  273. package/src/embed/rules/embedConstraints.ts +215 -0
  274. package/src/embed/rules/embedElements.ts +277 -0
  275. package/src/embed/rules/embedSectionFields.ts +126 -0
  276. package/src/embed/rules/embedSecurity.ts +116 -0
  277. package/src/embed/rules/fieldDependencies.ts +87 -0
  278. package/src/embed/rules/fieldOptions.ts +138 -0
  279. package/src/embed/rules/layerOptions.ts +161 -0
  280. package/src/embed/rules/readyProtocol.ts +66 -0
  281. package/src/embed/rules/safetyRules.ts +213 -0
  282. package/src/embed/rules/snippet.ts +531 -0
  283. package/src/embed/rules/tableCode.ts +269 -0
  284. package/src/embed/stores/embed.ts +60 -0
  285. package/src/embed/stores/embedContent.ts +77 -0
  286. package/src/engines/index.ts +81 -0
  287. package/src/handlers/index.ts +66 -0
  288. package/src/index.ts +1086 -0
  289. package/src/itinerary/contracts/itinerary.ts +705 -0
  290. package/src/itinerary/engines/itineraryPace.ts +612 -0
  291. package/src/itinerary/engines/profileMarker.ts +238 -0
  292. package/src/itinerary/handlers/importStaging.ts +352 -0
  293. package/src/itinerary/handlers/itinerary.ts +572 -0
  294. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  295. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  296. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  297. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  298. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  299. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  300. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  301. package/src/itinerary/handlers/publicationScope.ts +118 -0
  302. package/src/itinerary/handlers/restItineraries.ts +752 -0
  303. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  304. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  305. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  306. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  307. package/src/itinerary/handlers/suggestParams.ts +379 -0
  308. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  309. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  310. package/src/itinerary/rules/activity.ts +139 -0
  311. package/src/itinerary/rules/analysis.ts +42 -0
  312. package/src/itinerary/rules/ceiling.ts +49 -0
  313. package/src/itinerary/rules/createFlow.ts +107 -0
  314. package/src/itinerary/rules/densify.ts +440 -0
  315. package/src/itinerary/rules/draftSurface.ts +219 -0
  316. package/src/itinerary/rules/editorView.ts +83 -0
  317. package/src/itinerary/rules/export.ts +159 -0
  318. package/src/itinerary/rules/friendlyName.ts +77 -0
  319. package/src/itinerary/rules/import.ts +1052 -0
  320. package/src/itinerary/rules/importFiles.ts +140 -0
  321. package/src/itinerary/rules/importTotals.ts +77 -0
  322. package/src/itinerary/rules/liveSegment.ts +712 -0
  323. package/src/itinerary/rules/lngLat.ts +17 -0
  324. package/src/itinerary/rules/mapSync.ts +100 -0
  325. package/src/itinerary/rules/previewRender.ts +416 -0
  326. package/src/itinerary/rules/profileReadout.ts +216 -0
  327. package/src/itinerary/rules/routing.ts +707 -0
  328. package/src/itinerary/rules/suggest.ts +522 -0
  329. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  330. package/src/itinerary/rules/view.ts +61 -0
  331. package/src/itinerary/stores/importSession.ts +319 -0
  332. package/src/itinerary/stores/itinerary.ts +331 -0
  333. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  334. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  335. package/src/itinerary/stores/suggestSession.ts +418 -0
  336. package/src/layers/contracts/itinerary.ts +46 -0
  337. package/src/layers/contracts/overlay.ts +132 -0
  338. package/src/layers/handlers/enrichment.ts +36 -0
  339. package/src/layers/handlers/overlay.ts +406 -0
  340. package/src/layers/handlers/restLayers.ts +94 -0
  341. package/src/layers/handlers/tiles.ts +25 -0
  342. package/src/layers/rules/layers.ts +212 -0
  343. package/src/layers/rules/overlayInstant.ts +12 -0
  344. package/src/layers/rules/reachabilityIcon.ts +18 -0
  345. package/src/layers/rules/readout.ts +102 -0
  346. package/src/layers/stores/layers.ts +262 -0
  347. package/src/map/contracts/contextmenu.ts +33 -0
  348. package/src/map/contracts/geolocate.ts +37 -0
  349. package/src/map/contracts/map.ts +146 -0
  350. package/src/map/contracts/streetview.ts +53 -0
  351. package/src/map/contracts/terrain.ts +152 -0
  352. package/src/map/handlers/contextMenu.ts +135 -0
  353. package/src/map/handlers/geolocate.ts +52 -0
  354. package/src/map/handlers/map.ts +391 -0
  355. package/src/map/handlers/streetview.ts +94 -0
  356. package/src/map/handlers/terrain.ts +663 -0
  357. package/src/map/rules/baseTerrain.ts +75 -0
  358. package/src/map/rules/clickTargets.ts +464 -0
  359. package/src/map/rules/constraints.ts +32 -0
  360. package/src/map/rules/contextMenuReadout.ts +67 -0
  361. package/src/map/rules/coordinates.ts +71 -0
  362. package/src/map/rules/itineraryFit.ts +8 -0
  363. package/src/map/rules/mapEvents.ts +64 -0
  364. package/src/map/rules/mapProjection.ts +476 -0
  365. package/src/map/rules/terrainReading.ts +62 -0
  366. package/src/plugins/contracts/ids.ts +66 -0
  367. package/src/plugins/contracts/plugin.ts +200 -0
  368. package/src/plugins/contracts/slots.ts +137 -0
  369. package/src/plugins/engines/studioPlugin.ts +1365 -0
  370. package/src/plugins/index.ts +111 -0
  371. package/src/plugins/rules/contributions.ts +152 -0
  372. package/src/plugins/rules/errors.ts +60 -0
  373. package/src/plugins/rules/ids.ts +42 -0
  374. package/src/plugins/rules/validation.ts +249 -0
  375. package/src/rules/listeners.ts +57 -0
  376. package/src/rules/origin.ts +13 -0
  377. package/src/rules/storeWrite.ts +37 -0
  378. package/src/rules/types.ts +136 -0
  379. package/src/seams/index.ts +79 -0
  380. package/src/seams/rules/clock.ts +28 -0
  381. package/src/seams/rules/formatters.ts +209 -0
  382. package/src/seams/rules/ids.ts +102 -0
  383. package/src/seams/rules/links.ts +66 -0
  384. package/src/seams/rules/navigation.ts +222 -0
  385. package/src/seams/rules/notify.ts +49 -0
  386. package/src/seams/rules/persistenceDrawer.ts +220 -0
  387. package/src/seams/rules/saveFile.ts +101 -0
  388. package/src/seams/rules/seams.ts +156 -0
  389. package/src/seams/rules/storage.ts +116 -0
  390. package/src/search/contracts/overlay.ts +74 -0
  391. package/src/search/contracts/search.ts +197 -0
  392. package/src/search/handlers/pois.ts +57 -0
  393. package/src/search/handlers/search.ts +280 -0
  394. package/src/search/rules/params.ts +925 -0
  395. package/src/search/rules/poiGroups.ts +138 -0
  396. package/src/search/rules/searchFetch.ts +139 -0
  397. package/src/search/rules/timeWindow.ts +30 -0
  398. package/src/search/stores/search.ts +51 -0
  399. package/src/segments/contracts/itinerary.ts +433 -0
  400. package/src/segments/contracts/segment.ts +35 -0
  401. package/src/segments/engines/segmentDraft.ts +926 -0
  402. package/src/segments/handlers/chainGuards.ts +67 -0
  403. package/src/segments/handlers/directions.ts +44 -0
  404. package/src/segments/handlers/itineraryEcho.ts +45 -0
  405. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  406. package/src/segments/handlers/segment.ts +111 -0
  407. package/src/segments/handlers/segmentEdit.ts +1341 -0
  408. package/src/segments/handlers/segmentGroups.ts +347 -0
  409. package/src/segments/handlers/segmentStructure.ts +1144 -0
  410. package/src/segments/rules/chain.ts +196 -0
  411. package/src/segments/rules/chainModel.ts +217 -0
  412. package/src/segments/rules/colors.ts +11 -0
  413. package/src/segments/rules/commit.ts +76 -0
  414. package/src/segments/rules/draft.ts +90 -0
  415. package/src/segments/rules/draftDisposition.ts +43 -0
  416. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  417. package/src/segments/rules/engine.ts +222 -0
  418. package/src/segments/rules/groupSave.ts +234 -0
  419. package/src/segments/rules/hazardPrompt.ts +60 -0
  420. package/src/segments/rules/itineraryEcho.ts +40 -0
  421. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  422. package/src/segments/rules/merge.ts +51 -0
  423. package/src/segments/rules/metrics.ts +456 -0
  424. package/src/segments/rules/naming.ts +168 -0
  425. package/src/segments/rules/segmentArming.ts +144 -0
  426. package/src/segments/rules/splitPick.ts +84 -0
  427. package/src/segments/rules/viaSimplify.ts +230 -0
  428. package/src/segments/stores/directions.ts +77 -0
  429. package/src/segments/stores/roadAccessDialog.ts +58 -0
  430. package/src/segments/stores/segmentEdit.ts +922 -0
  431. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  432. package/src/segments/stores/segmentSplit.ts +77 -0
  433. package/src/share/contracts/share.ts +39 -0
  434. package/src/share/contracts/shareLink.ts +63 -0
  435. package/src/share/engines/shareLink.ts +1053 -0
  436. package/src/share/handlers/share.ts +47 -0
  437. package/src/share/handlers/shareLink.ts +231 -0
  438. package/src/share/handlers/shareScope.ts +54 -0
  439. package/src/share/rules/link.ts +89 -0
  440. package/src/share/rules/shareLink.ts +218 -0
  441. package/src/share/rules/targets.ts +92 -0
  442. package/src/share/rules/viewConfig.ts +95 -0
  443. package/src/share/stores/share.ts +58 -0
  444. package/src/strings/fr/index.ts +18 -0
  445. package/src/strings/fr/rules/fr.ts +2368 -0
  446. package/src/strings/index.ts +98 -0
  447. package/src/strings/rules/confirmCopy.ts +156 -0
  448. package/src/strings/rules/draftToolNames.ts +94 -0
  449. package/src/strings/rules/en.ts +2519 -0
  450. package/src/strings/rules/failureAlert.ts +115 -0
  451. package/src/strings/rules/formError.ts +400 -0
  452. package/src/strings/rules/maneuvers.ts +107 -0
  453. package/src/strings/rules/outputOptions.ts +126 -0
  454. package/src/strings/rules/publicationState.ts +100 -0
  455. package/src/strings/rules/routeHazardCopy.ts +62 -0
  456. package/src/strings/rules/searchLabels.ts +50 -0
  457. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  458. package/src/strings/rules/studioCopy.ts +130 -0
  459. package/src/strings/rules/unitOptions.ts +119 -0
  460. package/src/testing/checkedBus.ts +226 -0
  461. package/src/testing/index.ts +34 -0
  462. package/src/testing/plugins.ts +106 -0
  463. package/src/testing/studio.ts +267 -0
  464. package/src/testing/urlSeam.ts +153 -0
  465. package/src/time/index.ts +12 -0
  466. package/src/time/rules/sun.ts +78 -0
  467. package/src/video/contracts/cameraSchemas.ts +266 -0
  468. package/src/video/contracts/profileSchemas.ts +37 -0
  469. package/src/video/contracts/video.ts +601 -0
  470. package/src/video/handlers/video.ts +1638 -0
  471. package/src/video/handlers/videoDirector.ts +114 -0
  472. package/src/video/rules/previewRefresh.ts +76 -0
  473. package/src/video/rules/profileSource.ts +51 -0
  474. package/src/video/rules/routeSpans.ts +79 -0
  475. package/src/video/rules/shotDefaults.ts +28 -0
  476. package/src/video/rules/stepOrder.ts +17 -0
  477. package/src/video/rules/videoSnapshot.ts +136 -0
  478. package/src/video/stores/directorThreads.ts +167 -0
  479. package/src/video/stores/videoExport.ts +290 -0
  480. package/src/viewer/contracts/preferences.ts +40 -0
  481. package/src/viewer/handlers/preferences.ts +91 -0
  482. package/src/viewer/rules/capabilities.ts +42 -0
  483. package/src/viewer/rules/config.ts +266 -0
  484. package/src/viewer/rules/context.ts +375 -0
  485. package/src/viewer/rules/ownership.ts +134 -0
  486. package/src/viewer/rules/platformViewer.ts +198 -0
  487. package/src/viewer/rules/scope.ts +197 -0
  488. package/src/viewer/rules/url.ts +145 -0
  489. package/src/viewer/rules/viewer.ts +307 -0
  490. package/src/viewer/rules/viewerSeam.ts +49 -0
  491. package/src/viewer/rules/viewerUnits.ts +34 -0
  492. package/src/waypoints/contracts/itinerary.ts +417 -0
  493. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  494. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  495. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  496. package/src/waypoints/rules/amenities.ts +30 -0
  497. package/src/waypoints/rules/defaults.ts +31 -0
  498. package/src/waypoints/rules/details.ts +213 -0
  499. package/src/waypoints/rules/detailsDraft.ts +312 -0
  500. package/src/waypoints/rules/detailsPreview.ts +76 -0
  501. package/src/waypoints/rules/detailsSave.ts +356 -0
  502. package/src/waypoints/rules/draftDirty.ts +45 -0
  503. package/src/waypoints/rules/icons.ts +32 -0
  504. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  505. package/src/waypoints/rules/naming.ts +185 -0
  506. package/src/waypoints/rules/sections.ts +77 -0
  507. package/src/waypoints/rules/waypointDraft.ts +62 -0
  508. package/src/waypoints/stores/waypointDetails.ts +62 -0
  509. package/src/waypoints/stores/waypointEdit.ts +566 -0
  510. package/src/zones/contracts/collection.ts +37 -0
  511. package/src/zones/contracts/zone.ts +528 -0
  512. package/src/zones/engines/zoneForm.ts +1773 -0
  513. package/src/zones/handlers/restZones.ts +287 -0
  514. package/src/zones/handlers/zonePublish.ts +206 -0
  515. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  516. package/src/zones/handlers/zones.ts +2254 -0
  517. package/src/zones/rules/geometry.ts +946 -0
  518. package/src/zones/rules/zoneDefaults.ts +34 -0
  519. package/src/zones/rules/zoneDraft.ts +54 -0
  520. package/src/zones/rules/zoneForm.ts +563 -0
  521. package/src/zones/rules/zoneMetadata.ts +29 -0
  522. package/src/zones/rules/zoneSource.ts +87 -0
  523. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  524. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1638 @@
1
+ import type { z } from "zod";
2
+
3
+ import {
4
+ bitrateForOutput,
5
+ type CameraOutput,
6
+ type CameraPlan,
7
+ type CameraPlanner,
8
+ type CameraShot,
9
+ cameraPlanGenerators,
10
+ insertShotSorted,
11
+ neutralDirectorPlan,
12
+ type ProfileSource,
13
+ type RouteGeometry,
14
+ sameRouteContent,
15
+ VideoFlightEngine,
16
+ type VideoFlightStatus,
17
+ videoPresets,
18
+ } from "@mountaya/elements/camera";
19
+ import type { MapClient } from "@mountaya/elements/map-client";
20
+
21
+ import type { StudioToolInputs, studioToolContracts } from "../../bus/contracts/studioTools.js";
22
+ import type { ToolFailure, ToolResult } from "../../bus/rules/types.js";
23
+ import { requireOrganizationOwned } from "../../itinerary/handlers/publicationScope.js";
24
+ import { buildExportFilename, exportFileStem } from "../../itinerary/rules/export.js";
25
+ import { studioSeamAbsences } from "../../seams/rules/seams.js";
26
+ import type { StudioToolContext, StudioToolDefinition } from "../../viewer/rules/context.js";
27
+ import { entitlementWithheld } from "../../viewer/rules/viewer.js";
28
+ import { cameraOutputSchema, cameraPlanSchema } from "../contracts/cameraSchemas.js";
29
+ import {
30
+ defaultVideoExportProfile,
31
+ type VideoExport,
32
+ videoExportSchema,
33
+ videoExportStatusSchema,
34
+ } from "../stores/videoExport.js";
35
+
36
+ /**
37
+ * The flight a studio's video wizard flies, and what it was built over.
38
+ *
39
+ * One `VideoFlightEngine` of `@mountaya/elements/camera` flies the wizard: it warms the route,
40
+ * resolves and memoizes the flight, previews, parks, records and reports progress. The wizard's
41
+ * slot stays the authority for what is flown, and the engine for how the flight is going:
42
+ * {@link bindFlight} hands every plan, route and overlay the slot takes to the engine, and writes
43
+ * every status the engine states to the slot. The verbs keep what names a studio: the gates, the
44
+ * refusals, the shot vocabulary and the recording a download saves.
45
+ */
46
+ interface VideoFlightHold {
47
+ readonly engine: VideoFlightEngine;
48
+ /** The wizard map the engine drives. */
49
+ readonly map: MapClient;
50
+ /**
51
+ * The camera planner the last dispatch read, which the engine's planner resolves through as
52
+ * it is called.
53
+ */
54
+ planner: CameraPlanner;
55
+ /** Lets go of the slot the engine follows. */
56
+ readonly release: () => void;
57
+ }
58
+
59
+ /**
60
+ * flights holds the flight of each studio, keyed by the UI store its wizard slot lives in.
61
+ *
62
+ * Keyed and not one module value, because two studios mounted in one realm share this module:
63
+ * with one value, a wizard opened in one studio stops the other's recording. Held weakly, so a
64
+ * studio that is let go takes its flight with it. An open and a close reset the engine and keep
65
+ * it: a flight they stopped gives the camera back later, and a seek of the wizard that follows
66
+ * waits for it.
67
+ */
68
+ const flights = new WeakMap<StudioToolContext["ui"], VideoFlightHold>();
69
+
70
+ /**
71
+ * What the video tools keep for one wizard beside its flight.
72
+ *
73
+ * - `recording` is the recording in progress, from the dispatch that began it to its answer, and
74
+ * whether a change to what it records stopped it. The preview verbs read it to refuse.
75
+ * - `recorded` is the last recording, kept so a download saves it without encoding again.
76
+ * - `sequence` counts the dispatches that take the camera from a preview: a preview, a play, a
77
+ * recording, and the open or close that ends the wizard. A preview reads it to tell its own
78
+ * flight from a newer one as the engine states each.
79
+ */
80
+ interface VideoWizardRun {
81
+ recorded: { blob: Blob; extension: string } | null;
82
+ recording: { outdated: boolean } | null;
83
+ sequence: number;
84
+ }
85
+
86
+ /** wizardRuns holds the {@link VideoWizardRun} of each studio, keyed as {@link flights} is. */
87
+ const wizardRuns = new WeakMap<StudioToolContext["ui"], VideoWizardRun>();
88
+
89
+ /** wizardRunOf reads the run of the studio a dispatch is for, starting it when it has none. */
90
+ const wizardRunOf = (ctx: StudioToolContext): VideoWizardRun => {
91
+ const held = wizardRuns.get(ctx.ui);
92
+ if (held) {
93
+ return held;
94
+ }
95
+
96
+ const run: VideoWizardRun = { recorded: null, recording: null, sequence: 0 };
97
+ wizardRuns.set(ctx.ui, run);
98
+
99
+ return run;
100
+ };
101
+
102
+ /**
103
+ * storeProgress writes a status the engine states to the wizard's slot, once the status schema
104
+ * takes it.
105
+ *
106
+ * A wizard map is a host's to supply, and the progress it reports is held by a type alone. A
107
+ * status the schema refuses (a fraction outside 0 to 1 or that is no number, a phase the wizard
108
+ * does not know) is dropped, and the status the wizard holds stands: a surface draws a bar from
109
+ * the fraction and words the phase.
110
+ */
111
+ const storeProgress = (ctx: StudioToolContext, report: VideoFlightStatus): void => {
112
+ const status = videoExportStatusSchema.safeParse(report);
113
+ if (status.success) {
114
+ ctx.ui.getState().setVideoExportStatus(status.data);
115
+ }
116
+ };
117
+
118
+ /**
119
+ * bindFlight keeps an engine and a studio's wizard slot in step, and answers what lets go of the
120
+ * slot.
121
+ *
122
+ * The engine takes the plan, the route, the overlay settings, its source and the glyph the slot
123
+ * holds, at once and on every write that changes one of them, so a flight that waits on a warm
124
+ * or on a stopped flight flies what the wizard shows once it lands. The slot takes each status
125
+ * the engine states, through {@link storeProgress}. A closed wizard hands nothing over: an open
126
+ * resets the engine and hands it the wizard it opens.
127
+ */
128
+ const bindFlight = (ctx: StudioToolContext, engine: VideoFlightEngine): (() => void) => {
129
+ const follow = (video: VideoExport, before: VideoExport | null): void => {
130
+ if (video.plan !== before?.plan) {
131
+ engine.setPlan(video.plan);
132
+ }
133
+
134
+ if (video.route !== before?.route) {
135
+ engine.setRoute(video.route);
136
+ }
137
+
138
+ if (video.profile !== before?.profile) {
139
+ engine.setProfile(video.profile ?? defaultVideoExportProfile);
140
+ }
141
+
142
+ if (video.profileSource !== before?.profileSource) {
143
+ engine.setProfileSource(video.profileSource ?? null);
144
+ }
145
+
146
+ if (video.activityGlyphUrl !== before?.activityGlyphUrl) {
147
+ engine.setActivityGlyph(video.activityGlyphUrl ?? null);
148
+ }
149
+ };
150
+
151
+ const held = ctx.ui.getState().videoExport;
152
+ if (held) {
153
+ follow(held, null);
154
+ }
155
+
156
+ let stated = engine.getSnapshot().status;
157
+ const unmirror = engine.subscribe(() => {
158
+ const { status } = engine.getSnapshot();
159
+ if (status !== stated) {
160
+ stated = status;
161
+ storeProgress(ctx, status);
162
+ }
163
+ });
164
+ const unfollow = ctx.ui.subscribe((state, previous) => {
165
+ if (state.videoExport) {
166
+ follow(state.videoExport, previous.videoExport);
167
+ }
168
+ });
169
+
170
+ return () => {
171
+ unmirror();
172
+ unfollow();
173
+ };
174
+ };
175
+
176
+ /**
177
+ * flightOf answers the engine that flies the wizard of the studio a dispatch is for, over the
178
+ * wizard map it reads, with the camera planner and the brand mark that dispatch reads.
179
+ *
180
+ * One engine for each studio, built the first time a verb flies the wizard and kept across its
181
+ * opens and closes. It is built again, and the one before it disposed, only when the dispatch
182
+ * reads another wizard map. A planner that changes keeps it: the engine resolves through the
183
+ * planner the last dispatch read, so a host whose seams are new objects on every render keeps the
184
+ * flight's warms, its memoized poses and the flights a seek waits on.
185
+ *
186
+ * Whether the recorded frames carry the Mountaya watermark is the wizard map's organization's
187
+ * to answer, as the map reads it: white label takes the mark off, and nothing the studio states
188
+ * does. The MARK only: the tile attribution the renderer draws is a licence obligation of its
189
+ * sources, and no organization removes it.
190
+ *
191
+ * @param video The open wizard, whose plan the engine is built on.
192
+ */
193
+ const flightOf = (
194
+ ctx: StudioToolContext,
195
+ map: MapClient,
196
+ video: VideoExport,
197
+ ): VideoFlightEngine => {
198
+ const planner = ctx.cameraPlanner ?? studioSeamAbsences.cameraPlanner;
199
+ const held = flights.get(ctx.ui);
200
+ if (held?.map === map) {
201
+ held.planner = planner;
202
+
203
+ return held.engine;
204
+ }
205
+
206
+ held?.release();
207
+ held?.engine.dispose();
208
+ const engine = new VideoFlightEngine({
209
+ map,
210
+ plan: video.plan,
211
+ planner: {
212
+ resolveSamples: (...args) => hold.planner.resolveSamples(...args),
213
+ resolveTrack: (...args) => hold.planner.resolveTrack(...args),
214
+ },
215
+ });
216
+ const hold: VideoFlightHold = { engine, map, planner, release: bindFlight(ctx, engine) };
217
+ flights.set(ctx.ui, hold);
218
+
219
+ return engine;
220
+ };
221
+
222
+ /**
223
+ * landIdle lands the wizard's status on idle, unless it reads idle already: the engine states
224
+ * idle as it stops a run, and the slot takes that status from it.
225
+ */
226
+ const landIdle = (ctx: StudioToolContext): void => {
227
+ if (ctx.ui.getState().videoExport?.status.kind !== "idle") {
228
+ ctx.ui.getState().setVideoExportStatus({ kind: "idle" });
229
+ }
230
+ };
231
+
232
+ /**
233
+ * voidRecording drops the last recording and stops one in progress.
234
+ *
235
+ * Every verb that changes the plan, the route or the overlay calls it. The file then differs
236
+ * from what the wizard shows, so a later download must never save it, and a recording still
237
+ * running is capturing a flight other than the one the wizard describes. The stopped recording
238
+ * answers `conflict`. The wizard is released at once: the status lands on idle here, and not
239
+ * when the recorder next reads its signal. Idempotent.
240
+ */
241
+ const voidRecording = (ctx: StudioToolContext): void => {
242
+ const run = wizardRunOf(ctx);
243
+ run.recorded = null;
244
+
245
+ const recording = run.recording;
246
+ if (!recording) {
247
+ return;
248
+ }
249
+
250
+ recording.outdated = true;
251
+ run.recording = null;
252
+ flights.get(ctx.ui)?.engine.stop();
253
+ landIdle(ctx);
254
+ };
255
+
256
+ /**
257
+ * endWizardRun ends the wizard an open or a close lets go of: the engine is reset, which stops
258
+ * its run, overtakes a seek still warming and forgets its warms, its memo and its paused flight,
259
+ * and the wizard's run is let go with the recording a download would save.
260
+ */
261
+ const endWizardRun = (ctx: StudioToolContext): void => {
262
+ const run = wizardRuns.get(ctx.ui);
263
+ if (run) {
264
+ // A preview of the wizard that ends reads no further status of the engine as its own.
265
+ run.sequence += 1;
266
+ wizardRuns.delete(ctx.ui);
267
+ }
268
+
269
+ flights.get(ctx.ui)?.engine.reset();
270
+ };
271
+
272
+ /** wizardClosed is what a verb that acts on the wizard answers while none is open. */
273
+ const wizardClosed: ToolFailure = {
274
+ code: "no-session",
275
+ error: "video wizard is not open",
276
+ ok: false,
277
+ };
278
+
279
+ /** mapNotMounted is what a verb that drives the wizard map answers while none is mounted. */
280
+ const mapNotMounted: ToolFailure = {
281
+ code: "no-map",
282
+ error: "video wizard map is not mounted",
283
+ ok: false,
284
+ };
285
+
286
+ /**
287
+ * routeMissing is what a flight answers while the wizard holds no route: its itinerary's detail
288
+ * has not loaded, or holds no line a camera can follow.
289
+ */
290
+ const routeMissing: ToolFailure = {
291
+ code: "not-found",
292
+ error: "no usable route geometry for the itinerary",
293
+ ok: false,
294
+ };
295
+
296
+ /**
297
+ * recordingInFlight is what a preview verb answers while a recording runs.
298
+ *
299
+ * A recording holds the camera from its first warm to its last frame, so a preview verb that
300
+ * took it would end the capture and the file with it. A recording ends on
301
+ * `studio.video.cancel`, on a close, on a newer recording, or on a change to what it records.
302
+ */
303
+ const recordingInFlight: ToolFailure = {
304
+ code: "edit-in-progress",
305
+ error: "a video recording is in progress: cancel it with studio.video.cancel first",
306
+ ok: false,
307
+ };
308
+
309
+ /**
310
+ * requireVideoExport refuses a viewer without the `video-export` entitlement, else answers null.
311
+ * Every video verb but the organization modes runs it first, so a viewer the host withholds the
312
+ * export from, or that viewer's agent, cannot drive the wizard at all.
313
+ */
314
+ const requireVideoExport = (ctx: StudioToolContext): ToolFailure | null =>
315
+ ctx.viewer.hasEntitlement("video-export") ? null : entitlementWithheld("video-export");
316
+
317
+ /**
318
+ * personalWizard refuses an open wizard whose itinerary the session knows to be PERSONAL, with
319
+ * `forbidden`, else answers null.
320
+ *
321
+ * A video belongs to an organization, so a personal itinerary is made into none: no verb that
322
+ * configures, runs or hands over its video goes through. `studio.video.open` refuses one, and the
323
+ * open lets an unknown owner through, so the record can land after it: each verb reads the owner
324
+ * again. A wizard that is not open names no itinerary and is refused by the verb itself.
325
+ */
326
+ const personalWizard = (ctx: StudioToolContext): ToolFailure | null => {
327
+ const itineraryId = ctx.ui.getState().videoExport?.itineraryId;
328
+
329
+ return itineraryId === undefined ? null : requireOrganizationOwned(ctx, itineraryId, "recorded");
330
+ };
331
+
332
+ /**
333
+ * requireExportable refuses a verb that configures, runs or hands over the open wizard's video,
334
+ * else answers null: a viewer without `video-export` ({@link requireVideoExport}), then a personal
335
+ * itinerary ({@link personalWizard}). The entitlement comes first, since it is the reason that
336
+ * applies to the viewer whatever itinerary the wizard holds.
337
+ *
338
+ * Each such verb states it as its `precondition` and runs it again first in its handler.
339
+ */
340
+ const requireExportable = (ctx: StudioToolContext): ToolFailure | null =>
341
+ requireVideoExport(ctx) ?? personalWizard(ctx);
342
+
343
+ /**
344
+ * requireOrganizationModes refuses a verb of the organization modes, else answers null. The verbs
345
+ * that author a bespoke camera plan (director mode, every shot edit, orbit, a custom output) state
346
+ * it as their `precondition` and run it again first, the boundary the wizard's Director card
347
+ * states in the UI. Two refusals, in order:
348
+ *
349
+ * - A viewer without the `video-organization-modes` entitlement is refused with
350
+ * `upgrade-required`. A second entitlement rather than a stricter reading of the export: a
351
+ * host grants the two independently, and the viewer seam answers each on its own.
352
+ * - A personal itinerary is refused with `forbidden` ({@link personalWizard}).
353
+ */
354
+ const requireOrganizationModes = (ctx: StudioToolContext): ToolFailure | null =>
355
+ ctx.viewer.hasEntitlement("video-organization-modes")
356
+ ? personalWizard(ctx)
357
+ : entitlementWithheld("video-organization-modes");
358
+
359
+ /**
360
+ * openRefusal is what `studio.video.open` refuses before it runs: a viewer without `video-export`
361
+ * ({@link requireVideoExport}), then an itinerary the session knows to be personal, since a video
362
+ * belongs to an organization ({@link personalWizard}). A gate for the UI and for an agent, not the
363
+ * security boundary: the API publishes no personal itinerary, so a wizard over one would mount
364
+ * over a blank map.
365
+ */
366
+ const openRefusal = (
367
+ ctx: StudioToolContext,
368
+ input: StudioToolInputs["studio.video.open"],
369
+ ): ToolFailure | null =>
370
+ requireVideoExport(ctx) ?? requireOrganizationOwned(ctx, input.itineraryId, "recorded");
371
+
372
+ /**
373
+ * modeRefusal is what `studio.video.mode.set` refuses before it runs: director is one of the
374
+ * organization modes, and a preset comes with the export itself.
375
+ */
376
+ const modeRefusal = (
377
+ ctx: StudioToolContext,
378
+ input: StudioToolInputs["studio.video.mode.set"],
379
+ ): ToolFailure | null =>
380
+ input.mode === "director" ? requireOrganizationModes(ctx) : requireExportable(ctx);
381
+
382
+ /**
383
+ * currentPlan reads the Camera Plan off the open wizard, or null when the wizard
384
+ * is closed. The plan-editing tools read it to derive their next plan; absent a
385
+ * wizard they return a structured failure rather than mutating nothing.
386
+ */
387
+ const currentPlan = (ctx: StudioToolContext): CameraPlan | null =>
388
+ ctx.ui.getState().videoExport?.plan ?? null;
389
+
390
+ /**
391
+ * sameProfileSource reports whether two overlay sources hold the same content, or are both
392
+ * absent.
393
+ *
394
+ * By content, for the reason `sameRouteContent` compares routes by content: the route-sync hook
395
+ * builds a fresh source for each dispatch. Both arrive through the one contract, which states
396
+ * their members in one order, so two sources hold the same content exactly when they serialize
397
+ * to the same text.
398
+ */
399
+ const sameProfileSource = (a: ProfileSource | null, b: ProfileSource | null): boolean =>
400
+ a === b || (a !== null && b !== null && JSON.stringify(a) === JSON.stringify(b));
401
+
402
+ /**
403
+ * recordingStopped answers a recording that was stopped before it produced a file.
404
+ *
405
+ * One a change to the plan, the route or the overlay stopped ({@link voidRecording}) answers
406
+ * `conflict`: it lost to a newer state of what it records, and recording again takes that
407
+ * state. One a cancel, a close or a newer recording stopped answers `canceled`, the code for a
408
+ * run its caller ended before it produced its answer: nothing failed, so a surface says the
409
+ * recording was cancelled and not that something went wrong.
410
+ */
411
+ const recordingStopped = (recording: { outdated: boolean }): ToolFailure =>
412
+ recording.outdated
413
+ ? {
414
+ code: "conflict",
415
+ error: "recording stopped: the plan, the route or the overlay changed while it ran",
416
+ ok: false,
417
+ }
418
+ : { code: "canceled", error: "recording cancelled", ok: false };
419
+
420
+ /**
421
+ * recordingUnavailable answers a recording the wizard map could not start, which nobody
422
+ * cancelled: a map with no recorder, no drawing buffer to read, a canvas under the minimum
423
+ * size, a first frame that read black. The recorder states it as `reason: "unavailable"`
424
+ * beside the cancel's shape, and `no-map` is the code for a map that cannot do what the verb
425
+ * drives it to.
426
+ */
427
+ const recordingUnavailable: ToolFailure = {
428
+ code: "no-map",
429
+ error: "recording unavailable: the wizard map could not start a capture",
430
+ ok: false,
431
+ };
432
+
433
+ /**
434
+ * previewStopped answers a preview that a pause, a stop, a cancel, a close or a newer run
435
+ * ended while it was still warming. Nothing flew, and that is what its caller asked for.
436
+ */
437
+ const previewStopped: ToolResult<undefined> = {
438
+ ok: true,
439
+ summary: "Stopped the video preview before it flew.",
440
+ };
441
+
442
+ /**
443
+ * startPreview is `studio.video.preview.start` and `studio.video.preview.play` past their gate:
444
+ * the engine's `preview` or `play` over the wizard's plan on the wizard map, with no frame
445
+ * captured.
446
+ *
447
+ * `start` flies from the first frame. `play` resumes a flight `studio.video.preview.pause`
448
+ * stopped in the air, flies on from the frame a seek parked the camera on, and flies from the
449
+ * first frame when there is neither. The park a plan's refresh makes is a seek followed by a
450
+ * pause (`previewRefreshDisposition`), which lands the status on idle with no flight paused, so
451
+ * the next play flies the whole plan. The flight is of the plan the wizard holds once the warms
452
+ * have settled, and every exit lands the status on idle unless a newer run or a stop already
453
+ * did. A map whose `previewPoses` rejects with what a frame threw is answered as that throw,
454
+ * which the bus answers as `internal`.
455
+ *
456
+ * It answers a structured failure while a recording runs, while the wizard map is not mounted,
457
+ * while the wizard is closed and while it holds no route, and {@link previewStopped} for a
458
+ * preview stopped before it flew.
459
+ */
460
+ const startPreview = async (
461
+ ctx: StudioToolContext,
462
+ options: { resume: boolean },
463
+ ): Promise<ToolResult<undefined>> => {
464
+ const map = ctx.videoMap;
465
+ if (!map) {
466
+ return mapNotMounted;
467
+ }
468
+
469
+ const run = wizardRunOf(ctx);
470
+ if (run.recording) {
471
+ return recordingInFlight;
472
+ }
473
+
474
+ const video = ctx.ui.getState().videoExport;
475
+ if (!video) {
476
+ return wizardClosed;
477
+ }
478
+
479
+ if (!video.route) {
480
+ return routeMissing;
481
+ }
482
+
483
+ const engine = flightOf(ctx, map, video);
484
+ run.sequence += 1;
485
+ const sequence = run.sequence;
486
+ // Where this flight starts, as the engine states it once the flight is in the air. Read while
487
+ // no newer dispatch has taken the camera, so another flight's start is never taken for it.
488
+ let from: number | null = null;
489
+ const unwatch = engine.subscribe(() => {
490
+ const { status } = engine.getSnapshot();
491
+ if (from === null && run.sequence === sequence && status.kind === "previewing") {
492
+ from = status.fraction;
493
+ }
494
+ });
495
+
496
+ let outcome: Awaited<ReturnType<VideoFlightEngine["preview"]>>;
497
+ try {
498
+ outcome = await (options.resume ? engine.play() : engine.preview());
499
+ } finally {
500
+ unwatch();
501
+ }
502
+
503
+ if (!outcome.ok) {
504
+ switch (outcome.reason) {
505
+ case "failed":
506
+ throw outcome.error;
507
+ case "no-map":
508
+ return mapNotMounted;
509
+ case "no-route":
510
+ return routeMissing;
511
+ case "aborted":
512
+ if (from === null) {
513
+ return previewStopped;
514
+ }
515
+ }
516
+ }
517
+
518
+ if (from !== null && from > 0) {
519
+ return { ok: true, summary: "Resumed the video preview." };
520
+ }
521
+
522
+ return {
523
+ ok: true,
524
+ summary: options.resume ? "Played the video preview." : "Previewed the video flight.",
525
+ };
526
+ };
527
+
528
+ /**
529
+ * presetPlan builds the plan for a non-director preset the wizard switches to,
530
+ * preserving the current output and target duration so a mode change never resets
531
+ * the encoder settings or the length. The generated plan's output is overwritten
532
+ * with the preserved one so the user's format/aspect choices survive the switch.
533
+ * Director mode is handled separately (it seeds a neutral empty plan and needs no
534
+ * route), so this only takes the preset modes that have a generator.
535
+ */
536
+ const presetPlan = (
537
+ mode: Exclude<CameraPlan["mode"], "director">,
538
+ previous: CameraPlan,
539
+ route: RouteGeometry,
540
+ ): CameraPlan => ({
541
+ ...cameraPlanGenerators[mode](route, { targetDurationMs: previous.targetDurationMs }),
542
+ output: previous.output,
543
+ });
544
+
545
+ /**
546
+ * SHOT_ID_PREFIX is the stem the camera-edit tools mint shot ids from. A run
547
+ * counter keeps each minted id unique within a session so two added shots (or two
548
+ * orbits) never collide, and the prefix marks an interactively-authored shot apart
549
+ * from a preset's deterministic `${mode}-${index}` ids.
550
+ */
551
+ const SHOT_ID_PREFIX = "shot";
552
+
553
+ /** shotCounter increments per minted shot id so interactively-added shots never collide. */
554
+ let shotCounter = 0;
555
+
556
+ /** mintShotId returns a fresh, unique shot id for an interactively-added keyframe. */
557
+ const mintShotId = (): string => {
558
+ shotCounter += 1;
559
+
560
+ return `${SHOT_ID_PREFIX}-${shotCounter}`;
561
+ };
562
+
563
+ /**
564
+ * ORBIT_PROGRESS_SPAN is the tiny route-progress window an orbit's swept
565
+ * keyframes are laid across, so the orbit's fixed-bearing shots have distinct
566
+ * ascending `at` values (the spline needs unique knots) while the camera barely
567
+ * moves along the route, reading as a rotation in place rather than a travel.
568
+ */
569
+ const ORBIT_PROGRESS_SPAN = 0.0005;
570
+
571
+ /**
572
+ * ORBIT_STEP_DEG is the bearing increment between an orbit's swept keyframes. It
573
+ * is below 180° so the circular bearing interpolation advances each leg in the
574
+ * intended direction (a step of exactly 180° is ambiguous, and a larger step
575
+ * would interpolate the short way backward), so stacking these steps sweeps a
576
+ * full turn the chosen way.
577
+ */
578
+ const ORBIT_STEP_DEG = 120;
579
+
580
+ /**
581
+ * orbitShots expands an orbit request into the run of fixed-bearing keyframes the
582
+ * resolver sweeps between: `turns` full rotations stepped by ORBIT_STEP_DEG,
583
+ * clockwise or counter-clockwise, laid across a tiny progress window starting at
584
+ * `at` so the knots stay unique while the camera holds its ground. The dwell is
585
+ * split evenly across the steps so the whole sweep spans `dwellMs`.
586
+ *
587
+ * An orbit asked for within the window's width of the route's end is laid back from the end,
588
+ * so its keyframes stay distinct and ascending there too: started where it was asked, every
589
+ * one past the end would be held at 1, on one knot.
590
+ */
591
+ const orbitShots = (
592
+ input: z.infer<(typeof studioToolContracts)["studio.video.orbit"]["input"]>,
593
+ ): CameraShot[] => {
594
+ const steps = Math.max(1, Math.round((360 * input.turns) / ORBIT_STEP_DEG));
595
+ const direction = input.clockwise ? 1 : -1;
596
+ const holdPerStep = input.dwellMs / (steps + 1);
597
+ const start = Math.min(input.at, 1 - ORBIT_PROGRESS_SPAN);
598
+ const shots: CameraShot[] = [];
599
+ for (let step = 0; step <= steps; step += 1) {
600
+ const fraction = Math.min(1, start + (ORBIT_PROGRESS_SPAN * step) / Math.max(1, steps));
601
+ const bearing = (((direction * step * ORBIT_STEP_DEG) % 360) + 360) % 360;
602
+ shots.push({
603
+ at: fraction,
604
+ bearingDeg: bearing,
605
+ bearingMode: "value",
606
+ holdMs: holdPerStep,
607
+ id: mintShotId(),
608
+ pitchDeg: input.pitchDeg,
609
+ speedScale: 1,
610
+ zoom: input.zoom,
611
+ });
612
+ }
613
+
614
+ return shots;
615
+ };
616
+
617
+ /**
618
+ * open opens the video export wizard for an itinerary (optionally narrowed to one
619
+ * segment): it seeds the videoExport slot with a default `smart` plan and a null
620
+ * route, then starts on the format step. The route is sourced separately (the
621
+ * wizard fetches the exported itinerary's detail by id and dispatches it through
622
+ * route.set once it loads), so the wizard is decoupled from the studio's active
623
+ * itinerary (it is opened from a list row, which is not necessarily the active
624
+ * one). The Smart plan opens with no shots; route.set regenerates it the moment
625
+ * the detail lands, so the preview and the presets have a real flight to resolve.
626
+ * Any prior run is stopped and the last recording dropped, so a reopen starts clean.
627
+ * Refuses before it runs ({@link openRefusal}): a viewer without `video-export`, then an
628
+ * itinerary the session knows to be personal.
629
+ */
630
+ export const open: StudioToolDefinition<"studio.video.open"> = {
631
+ handler: (ctx, input) => {
632
+ const gate = openRefusal(ctx, input);
633
+ if (gate) {
634
+ return gate;
635
+ }
636
+
637
+ // A fresh wizard warms its own route and resolves its flights from scratch: the engine is
638
+ // reset, which stops the run before it, overtakes a seek still warming for it, and lets go
639
+ // of its warms, its memo and its paused flight. The flight it stopped still gives the
640
+ // camera back to the engine, for the seek that follows. The recording goes with the wizard.
641
+ endWizardRun(ctx);
642
+ // Built through the slot's own schema, which fills what an open leaves out: no route, no
643
+ // profile source and no glyph yet, and the profile block on its seed.
644
+ ctx.ui.getState().setVideoExport(
645
+ videoExportSchema.parse({
646
+ itineraryId: input.itineraryId,
647
+ plan: { mode: "smart" },
648
+ segmentId: input.segmentId ?? null,
649
+ status: { kind: "idle" },
650
+ step: "format",
651
+ }),
652
+ );
653
+
654
+ return {
655
+ ok: true,
656
+ summary: `Opened the video export wizard for itinerary ${input.itineraryId}.`,
657
+ };
658
+ },
659
+ precondition: (ctx, input) => openRefusal(ctx, input),
660
+ };
661
+
662
+ /**
663
+ * setRoute stores the flattened route the open wizard's Camera Plan resolves
664
+ * against, then, when the plan is on a preset (any non-director mode) and a
665
+ * non-null route arrived, regenerates the plan from that route (preserving the
666
+ * output and target duration) so the preview has a real flight to fly. The wizard
667
+ * fetches its exported itinerary's detail by id, flattens it to a route, and
668
+ * dispatches this, which is how the feature stays decoupled from the studio's
669
+ * active itinerary. Alongside the route it stores the plan-independent
670
+ * `profileSource` (the per-segment elevation/surface/slope analysis the route-sync
671
+ * hook derives from the same itinerary detail), so the live profile overlay can
672
+ * sample it per frame without reaching back into the itinerary at record time; an
673
+ * absent source clears the slot. Director mode keeps its authored shots untouched
674
+ * (they are not derived from the route). A null route just clears the slot (the
675
+ * detail is still loading or has no usable line). Feature-gated like the rest of
676
+ * the wizard; a no-op-with-failure when the wizard is closed.
677
+ *
678
+ * A route equal to the stored one (`sameRouteContent`: every vertex, elevation and jump) updates
679
+ * the profile source and the glyph alone. The stored route, its memoized flights and the plan
680
+ * stay as they are, and so does the last recording when the glyph and the source hold what the
681
+ * wizard already held ({@link sameProfileSource}). A glyph or a source that differs drops the
682
+ * last recording and stops one in progress, as any other route does when it replaces the stored
683
+ * one.
684
+ *
685
+ * Another route also stops a preview that is flying the one before it, and lands the status on
686
+ * idle: the camera would go on flying a route the wizard has let go of, under a status that
687
+ * says so. A preview still warming flies the route that arrived. A `parked` status lands on
688
+ * idle as well: the frame it states is one of the route that left, so the next
689
+ * `studio.video.preview.play` flies the route that arrived from its first frame.
690
+ */
691
+ export const setRoute: StudioToolDefinition<"studio.video.route.set"> = {
692
+ handler: (ctx, input) => {
693
+ const gate = requireVideoExport(ctx);
694
+ if (gate) {
695
+ return gate;
696
+ }
697
+
698
+ const plan = currentPlan(ctx);
699
+ if (!plan) {
700
+ return wizardClosed;
701
+ }
702
+
703
+ // Idempotent on route CONTENT. The route-sync hook resolves the activity glyph from a
704
+ // separate catalog query, so on a cold cache it re-dispatches a SECOND route.set with a
705
+ // fresh but content-identical route object once the glyph resolves. Compare the incoming
706
+ // route's content against the stored one BEFORE any mutation.
707
+ const currentRoute = ctx.ui.getState().videoExport?.route ?? null;
708
+ const sameContent =
709
+ currentRoute !== null && input.route !== null && sameRouteContent(currentRoute, input.route);
710
+
711
+ if (sameContent) {
712
+ // A content-identical re-dispatch updates ONLY the glyph and profile source. It must
713
+ // not drop the recording or regenerate the plan, and the stored route object is left as
714
+ // is: the engine keeps its warms and its memo for a route whose content holds, so the
715
+ // DEM-heavy flight warm and a full resolve do not run again.
716
+ const held = ctx.ui.getState().videoExport;
717
+ const profileSource = input.profileSource ?? null;
718
+ const activityGlyphUrl = input.activityGlyphUrl ?? null;
719
+ // A recording is handed the glyph and the source as it begins. One that holds another
720
+ // glyph or another source than the wizard shows is not the wizard's: the file is
721
+ // dropped and a run in progress is stopped, as for any other change to the overlay.
722
+ if (
723
+ (held?.activityGlyphUrl ?? null) !== activityGlyphUrl ||
724
+ !sameProfileSource(held?.profileSource ?? null, profileSource)
725
+ ) {
726
+ voidRecording(ctx);
727
+ }
728
+
729
+ ctx.ui.getState().setVideoExportProfileSource(profileSource);
730
+ ctx.ui.getState().setVideoExportActivityGlyph(activityGlyphUrl);
731
+
732
+ return { ok: true, summary: "Updated the video route glyph." };
733
+ }
734
+
735
+ voidRecording(ctx);
736
+ // The engine follows the route stored here: another route's flights and warms are no use
737
+ // to it, and neither is a flight paused over the one that leaves. A preview in the air is
738
+ // stopped and a `parked` status lands on idle, since each states a frame of the route that
739
+ // leaves. A preview or a seek still warming flies, or parks on, the route stored here.
740
+ ctx.ui.getState().setVideoExportRoute(input.route);
741
+ // Store the plan-independent profile source alongside the route so the overlay
742
+ // samples it per frame at record time; the route-sync hook derives it from the
743
+ // same itinerary detail, and an absent source clears the slot.
744
+ ctx.ui.getState().setVideoExportProfileSource(input.profileSource ?? null);
745
+ // Store the resolved activity glyph URL the moving dot masks; the route-sync hook
746
+ // resolves it from the same itinerary's activity, and an absent glyph clears the
747
+ // slot (a plain disc). It rides the route-set payload so the marker, the route, and
748
+ // the overlay source all land together, decoupled from the active itinerary.
749
+ ctx.ui.getState().setVideoExportActivityGlyph(input.activityGlyphUrl ?? null);
750
+
751
+ // Regenerate a preset plan from the freshly-loaded route so the preview and
752
+ // the chosen preset reflect the real flight; director mode authors its shots
753
+ // explicitly, so its plan is left as-is, and a null route has nothing to
754
+ // regenerate from.
755
+ if (input.route && plan.mode !== "director") {
756
+ ctx.ui.getState().setVideoExportPlan(presetPlan(plan.mode, plan, input.route));
757
+ }
758
+
759
+ return { ok: true, summary: "Set the video route geometry." };
760
+ },
761
+ };
762
+
763
+ /**
764
+ * close closes the video export wizard: it stops any in-flight preview or
765
+ * recording, drops the last recording, and clears the videoExport slot. Gated on
766
+ * `video-export` for consistency with open (a viewer without it has no wizard to close).
767
+ */
768
+ export const close: StudioToolDefinition<"studio.video.close"> = {
769
+ handler: (ctx) => {
770
+ const gate = requireVideoExport(ctx);
771
+ if (gate) {
772
+ return gate;
773
+ }
774
+
775
+ // The run is stopped, a seek still warming is overtaken, a flight warm still sweeping is
776
+ // ended, and the wizard's run is let go.
777
+ endWizardRun(ctx);
778
+ ctx.ui.getState().setVideoExport(null);
779
+
780
+ return { ok: true, summary: "Closed the video export wizard." };
781
+ },
782
+ };
783
+
784
+ /**
785
+ * setStep switches the wizard's active step (format / camera / profile /
786
+ * review). Feature-gated. Returns a structured failure when the wizard is closed.
787
+ */
788
+ export const setStep: StudioToolDefinition<"studio.video.step.set"> = {
789
+ handler: (ctx, input) => {
790
+ const gate = requireVideoExport(ctx);
791
+ if (gate) {
792
+ return gate;
793
+ }
794
+
795
+ if (!currentPlan(ctx)) {
796
+ return wizardClosed;
797
+ }
798
+
799
+ ctx.ui.getState().setVideoExportStep(input.step);
800
+
801
+ return { ok: true, summary: `Switched the video wizard to the ${input.step} step.` };
802
+ },
803
+ };
804
+
805
+ /**
806
+ * setMode switches the camera mode and regenerates the plan from it, preserving
807
+ * the output and target duration. A preset (any non-director mode: Smart,
808
+ * Cinematic, Drone, Helicopter, Chase, Overview) needs `video-export`; switching to
809
+ * `director` needs `video-organization-modes`, the entitlement that covers the AI Director.
810
+ * The preset regenerate reads the route off the wizard
811
+ * slice (set once the itinerary detail loads); when the route is present it
812
+ * regenerates the shots from it, and when it has not loaded yet it still switches
813
+ * the mode with empty shots so the radio selection always lands (the preview
814
+ * simply resolves nothing until route.set arrives). The entitlement gate is the real
815
+ * boundary.
816
+ *
817
+ * Naming the mode the plan already has changes nothing: the plan keeps its reference, a
818
+ * director's authored shots stay, and so does the last recording. A model that restates the
819
+ * mode at the head of a turn therefore empties no shot list.
820
+ */
821
+ export const setMode: StudioToolDefinition<"studio.video.mode.set"> = {
822
+ handler: (ctx, input) => {
823
+ const gate = modeRefusal(ctx, input);
824
+ if (gate) {
825
+ return gate;
826
+ }
827
+
828
+ const plan = currentPlan(ctx);
829
+ if (!plan) {
830
+ return wizardClosed;
831
+ }
832
+
833
+ if (plan.mode === input.mode) {
834
+ return { ok: true, summary: `The video camera is already in ${input.mode} mode.` };
835
+ }
836
+
837
+ voidRecording(ctx);
838
+ if (input.mode === "director") {
839
+ // Director seeds a neutral empty plan an explicit shot sequence fills; it
840
+ // needs no route, and the preserved output/duration carry over.
841
+ const seeded = neutralDirectorPlan({ targetDurationMs: plan.targetDurationMs });
842
+ ctx.ui.getState().setVideoExportPlan({ ...seeded, output: plan.output });
843
+
844
+ return { ok: true, summary: "Switched the video camera to Director mode." };
845
+ }
846
+
847
+ // Regenerate the shots from the slice route when it has loaded; otherwise
848
+ // switch the mode and clear the shots so the radio selection always lands:
849
+ // route.set regenerates the shots the moment the itinerary detail arrives.
850
+ const route = ctx.ui.getState().videoExport?.route ?? null;
851
+ const next = route
852
+ ? presetPlan(input.mode, plan, route)
853
+ : { ...plan, mode: input.mode, shots: [] };
854
+ ctx.ui.getState().setVideoExportPlan(next);
855
+
856
+ return { ok: true, summary: `Switched the video camera to ${input.mode} mode.` };
857
+ },
858
+ precondition: (ctx, input) => modeRefusal(ctx, input),
859
+ };
860
+
861
+ /**
862
+ * setDuration sets the plan's whole-flight target duration, leaving the mode,
863
+ * shots, and output untouched (shots are anchored by progress, not wall-clock, so
864
+ * retiming never invalidates them). Feature-gated. Returns a structured failure
865
+ * when the wizard is closed.
866
+ */
867
+ export const setDuration: StudioToolDefinition<"studio.video.duration.set"> = {
868
+ handler: (ctx, input) => {
869
+ const gate = requireExportable(ctx);
870
+ if (gate) {
871
+ return gate;
872
+ }
873
+
874
+ const plan = currentPlan(ctx);
875
+ if (!plan) {
876
+ return wizardClosed;
877
+ }
878
+
879
+ voidRecording(ctx);
880
+ ctx.ui.getState().setVideoExportPlan({ ...plan, targetDurationMs: input.targetDurationMs });
881
+
882
+ return { ok: true, summary: `Set the video duration to ${input.targetDurationMs} ms.` };
883
+ },
884
+ precondition: (ctx) => requireExportable(ctx),
885
+ };
886
+
887
+ /**
888
+ * setOutput merges a partial encoder-output reconfiguration over the plan's
889
+ * current output (format, resolution, fps, aspect, bitrate). Needs
890
+ * `video-organization-modes`: the custom encoder matrix is one of them. Returns a structured
891
+ * failure when the wizard is closed.
892
+ *
893
+ * The bitrate follows the tiers. A change to the resolution, the frame rate or the quality
894
+ * that names no bitrate stores the one `bitrateForOutput` gives the merged output, so the
895
+ * recording is encoded at the fidelity the plan states whoever dispatched the change, and
896
+ * never at the bitrate an earlier preset or tier left behind. A bitrate the caller names is
897
+ * kept as named, and a change that moves no tier (the aspect, the container, the preset's
898
+ * name) leaves the bitrate as it is.
899
+ */
900
+ export const setOutput: StudioToolDefinition<"studio.video.output.set"> = {
901
+ handler: (ctx, input) => {
902
+ const gate = requireOrganizationModes(ctx);
903
+ if (gate) {
904
+ return gate;
905
+ }
906
+
907
+ const plan = currentPlan(ctx);
908
+ if (!plan) {
909
+ return wizardClosed;
910
+ }
911
+
912
+ // Member by member and not by a spread of the input: a member the caller states as
913
+ // `undefined` is one it left out, and a spread would write the `undefined` over the plan's.
914
+ const held = plan.output;
915
+ const merged: CameraOutput = {
916
+ ...held,
917
+ aspect: input.aspect ?? held.aspect,
918
+ format: input.format ?? held.format,
919
+ fps: input.fps ?? held.fps,
920
+ preset: input.preset ?? held.preset,
921
+ quality: input.quality ?? held.quality,
922
+ resolution: input.resolution ?? held.resolution,
923
+ ...(input.bitrateMbps === undefined ? {} : { bitrateMbps: input.bitrateMbps }),
924
+ };
925
+ const movesTier =
926
+ input.resolution !== undefined || input.fps !== undefined || input.quality !== undefined;
927
+ const output: CameraOutput =
928
+ input.bitrateMbps === undefined && movesTier
929
+ ? {
930
+ ...merged,
931
+ bitrateMbps: bitrateForOutput(merged.resolution, merged.fps, merged.quality),
932
+ }
933
+ : merged;
934
+
935
+ voidRecording(ctx);
936
+ ctx.ui.getState().setVideoExportPlan({ ...plan, output });
937
+
938
+ return { ok: true, summary: "Updated the video encoder output." };
939
+ },
940
+ precondition: (ctx) => requireOrganizationModes(ctx),
941
+ };
942
+
943
+ /**
944
+ * setPreset applies a ready-made framing preset (Vertical / Widescreen / Square) to
945
+ * the plan's output: it spreads the videoPresets template (format, resolution,
946
+ * aspect, fps, bitrate) over the current output and stamps `preset` so a later read
947
+ * knows which template seeded it, leaving the mode, shots, and target duration
948
+ * untouched. The templates share one broadcast recipe (1080p H.264 30 fps,
949
+ * 12 Mbps) and differ only in frame shape, so a preset change reframes the map
950
+ * without touching the fidelity. The merged output is parsed again through
951
+ * cameraOutputSchema (then the whole plan through cameraPlanSchema) so a stamped
952
+ * preset can never drift the encoder configuration out of its validated shape. A
953
+ * fresh plan object is minted so the preview's plan-ref watcher restarts the fly,
954
+ * the same way the other plan mutators do. Refused by {@link requireExportable}: presets come
955
+ * with the export, while the Custom encoder matrix behind output.set needs the organization
956
+ * modes. Returns a structured failure when the wizard is closed.
957
+ */
958
+ export const setPreset: StudioToolDefinition<"studio.video.preset.set"> = {
959
+ handler: (ctx, input) => {
960
+ const gate = requireExportable(ctx);
961
+ if (gate) {
962
+ return gate;
963
+ }
964
+
965
+ const plan = currentPlan(ctx);
966
+ if (!plan) {
967
+ return wizardClosed;
968
+ }
969
+
970
+ // Spread the preset template over the current output and stamp the preset
971
+ // name, then re-parse so the merged output stays inside cameraOutputSchema.
972
+ const output: CameraOutput = cameraOutputSchema.parse({
973
+ ...plan.output,
974
+ ...videoPresets[input.preset],
975
+ preset: input.preset,
976
+ });
977
+ // Mint a fresh plan through the schema so the preview's plan-ref watcher sees a
978
+ // new reference and restarts, leaving mode/shots/targetDurationMs as they were.
979
+ const next = cameraPlanSchema.parse({ ...plan, output });
980
+ voidRecording(ctx);
981
+ ctx.ui.getState().setVideoExportPlan(next);
982
+
983
+ return { ok: true, summary: `Applied the ${input.preset} video preset.` };
984
+ },
985
+ precondition: (ctx) => requireExportable(ctx),
986
+ };
987
+
988
+ /**
989
+ * setProfileToggle flips the live profile overlay on or off: whether the
990
+ * Tour-de-France-style data band is composited into the preview and the recording.
991
+ * It merges just the `enabled` flag over the wizard's profile settings, so the
992
+ * design, units, and language the user already chose survive the toggle.
993
+ * Refused by {@link requireExportable}: the overlay ships with the export. Returns a structured
994
+ * failure when the wizard is closed.
995
+ */
996
+ export const setProfileToggle: StudioToolDefinition<"studio.video.profile.toggle"> = {
997
+ handler: (ctx, input) => {
998
+ const gate = requireExportable(ctx);
999
+ if (gate) {
1000
+ return gate;
1001
+ }
1002
+
1003
+ if (!currentPlan(ctx)) {
1004
+ return wizardClosed;
1005
+ }
1006
+
1007
+ voidRecording(ctx);
1008
+ ctx.ui.getState().setVideoExportProfile({ enabled: input.enabled });
1009
+
1010
+ return {
1011
+ ok: true,
1012
+ summary: `${input.enabled ? "Enabled" : "Disabled"} the video profile overlay.`,
1013
+ };
1014
+ },
1015
+ precondition: (ctx) => requireExportable(ctx),
1016
+ };
1017
+
1018
+ /**
1019
+ * setProfileDesign switches the live profile overlay's design: `graph` (the full
1020
+ * Tour-de-France elevation curve with a moving readout), `strip` (the compact
1021
+ * stats band), or `minimal` (a single distance-to-go chip). It merges just the
1022
+ * `design` field over the wizard's profile settings so the enable flag, units,
1023
+ * and language are left as they were. Feature-gated. Returns a structured failure
1024
+ * when the wizard is closed.
1025
+ */
1026
+ export const setProfileDesign: StudioToolDefinition<"studio.video.profile.design.set"> = {
1027
+ handler: (ctx, input) => {
1028
+ const gate = requireExportable(ctx);
1029
+ if (gate) {
1030
+ return gate;
1031
+ }
1032
+
1033
+ if (!currentPlan(ctx)) {
1034
+ return wizardClosed;
1035
+ }
1036
+
1037
+ voidRecording(ctx);
1038
+ ctx.ui.getState().setVideoExportProfile({ design: input.design });
1039
+
1040
+ return { ok: true, summary: `Set the video profile design to ${input.design}.` };
1041
+ },
1042
+ precondition: (ctx) => requireExportable(ctx),
1043
+ };
1044
+
1045
+ /**
1046
+ * setProfileUnits sets the video-scoped units the profile overlay formats with:
1047
+ * the `length` unit (metric/imperial), the `pace` form (per-time/per-distance) and
1048
+ * the `slope` unit (degrees/percentage). They are local to the export: the overlay
1049
+ * reads them straight into the param-based formatters, never touching the global
1050
+ * preferences or the map. It merges all three fields over the wizard's profile
1051
+ * settings, leaving the enable flag, design, and language untouched. Feature-gated.
1052
+ * Returns a structured failure when the wizard is closed.
1053
+ */
1054
+ export const setProfileUnits: StudioToolDefinition<"studio.video.profile.units.set"> = {
1055
+ handler: (ctx, input) => {
1056
+ const gate = requireExportable(ctx);
1057
+ if (gate) {
1058
+ return gate;
1059
+ }
1060
+
1061
+ if (!currentPlan(ctx)) {
1062
+ return wizardClosed;
1063
+ }
1064
+
1065
+ voidRecording(ctx);
1066
+ ctx.ui
1067
+ .getState()
1068
+ .setVideoExportProfile({ length: input.length, pace: input.pace, slope: input.slope });
1069
+
1070
+ return { ok: true, summary: "Set the video profile units." };
1071
+ },
1072
+ precondition: (ctx) => requireExportable(ctx),
1073
+ };
1074
+
1075
+ /**
1076
+ * setProfileLanguage sets the video-scoped language the profile overlay localizes
1077
+ * its labels in. Like the units it is local to the export, merged as the sole
1078
+ * `language` field over the wizard's profile settings so the enable flag, design,
1079
+ * and units are left as they were. Feature-gated. Returns a structured failure when the
1080
+ * wizard is closed.
1081
+ */
1082
+ export const setProfileLanguage: StudioToolDefinition<"studio.video.profile.language.set"> = {
1083
+ handler: (ctx, input) => {
1084
+ const gate = requireExportable(ctx);
1085
+ if (gate) {
1086
+ return gate;
1087
+ }
1088
+
1089
+ if (!currentPlan(ctx)) {
1090
+ return wizardClosed;
1091
+ }
1092
+
1093
+ voidRecording(ctx);
1094
+ ctx.ui.getState().setVideoExportProfile({ language: input.language });
1095
+
1096
+ return { ok: true, summary: `Set the video profile language to ${input.language}.` };
1097
+ },
1098
+ precondition: (ctx) => requireExportable(ctx),
1099
+ };
1100
+
1101
+ /**
1102
+ * addShot inserts a new keyframe into the plan (the tool mints its id), keeping
1103
+ * the shot list sorted by progress. Needs `video-organization-modes`: explicit shots are
1104
+ * the AI Director's vocabulary. Returns the minted id so a caller can target it next,
1105
+ * and a structured failure when the wizard is closed.
1106
+ */
1107
+ export const addShot: StudioToolDefinition<"studio.video.shot.add"> = {
1108
+ handler: (ctx, input) => {
1109
+ const gate = requireOrganizationModes(ctx);
1110
+ if (gate) {
1111
+ return gate;
1112
+ }
1113
+
1114
+ const plan = currentPlan(ctx);
1115
+ if (!plan) {
1116
+ return wizardClosed;
1117
+ }
1118
+
1119
+ const id = mintShotId();
1120
+ const shots = insertShotSorted(plan.shots, { ...input, id });
1121
+ voidRecording(ctx);
1122
+ ctx.ui.getState().setVideoExportPlan({ ...plan, shots });
1123
+
1124
+ return { data: { id }, ok: true, summary: `Added a camera shot at ${input.at}.` };
1125
+ },
1126
+ precondition: (ctx) => requireOrganizationModes(ctx),
1127
+ };
1128
+
1129
+ /**
1130
+ * setShot edits one existing keyframe by id, merging the provided fields over it
1131
+ * and re-sorting the list when the progress moved (so the sorted-by-`at` invariant
1132
+ * holds). Needs `video-organization-modes`. Returns a structured failure when the wizard is
1133
+ * closed or no shot carries the id.
1134
+ */
1135
+ export const setShot: StudioToolDefinition<"studio.video.shot.set"> = {
1136
+ handler: (ctx, input) => {
1137
+ const gate = requireOrganizationModes(ctx);
1138
+ if (gate) {
1139
+ return gate;
1140
+ }
1141
+
1142
+ const plan = currentPlan(ctx);
1143
+ if (!plan) {
1144
+ return wizardClosed;
1145
+ }
1146
+
1147
+ const { id, ...changes } = input;
1148
+ const existing = plan.shots.find((shot) => shot.id === id);
1149
+ if (!existing) {
1150
+ return { code: "not-found", error: `no camera shot with id ${id}`, ok: false };
1151
+ }
1152
+
1153
+ // Member by member and not by a spread of the changes: a member the caller states as
1154
+ // `undefined` is one it left out, and a spread would write the `undefined` over the shot's.
1155
+ const merged: CameraShot = {
1156
+ ...existing,
1157
+ at: changes.at ?? existing.at,
1158
+ bearingMode: changes.bearingMode ?? existing.bearingMode,
1159
+ holdMs: changes.holdMs ?? existing.holdMs,
1160
+ pitchDeg: changes.pitchDeg ?? existing.pitchDeg,
1161
+ speedScale: changes.speedScale ?? existing.speedScale,
1162
+ zoom: changes.zoom ?? existing.zoom,
1163
+ ...(changes.bearingDeg === undefined ? {} : { bearingDeg: changes.bearingDeg }),
1164
+ };
1165
+
1166
+ // Re-sort by dropping the shot and re-inserting the merged copy, so a moved
1167
+ // `at` lands it in the right place and the sorted invariant holds.
1168
+ const remaining = plan.shots.filter((shot) => shot.id !== id);
1169
+ const shots = insertShotSorted(remaining, merged);
1170
+ voidRecording(ctx);
1171
+ ctx.ui.getState().setVideoExportPlan({ ...plan, shots });
1172
+
1173
+ return { ok: true, summary: `Edited camera shot ${id}.` };
1174
+ },
1175
+ precondition: (ctx) => requireOrganizationModes(ctx),
1176
+ };
1177
+
1178
+ /**
1179
+ * removeShot drops one keyframe from the plan by id. Needs `video-organization-modes`. Returns a
1180
+ * structured failure when the wizard is closed or no shot carries the id, so a
1181
+ * stray remove is a clear no-op rather than a silent one.
1182
+ */
1183
+ export const removeShot: StudioToolDefinition<"studio.video.shot.remove"> = {
1184
+ handler: (ctx, input) => {
1185
+ const gate = requireOrganizationModes(ctx);
1186
+ if (gate) {
1187
+ return gate;
1188
+ }
1189
+
1190
+ const plan = currentPlan(ctx);
1191
+ if (!plan) {
1192
+ return wizardClosed;
1193
+ }
1194
+
1195
+ if (!plan.shots.some((shot) => shot.id === input.id)) {
1196
+ return { code: "not-found", error: `no camera shot with id ${input.id}`, ok: false };
1197
+ }
1198
+
1199
+ const shots = plan.shots.filter((shot) => shot.id !== input.id);
1200
+ voidRecording(ctx);
1201
+ ctx.ui.getState().setVideoExportPlan({ ...plan, shots });
1202
+
1203
+ return { ok: true, summary: `Removed camera shot ${input.id}.` };
1204
+ },
1205
+ precondition: (ctx) => requireOrganizationModes(ctx),
1206
+ };
1207
+
1208
+ /**
1209
+ * addHold inserts a hold-beat keyframe (the camera parks at a progress point for a dwell
1210
+ * while framing the route) into the plan, the tool minting its id, and keeps the list sorted.
1211
+ * Needs `video-organization-modes`: it is part of the director's vocabulary. Returns the minted
1212
+ * id, and a structured failure when the wizard is closed.
1213
+ */
1214
+ export const addHold: StudioToolDefinition<"studio.video.shot.addHold"> = {
1215
+ handler: (ctx, input) => {
1216
+ const gate = requireOrganizationModes(ctx);
1217
+ if (gate) {
1218
+ return gate;
1219
+ }
1220
+
1221
+ const plan = currentPlan(ctx);
1222
+ if (!plan) {
1223
+ return wizardClosed;
1224
+ }
1225
+
1226
+ const id = mintShotId();
1227
+ const shot: CameraShot = {
1228
+ at: input.at,
1229
+ bearingMode: "follow",
1230
+ holdMs: input.holdMs,
1231
+ id,
1232
+ pitchDeg: input.pitchDeg,
1233
+ speedScale: 1,
1234
+ zoom: input.zoom,
1235
+ };
1236
+ const shots = insertShotSorted(plan.shots, shot);
1237
+ voidRecording(ctx);
1238
+ ctx.ui.getState().setVideoExportPlan({ ...plan, shots });
1239
+
1240
+ return { data: { id }, ok: true, summary: `Added a ${input.holdMs} ms hold at ${input.at}.` };
1241
+ },
1242
+ precondition: (ctx) => requireOrganizationModes(ctx),
1243
+ };
1244
+
1245
+ /**
1246
+ * orbit adds an orbit around a point (the camera holds at a progress fraction and sweeps its
1247
+ * heading through one or more full turns) by expanding the request into a run of fixed-bearing
1248
+ * keyframes the resolver sweeps between. Needs `video-organization-modes`: it is the director's
1249
+ * "circle this spot" verb. Returns a structured failure when the wizard is closed.
1250
+ */
1251
+ export const orbit: StudioToolDefinition<"studio.video.orbit"> = {
1252
+ handler: (ctx, input) => {
1253
+ const gate = requireOrganizationModes(ctx);
1254
+ if (gate) {
1255
+ return gate;
1256
+ }
1257
+
1258
+ const plan = currentPlan(ctx);
1259
+ if (!plan) {
1260
+ return wizardClosed;
1261
+ }
1262
+
1263
+ voidRecording(ctx);
1264
+ let shots = plan.shots;
1265
+ for (const shot of orbitShots(input)) {
1266
+ shots = insertShotSorted(shots, shot);
1267
+ }
1268
+
1269
+ ctx.ui.getState().setVideoExportPlan({ ...plan, shots });
1270
+
1271
+ return { ok: true, summary: `Added an orbit of ${input.turns} turn(s) at ${input.at}.` };
1272
+ },
1273
+ precondition: (ctx) => requireOrganizationModes(ctx),
1274
+ };
1275
+
1276
+ /**
1277
+ * getPlan returns the open wizard's current Camera Plan as the result data, so a
1278
+ * caller (the AI Director, a test) can read the authoritative plan the presets and
1279
+ * camera edits have built. Feature-gated. Returns a structured failure when the
1280
+ * wizard is closed.
1281
+ */
1282
+ export const getPlan: StudioToolDefinition<"studio.video.plan.get"> = {
1283
+ handler: (ctx) => {
1284
+ const gate = requireVideoExport(ctx);
1285
+ if (gate) {
1286
+ return gate;
1287
+ }
1288
+
1289
+ const plan = currentPlan(ctx);
1290
+ if (!plan) {
1291
+ return wizardClosed;
1292
+ }
1293
+
1294
+ return { data: { plan }, ok: true, summary: "Read the current camera plan." };
1295
+ },
1296
+ };
1297
+
1298
+ /**
1299
+ * previewStart begins a live camera fly of the wizard's plan on the dedicated wizard map, from
1300
+ * its first frame and with no frame captured, reporting progress into the UI store's status
1301
+ * slot. {@link startPreview} states the run, its warms and every way it ends. Feature-gated.
1302
+ */
1303
+ export const previewStart: StudioToolDefinition<"studio.video.preview.start"> = {
1304
+ handler: (ctx) => {
1305
+ const gate = requireExportable(ctx);
1306
+ if (gate) {
1307
+ return gate;
1308
+ }
1309
+
1310
+ return startPreview(ctx, { resume: false });
1311
+ },
1312
+ precondition: (ctx) => requireExportable(ctx),
1313
+ };
1314
+
1315
+ /**
1316
+ * previewPlay resumes the preview a pause stopped in the air, from the frame nearest where it
1317
+ * was, flies on from the frame a seek parked the camera on, and flies the plan from its first
1318
+ * frame when there is neither. {@link startPreview} states the run, its warms, where it starts and
1319
+ * every way it ends. Feature-gated and map-guarded as previewStart is.
1320
+ */
1321
+ export const previewPlay: StudioToolDefinition<"studio.video.preview.play"> = {
1322
+ handler: (ctx) => {
1323
+ const gate = requireExportable(ctx);
1324
+ if (gate) {
1325
+ return gate;
1326
+ }
1327
+
1328
+ return startPreview(ctx, { resume: true });
1329
+ },
1330
+ precondition: (ctx) => requireExportable(ctx),
1331
+ };
1332
+
1333
+ /**
1334
+ * previewPause pauses the live preview fly by stopping its run, and lands the status on idle,
1335
+ * from `previewing` and from `parked` alike.
1336
+ * The map's `previewPoses` restores the camera from before the preview as the run stops.
1337
+ *
1338
+ * A flight stopped in the air is remembered by how far it had flown, which
1339
+ * `studio.video.preview.play` resumes from. One stopped while it was still warming had flown
1340
+ * nothing, so whatever was paused before it stays paused. Feature-gated. Refused while a
1341
+ * recording runs, which no preview verb stops. With nothing in flight it only lands the status
1342
+ * on idle.
1343
+ */
1344
+ export const previewPause: StudioToolDefinition<"studio.video.preview.pause"> = {
1345
+ handler: (ctx) => {
1346
+ const gate = requireVideoExport(ctx);
1347
+ if (gate) {
1348
+ return gate;
1349
+ }
1350
+
1351
+ if (wizardRunOf(ctx).recording) {
1352
+ return recordingInFlight;
1353
+ }
1354
+
1355
+ flights.get(ctx.ui)?.engine.pause();
1356
+ landIdle(ctx);
1357
+
1358
+ return { ok: true, summary: "Paused the video preview." };
1359
+ },
1360
+ };
1361
+
1362
+ /**
1363
+ * previewSeek jumps the preview to a progress fraction: it parks the wizard map's camera on the
1364
+ * resolved pose nearest the fraction and states the fraction in the status slot as `parked`,
1365
+ * which the wizard's scrubber reads. `parked` and neither `previewing` nor idle: the camera rests
1366
+ * on a frame of the flight, and nothing flies. Feature-gated and map-guarded.
1367
+ *
1368
+ * A seek asked for while a flight is in the air stops that flight and parks once the flight has
1369
+ * given the camera back, as it does after a flight a pause, a stop or a
1370
+ * cancel stopped a moment before: the stopped flight restores the camera it found as its map
1371
+ * call settles, and a pose parked ahead of that restore would be overwritten by it.
1372
+ *
1373
+ * The pose parked on is one of the route and the plan the wizard holds as the camera is parked.
1374
+ * A `studio.video.route.set` or an edit of the plan overtakes no seek, so the wizard is read
1375
+ * again once every wait has settled, the warms, the resolve and the stopped flights alike: where
1376
+ * it holds another route or another plan than the poses were resolved for, the seek warms and
1377
+ * resolves again, and where it holds no route any more the seek answers `not-found` and parks
1378
+ * nothing. A seek that stopped a flight and answers so leaves the status on idle.
1379
+ *
1380
+ * A seek waits on the route's two warms like any flight and starts neither twice, so a scrubber
1381
+ * dragged on a cold route sweeps the camera once. It installs no run of its own, so it is
1382
+ * overtaken and not aborted: a preview, a recording or a seek dispatched while it warms takes
1383
+ * the camera, as a close does, and the seek then parks nothing and answers
1384
+ * `data.parked: false`. The camera and the status therefore follow the seek dispatched last,
1385
+ * whichever warm settles last. A pause, a stop or a cancel takes no camera, so a seek still
1386
+ * warming goes on to park. A seek that parked answers `data.parked: true` and forgets a paused
1387
+ * flight: the next play flies on from the parked frame, which the `parked` status states, and
1388
+ * from the first frame once a pause or a stop has landed the status on idle.
1389
+ *
1390
+ * Refused while a recording runs, which no preview verb stops.
1391
+ */
1392
+ export const previewSeek: StudioToolDefinition<"studio.video.preview.seek"> = {
1393
+ handler: async (ctx, input) => {
1394
+ const gate = requireExportable(ctx);
1395
+ if (gate) {
1396
+ return gate;
1397
+ }
1398
+
1399
+ const map = ctx.videoMap;
1400
+ if (!map) {
1401
+ return mapNotMounted;
1402
+ }
1403
+
1404
+ if (wizardRunOf(ctx).recording) {
1405
+ return recordingInFlight;
1406
+ }
1407
+
1408
+ const video = ctx.ui.getState().videoExport;
1409
+ if (!video) {
1410
+ return wizardClosed;
1411
+ }
1412
+
1413
+ if (!video.route) {
1414
+ return routeMissing;
1415
+ }
1416
+
1417
+ const outcome = await flightOf(ctx, map, video).seek(input.fraction);
1418
+ if (outcome.ok) {
1419
+ return {
1420
+ data: { parked: true },
1421
+ ok: true,
1422
+ summary: `Seeked the video preview to ${input.fraction}.`,
1423
+ };
1424
+ }
1425
+
1426
+ switch (outcome.reason) {
1427
+ case "aborted":
1428
+ return {
1429
+ data: { parked: false },
1430
+ ok: true,
1431
+ summary: `Left the video preview to a newer command: the seek to ${input.fraction} parked nothing.`,
1432
+ };
1433
+ case "failed":
1434
+ throw outcome.error;
1435
+ case "no-map":
1436
+ return mapNotMounted;
1437
+ case "no-route":
1438
+ return routeMissing;
1439
+ }
1440
+ },
1441
+ precondition: (ctx) => requireExportable(ctx),
1442
+ };
1443
+
1444
+ /**
1445
+ * previewStop stops the live preview: it stops the run, which restores the camera, returns the
1446
+ * status to idle and forgets a paused flight, so the next play starts from the first frame.
1447
+ * Feature-gated. Refused while a recording runs, which no preview verb stops.
1448
+ */
1449
+ export const previewStop: StudioToolDefinition<"studio.video.preview.stop"> = {
1450
+ handler: (ctx) => {
1451
+ const gate = requireVideoExport(ctx);
1452
+ if (gate) {
1453
+ return gate;
1454
+ }
1455
+
1456
+ if (wizardRunOf(ctx).recording) {
1457
+ return recordingInFlight;
1458
+ }
1459
+
1460
+ flights.get(ctx.ui)?.engine.stop();
1461
+ landIdle(ctx);
1462
+
1463
+ return { ok: true, summary: "Stopped the video preview." };
1464
+ },
1465
+ };
1466
+
1467
+ /**
1468
+ * record captures and encodes the wizard's plan into a video on the dedicated wizard map,
1469
+ * through the engine's `record`, which states its progress (preparing, recording, encoding) in
1470
+ * the UI store's status slot. The blob and its extension are kept for a later download.
1471
+ * Feature-gated.
1472
+ *
1473
+ * - **What it records is what the wizard shows.** A change to the plan, the route, the overlay
1474
+ * settings or the glyph while it runs stops it ({@link voidRecording}).
1475
+ * - **The run opens before the warms,** so a cancel during a warm stops this run before it
1476
+ * captures a frame, and its sweep with it.
1477
+ * - **A stopped run keeps no file,** whatever the recorder resolved: a recorder a host supplies
1478
+ * may finish a file after its signal aborted, and that file is the plan's no longer.
1479
+ *
1480
+ * Returns a structured failure, never throwing: `no-map` when the wizard map is not mounted
1481
+ * and when it could not start a capture, which the recorder states as `reason: "unavailable"`,
1482
+ * `no-session` when the wizard is closed, `not-found` when it holds no route, `conflict` when
1483
+ * a change stopped the run, `canceled` when a cancel, a close or a newer recording
1484
+ * did, and `internal` with the recorder's own message when the recorder failed (a missing
1485
+ * encoder peer, a surface or capture that could not be built, an encode that threw) or
1486
+ * resolved no video and no reason. Every exit, a throw from a warm or the recorder included,
1487
+ * returns the status to idle unless a newer run or a stop already took it over.
1488
+ */
1489
+ export const record: StudioToolDefinition<"studio.video.record"> = {
1490
+ handler: async (ctx) => {
1491
+ const gate = requireExportable(ctx);
1492
+ if (gate) {
1493
+ return gate;
1494
+ }
1495
+
1496
+ const map = ctx.videoMap;
1497
+ if (!map) {
1498
+ return mapNotMounted;
1499
+ }
1500
+
1501
+ const video = ctx.ui.getState().videoExport;
1502
+ if (!video) {
1503
+ return wizardClosed;
1504
+ }
1505
+
1506
+ if (!video.route) {
1507
+ return routeMissing;
1508
+ }
1509
+
1510
+ // The recording takes the camera: the engine stops the run before it and overtakes a seek
1511
+ // still warming, and a preview stopped here reads no later status as its own.
1512
+ const engine = flightOf(ctx, map, video);
1513
+ const run = wizardRunOf(ctx);
1514
+ run.sequence += 1;
1515
+ const recording = { outdated: false };
1516
+ run.recording = recording;
1517
+
1518
+ let outcome: Awaited<ReturnType<VideoFlightEngine["record"]>>;
1519
+ try {
1520
+ outcome = await engine.record();
1521
+ } finally {
1522
+ if (run.recording === recording) {
1523
+ run.recording = null;
1524
+ }
1525
+ }
1526
+
1527
+ if (outcome.ok) {
1528
+ run.recorded = { blob: outcome.blob, extension: outcome.extension };
1529
+
1530
+ return { ok: true, summary: "Recorded the video." };
1531
+ }
1532
+
1533
+ switch (outcome.reason) {
1534
+ case "aborted":
1535
+ return recordingStopped(recording);
1536
+ // A failed run is not a cancel: the recorder's message names what went wrong and, for a
1537
+ // missing encoder peer, the install that fixes it.
1538
+ case "failed":
1539
+ return { code: "internal", error: outcome.error.message, ok: false };
1540
+ case "no-frames":
1541
+ return { code: "internal", error: "recording produced no video", ok: false };
1542
+ case "no-map":
1543
+ return mapNotMounted;
1544
+ case "no-route":
1545
+ return routeMissing;
1546
+ case "unavailable":
1547
+ return recordingUnavailable;
1548
+ }
1549
+ },
1550
+ precondition: (ctx) => requireExportable(ctx),
1551
+ };
1552
+
1553
+ /**
1554
+ * cancel stops the recording in flight through the engine's `stop`: the recorder leaves its
1555
+ * frame loop and the camera is restored, and the status returns to idle. Feature-gated.
1556
+ *
1557
+ * It stops a preview in flight as well, as a stop does, and its summary names the run it
1558
+ * stopped. With nothing in flight it only lands the status on idle.
1559
+ */
1560
+ export const cancel: StudioToolDefinition<"studio.video.cancel"> = {
1561
+ handler: (ctx) => {
1562
+ const gate = requireVideoExport(ctx);
1563
+ if (gate) {
1564
+ return gate;
1565
+ }
1566
+
1567
+ wizardRunOf(ctx).recording = null;
1568
+ const stopped = flights.get(ctx.ui)?.engine.stop() ?? null;
1569
+ landIdle(ctx);
1570
+
1571
+ if (stopped === "record") {
1572
+ return { ok: true, summary: "Cancelled the video recording." };
1573
+ }
1574
+
1575
+ return {
1576
+ ok: true,
1577
+ summary:
1578
+ stopped === "preview"
1579
+ ? "Stopped the video preview."
1580
+ : "No video recording or preview is in progress.",
1581
+ };
1582
+ },
1583
+ };
1584
+
1585
+ /**
1586
+ * download saves the last recorded video to disk through the host's `saveFile` seam, which
1587
+ * the itinerary export uses too. It names the file as `studio.itinerary.export` does: from the
1588
+ * published itinerary's name in the cache and the segment the wizard is narrowed to, with the
1589
+ * recording's container extension. With no published entry in the cache, the open wizard's
1590
+ * itinerary id names the file. Feature-gated. Returns a structured failure when no recording is
1591
+ * available: none was made since the wizard opened, it was stopped, or a change to the plan,
1592
+ * the route or the overlay dropped it ({@link voidRecording}).
1593
+ *
1594
+ * The recording arrives as a `Blob`, because a browser encoder is what produced it, and the
1595
+ * seam carries BYTES, so the conversion happens here, at the one place holding a platform
1596
+ * object that a native shell, a worker or a server-side host has no use for.
1597
+ */
1598
+ export const download: StudioToolDefinition<"studio.video.download"> = {
1599
+ handler: async (ctx) => {
1600
+ const gate = requireExportable(ctx);
1601
+ if (gate) {
1602
+ return gate;
1603
+ }
1604
+
1605
+ const recorded = wizardRunOf(ctx).recorded;
1606
+ if (!recorded) {
1607
+ return { code: "not-found", error: "no recorded video to download", ok: false };
1608
+ }
1609
+
1610
+ const video = ctx.ui.getState().videoExport;
1611
+ const itineraryId = video?.itineraryId ?? "video";
1612
+ // Named as `studio.itinerary.export` names its file, from the PUBLISHED itinerary (the one a
1613
+ // video records) and the segment the wizard is narrowed to, so every studio download reads
1614
+ // alike. With no published entry in the cache, the itinerary's id names it.
1615
+ const published = ctx.api?.cache.get({
1616
+ id: itineraryId,
1617
+ kind: "itinerary",
1618
+ surface: "published",
1619
+ });
1620
+ const filename =
1621
+ published === undefined
1622
+ ? `${itineraryId}.${recorded.extension}`
1623
+ : buildExportFilename(exportFileStem(published, video?.segmentId), recorded.extension);
1624
+ // Through the host's seam and nothing else. A fallback to the browser's own would build an
1625
+ // anchor in a document a Node, worker or agent host does not have, so the context names the
1626
+ // seam (see `StudioToolContext.saveFile`).
1627
+ ctx.saveFile(
1628
+ {
1629
+ bytes: await recorded.blob.arrayBuffer(),
1630
+ contentType: recorded.blob.type === "" ? undefined : recorded.blob.type,
1631
+ },
1632
+ filename,
1633
+ );
1634
+
1635
+ return { ok: true, summary: "Downloaded the recorded video." };
1636
+ },
1637
+ precondition: (ctx) => requireExportable(ctx),
1638
+ };