@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,2254 @@
1
+ import type { Polygon } from "geojson";
2
+ import type { z } from "zod";
3
+
4
+ import type { DataSchema, Zone, ZoneMode } from "@mountaya/client";
5
+ import { POINT_ZOOM } from "@mountaya/elements/camera";
6
+ import { boundsOf } from "@mountaya/elements/geo";
7
+
8
+ import type { studioToolContracts } from "../../bus/contracts/studioTools.js";
9
+ import { failureFromThrown } from "../../bus/rules/handlerErrors.js";
10
+ import type { ToolFailure, ToolResult } from "../../bus/rules/types.js";
11
+ import { selectActiveEditEngine } from "../../chrome/rules/agentSelectors.js";
12
+ import type { UiState } from "../../chrome/stores/uiStore.js";
13
+ import { attachZoneToCollections } from "../../collections/handlers/collectionAttach.js";
14
+ import { refreshHeldCollection } from "../../collections/handlers/heldCollection.js";
15
+ import { requireData } from "../../data/handlers/graphql.js";
16
+ import { evictResources, invalidateLanded, type StudioCache } from "../../data/rules/cache.js";
17
+ import {
18
+ acquireCollabLock,
19
+ editInProgressError,
20
+ guardCollabLock,
21
+ guardEditBegin,
22
+ guardEditBeginUnderLock,
23
+ maybeResetCopilotOnSwitch,
24
+ releaseCollabEntity,
25
+ returnFromZoneSurface,
26
+ teardownActiveEditSession,
27
+ } from "../../edit/handlers/editLock.js";
28
+ import { selectUnsavedWork } from "../../edit/rules/unsavedWork.js";
29
+ import type { openedOutputSchema } from "../../itinerary/contracts/itinerary.js";
30
+ import { askToDiscard, leaveStagedSurface } from "../../itinerary/handlers/surfaceOpen.js";
31
+ import { toDataActivity } from "../../itinerary/rules/activity.js";
32
+ import { showingDraftSurface } from "../../itinerary/rules/draftSurface.js";
33
+ import type { StudioToolContext, StudioToolDefinition } from "../../viewer/rules/context.js";
34
+ import { requireWritableScope } from "../../viewer/rules/scope.js";
35
+ import {
36
+ isPolygonGeometry,
37
+ wrapZoneGeometryPastRange,
38
+ zoneCircleGeometry,
39
+ zoneSectorGeometry,
40
+ zoneSensorGeometry,
41
+ } from "../rules/geometry.js";
42
+ import { DEFAULT_ZONE_CREATE_METHOD, DEFAULT_ZONE_LEVEL } from "../rules/zoneDefaults.js";
43
+ import {
44
+ type ZoneCreateSeed,
45
+ type ZonePreviewBand,
46
+ zonePreviewQueryKey,
47
+ } from "../stores/zoneEdit.js";
48
+ import {
49
+ addZoneToCollection,
50
+ createZone as createZoneRequest,
51
+ deleteZone as deleteZoneRequest,
52
+ fetchZone,
53
+ removeZoneFromCollection,
54
+ updateZone as updateZoneRequest,
55
+ zoneFeature,
56
+ } from "./restZones.js";
57
+
58
+ /**
59
+ * revealZoneCreate is the shared "show a fresh zone create" write every entry into the create
60
+ * surface runs: unbind whatever zone the panel last held, seed the create state, and mount the
61
+ * zone panel.
62
+ *
63
+ * It deliberately does NOT navigate. The sidenav cascade resolves the open content slot BEFORE
64
+ * the url's itinerary detail, so the zone panel already renders over an open itinerary, and
65
+ * leaving the detail keys in place is what lets closing the zone panel fall back to the
66
+ * itinerary the user was editing instead of dropping them on the collections list. Clearing
67
+ * those keys, which is what a zone-open path does when it does not know about that cascade
68
+ * order, only destroys the route the user came from.
69
+ */
70
+ const revealZoneCreate = (ctx: StudioToolContext, seed: ZoneCreateSeed): void => {
71
+ ctx.ui.getState().setActiveZone(null);
72
+ ctx.ui.getState().resetZoneCreate(seed);
73
+ ctx.ui.getState().setOpenContent("zone");
74
+ };
75
+
76
+ /**
77
+ * refuseCreateOverEdit answers `edit-in-progress` while any authoring engine is armed, and null
78
+ * otherwise. The sidenav's entry into the create surface asks it first, and so do a create and a
79
+ * co-pilot's seeded begin; a person's seeded begin asks them to let the edit go instead
80
+ * ({@link leaveEditForCreate}).
81
+ *
82
+ * A create unbinds the panel's zone and seeds its own state, and it ends no session. Over an
83
+ * armed zone edit that leaves a form with no zone bound and a session still open on the saved
84
+ * one, whose Save would then write the create's fields onto that zone. Over a segment or a
85
+ * waypoint edit it hides the surface of an edit that stays armed. So the create is refused, as
86
+ * `studio.zone.openForView` refuses to bind another zone, and the edit is the reader's to save
87
+ * or cancel first.
88
+ */
89
+ const refuseCreateOverEdit = (ctx: StudioToolContext): ToolFailure | null => {
90
+ const active = selectActiveEditEngine(ctx.ui.getState());
91
+
92
+ return active === null ? null : editInProgressError(active.kind);
93
+ };
94
+
95
+ /**
96
+ * leaveEditForCreate makes room for a create begun over an edit, and answers null when the
97
+ * create may begin.
98
+ *
99
+ * A person is asked before work they have not saved is dropped, with the shared unsaved-changes
100
+ * prompt ({@link askToDiscard}) closing the editor asks: a yes ends the armed session and the
101
+ * create begins, and a no, or a confirm gate that throws, answers `confirmation-denied` with
102
+ * nothing changed. An edit with nothing changed is closed unasked, as the editor's close closes
103
+ * it. A co-pilot is asked nothing, since a run answers no dialog: its call keeps the refusal of
104
+ * {@link refuseCreateOverEdit}, `edit-in-progress`, while any edit is armed.
105
+ *
106
+ * @param input The create's own input, handed to the confirmation request.
107
+ */
108
+ const leaveEditForCreate = async (
109
+ ctx: StudioToolContext,
110
+ input: object,
111
+ ): Promise<ToolFailure | null> => {
112
+ if (ctx.origin === "agent") {
113
+ return refuseCreateOverEdit(ctx);
114
+ }
115
+
116
+ if (selectUnsavedWork(ctx.ui.getState())) {
117
+ const kept = await askToDiscard(
118
+ ctx,
119
+ "studio.zone.createBegin",
120
+ input,
121
+ "zone create declined: kept the open edit and the surface it belongs to",
122
+ );
123
+ if (kept) {
124
+ return kept;
125
+ }
126
+ }
127
+
128
+ teardownActiveEditSession(ctx);
129
+
130
+ return null;
131
+ };
132
+
133
+ /**
134
+ * open opens the studio's zone surface, the entry point for defining a zone on
135
+ * the map (to explore, to avoid, or to highlight). It clears any zone the panel
136
+ * was last bound to and starts a fresh hand-drawn create, so the surface always
137
+ * opens clean rather than showing a previously viewed zone's data or a previous
138
+ * create's half-configured reachability query. Seeding a create with a specific
139
+ * method and origin is {@link createBegin}, which is an edit verb.
140
+ *
141
+ * Over a staged import or suggestion it leaves that surface first ({@link leaveStagedSurface}):
142
+ * a staged draft is asked about through the shared discard prompt and its session ends on a yes,
143
+ * a decline answers `confirmation-denied`, and a draft whose save is out answers `conflict`. Then,
144
+ * while any edit is armed, it answers `edit-in-progress` and changes nothing: see
145
+ * {@link refuseCreateOverEdit}.
146
+ */
147
+ export const open: StudioToolDefinition<"studio.zone.open"> = {
148
+ handler: async (ctx, input) => {
149
+ const left = await leaveStagedSurface(ctx, "studio.zone.open", input, "zone");
150
+ if (left) {
151
+ return left;
152
+ }
153
+
154
+ const refused = refuseCreateOverEdit(ctx);
155
+ if (refused) {
156
+ return refused;
157
+ }
158
+
159
+ // The sidenav entry inherits nothing: it is reachable with no itinerary open at
160
+ // all, so the organization, the collections and the activity are real questions
161
+ // here even when one happens to be loaded.
162
+ revealZoneCreate(ctx, {
163
+ inheritItinerary: false,
164
+ method: DEFAULT_ZONE_CREATE_METHOD,
165
+ origin: null,
166
+ });
167
+
168
+ return { ok: true, summary: "Opened the zone surface." };
169
+ },
170
+ };
171
+
172
+ /**
173
+ * createBegin opens the zone surface on a specific authoring method, seeded with an origin when
174
+ * one is known: the map context menu's "Reachability from here" passes the right-clicked
175
+ * coordinate, and a waypoint's menu the waypoint's, so the create opens already measuring from
176
+ * the point the user pointed at.
177
+ *
178
+ * It is separate from {@link open} rather than an optional payload on it because the two sit on
179
+ * opposite sides of a capability boundary: opening the surface is a view, seeding a create is
180
+ * an edit. agentHidden: it is a human create affordance; a co-pilot proposes a computed zone
181
+ * through editPropose, which opens a live draft rather than a form for someone else to fill in.
182
+ *
183
+ * A create begun from here INHERITS the open itinerary's context when there is one. This is the
184
+ * from-the-map entry: the user right-clicked inside the itinerary they are editing, so its
185
+ * organization, its collections and its activity are the answers, and asking for all three
186
+ * again is three chances to file the zone away from the route it was drawn for. The sidenav's
187
+ * own zone button goes through {@link open} instead, where no itinerary is in play and every
188
+ * one of them is a real question.
189
+ *
190
+ * Over a staged import or suggestion it leaves that surface first, as {@link open} does. Then,
191
+ * over an armed edit, it asks a person about the work they have not saved and closes the edit
192
+ * once they let it go, as closing the editor does, and answers a co-pilot `edit-in-progress`
193
+ * with nothing seeded: see {@link leaveEditForCreate}.
194
+ */
195
+ export const createBegin: StudioToolDefinition<"studio.zone.createBegin"> = {
196
+ agentHidden: true,
197
+ handler: async (ctx, input) => {
198
+ const left = await leaveStagedSurface(ctx, "studio.zone.createBegin", input, "zone");
199
+ if (left) {
200
+ return left;
201
+ }
202
+
203
+ const refused = await leaveEditForCreate(ctx, input);
204
+ if (refused) {
205
+ return refused;
206
+ }
207
+
208
+ revealZoneCreate(ctx, {
209
+ inheritItinerary: ctx.ui.getState().activeItinerary !== null,
210
+ method: input.method,
211
+ origin: input.origin ?? null,
212
+ });
213
+
214
+ return { ok: true, summary: `Started a ${input.method} zone create.` };
215
+ },
216
+ };
217
+
218
+ /**
219
+ * setCreateMethod switches the create surface between drawing the zone by hand and computing it
220
+ * from a reachability query. Switching AWAY from reachability drops any band preview: those
221
+ * bands describe a query the surface no longer offers, so leaving them painted would show the
222
+ * user a shape nothing on screen can still produce. The origin is deliberately kept: switching
223
+ * to draw and back should not cost the point already placed. agentHidden, like the rest of the
224
+ * create-surface plumbing.
225
+ */
226
+ export const setCreateMethod: StudioToolDefinition<"studio.zone.setCreateMethod"> = {
227
+ agentHidden: true,
228
+ handler: (ctx, input) => {
229
+ ctx.ui.getState().setZoneCreateMethod(input.method);
230
+ if (input.method !== "reachability") {
231
+ ctx.ui.getState().setZonePreview(null);
232
+ }
233
+
234
+ return { ok: true, summary: `Switched the zone create to ${input.method}.` };
235
+ },
236
+ };
237
+
238
+ /**
239
+ * beginOriginPick arms the map to capture the next click as the reachability
240
+ * origin. It refuses while any authoring engine is armed, exactly as the segment
241
+ * split pick does: the cursor lock, the base-map block and the pointer tooltip
242
+ * are NOT reference-counted, so a pick layered over a live reshape would paint a
243
+ * second tooltip and drop the reshape's cursor lock when it tore down.
244
+ *
245
+ * agentHidden: it opens a surface that waits for a human click, which an agent
246
+ * run has no way to satisfy; a co-pilot sets an origin by passing coordinates to
247
+ * editPropose instead.
248
+ */
249
+ export const beginOriginPick: StudioToolDefinition<"studio.zone.beginOriginPick"> = {
250
+ agentHidden: true,
251
+ handler: (ctx) => {
252
+ if (selectActiveEditEngine(ctx.ui.getState()) !== null) {
253
+ return {
254
+ code: "edit-in-progress",
255
+ error: "another edit is already armed: finish or cancel it before picking a point",
256
+ ok: false,
257
+ };
258
+ }
259
+
260
+ ctx.ui.getState().setZoneOriginPicking(true);
261
+
262
+ return { ok: true, summary: "Waiting for a click to set the reachability origin." };
263
+ },
264
+ };
265
+
266
+ /**
267
+ * cancelOriginPick disarms the origin pick without placing a point, leaving any
268
+ * previously placed origin as it was. Escape drives it from the picking hook.
269
+ * agentHidden for the same reason as its arming twin.
270
+ */
271
+ export const cancelOriginPick: StudioToolDefinition<"studio.zone.cancelOriginPick"> = {
272
+ agentHidden: true,
273
+ handler: (ctx) => {
274
+ ctx.ui.getState().setZoneOriginPicking(false);
275
+
276
+ return { ok: true, summary: "Cancelled the reachability origin pick." };
277
+ },
278
+ };
279
+
280
+ /**
281
+ * setOrigin writes the point a reachability create measures from. The store setter also clears
282
+ * the picking flag, which makes the pick one-shot: the click that places the point is the same
283
+ * event that disarms the cursor, the tooltip and the pick engine, so no explicit stop call is
284
+ * needed. agentHidden: it is the picking hook's own resolve seam.
285
+ */
286
+ export const setOrigin: StudioToolDefinition<"studio.zone.setOrigin"> = {
287
+ agentHidden: true,
288
+ handler: (ctx, input) => {
289
+ ctx.ui.getState().setZoneCreateOrigin(input.lngLat);
290
+
291
+ return { ok: true, summary: "Set the reachability origin." };
292
+ },
293
+ };
294
+
295
+ /**
296
+ * rangeTypeToData maps the zone source's `time`/`distance` measure onto the
297
+ * Data-API isochrones enum (`TIME`/`DISTANCE`, SCREAMING per the SDL). The wire
298
+ * ZoneSource stores the lowercase form; the isochrones query wants the enum, so
299
+ * the reachability preview converts it here at the one call site.
300
+ */
301
+ const rangeTypeToData = (
302
+ rangeType: z.infer<
303
+ (typeof studioToolContracts)["studio.zone.reachabilityPreview"]["input"]
304
+ >["rangeType"],
305
+ ): DataSchema.RangeType => (rangeType === "time" ? "TIME" : "DISTANCE");
306
+
307
+ /**
308
+ * invalidateZoneMembership evicts the caches a zone-collection membership change reshapes:
309
+ * every collection listing, since each serves the collection's counts and the picker of where
310
+ * the zone is filed among them, the collection's record and its zones, and the collection's
311
+ * tile SPECIFICATION.
312
+ *
313
+ * The specification is not a listing: it is the collection's render-layer set, so a
314
+ * zone entering or leaving the folder changes exactly what the embed and share
315
+ * surfaces draw. Left warm, a zone filed into a shared collection stays invisible on
316
+ * every map rendered from it.
317
+ *
318
+ * It never rejects. The membership has landed by the time the cache is told, and a cache that
319
+ * fails to evict says nothing about that write: reported as the verb's failure, it would have
320
+ * the picker offer the same change again over a membership the server already holds.
321
+ */
322
+ const invalidateZoneMembership = async (
323
+ ctx: StudioToolContext,
324
+ collectionId: string,
325
+ ): Promise<void> => {
326
+ if (!ctx.api) {
327
+ return;
328
+ }
329
+
330
+ try {
331
+ await ctx.api.cache.invalidate(
332
+ { kind: "collections" },
333
+ { id: collectionId, kind: "collection" },
334
+ { id: collectionId, kind: "collectionZones" },
335
+ { id: collectionId, kind: "collectionSpecification" },
336
+ );
337
+ } catch {
338
+ // The membership is written. Every entry is read again by whatever reads it next.
339
+ }
340
+
341
+ // The membership moved the collection's version, which a later update of it is made
342
+ // conditional on: a record the studio holds is read again.
343
+ await refreshHeldCollection(ctx.api.client, ctx.api.cache, collectionId);
344
+ };
345
+
346
+ /**
347
+ * savedZoneOrganization finds the organization a saved zone belongs to from what the session
348
+ * already holds: the zone bound to the panel when it is this one, then the zone's cached record.
349
+ * It never fetches. `undefined` is UNKNOWN, and `null` a personal zone, as the API spells one.
350
+ */
351
+ export const savedZoneOrganization = (
352
+ ctx: StudioToolContext,
353
+ zoneId: string,
354
+ ): string | null | undefined => {
355
+ const active = ctx.ui.getState().activeZone;
356
+ if (active?.id === zoneId) {
357
+ return active.organization_id;
358
+ }
359
+
360
+ return ctx.api?.cache.get({ id: zoneId, kind: "zone" })?.organization_id;
361
+ };
362
+
363
+ /**
364
+ * refuseZoneScope refuses a write of a zone into the scope `organizationId` names, before
365
+ * anything is written ({@link requireWritableScope}): the personal space holds no zone, and an
366
+ * organization whose agreement does not include Map Studio takes none. An UNKNOWN organization
367
+ * (`undefined`) is no refusal: it is a saved zone the session holds no record of, or a create
368
+ * whose form has not named one yet, and the write that follows answers for it.
369
+ */
370
+ const refuseZoneScope = (
371
+ ctx: StudioToolContext,
372
+ organizationId: string | null | undefined,
373
+ ): ToolFailure | null =>
374
+ organizationId === undefined ? null : requireWritableScope(ctx, "zone", organizationId);
375
+
376
+ /**
377
+ * createZone persists a new zone, writing through to the server. The whole geometry is sent as
378
+ * the drawn Feature (no flatten or build step: zone geometry is a plain RFC-7946 Feature). The
379
+ * name is required and the description optional: an empty one is omitted, which creates the
380
+ * zone without one. A name another zone of the organization already carries fails with the
381
+ * API's 409, which the bus reports as `conflict`. On success it sets the created zone active so
382
+ * the panel rebinds to the saved entity, and returns the new id in data so a caller can route
383
+ * or chain a collection add. It is the persist a caller sends with a geometry or a source
384
+ * already in hand: a reachability form's Save, a host, or an agent that needs no confirmation
385
+ * of the shape (`studio.zone.editPropose` is the agent's path to a draft a person confirms).
386
+ * Persisting, so it needs the api seam.
387
+ *
388
+ * While any edit is armed it answers `edit-in-progress` and sends nothing: see
389
+ * {@link refuseCreateOverEdit}. A scope that takes no zone is refused before anything is sent
390
+ * ({@link requireWritableScope}): a create naming no organization is the reader's own space,
391
+ * which holds none.
392
+ *
393
+ * The panel is bound and opened only for a reader who stayed where they were: the surface, the
394
+ * bound zone, the create and the armed session are read as the request leaves and again once it
395
+ * has answered ({@link zoneSurfaceStandsAt}). A reader who closed the zone surface meanwhile, or
396
+ * opened another zone or another create, keeps what they opened: the zone exists, the answer
397
+ * names it and states `opened` false, and it is drawn from its tiles. A zone created while a
398
+ * staged import or suggestion shows is answered the same way: the surface and its draft stay, as
399
+ * only an open asks to leave them.
400
+ *
401
+ * A create the API made and could not answer again is saved, and reconciled as one
402
+ * ({@link savedUnnamed} where nothing names the zone it made): it is never answered as a taken
403
+ * name nor sent again.
404
+ */
405
+ export const createZone: StudioToolDefinition<"studio.zone.create"> = {
406
+ handler: async (ctx, input) => {
407
+ if (!ctx.api) {
408
+ return { code: "no-api", error: "create zone: no persistence seam", ok: false };
409
+ }
410
+
411
+ const scoped = requireWritableScope(ctx, "zone", input.organizationId);
412
+ if (scoped) {
413
+ return scoped;
414
+ }
415
+
416
+ const refused = refuseCreateOverEdit(ctx);
417
+ if (refused) {
418
+ return refused;
419
+ }
420
+
421
+ // What the reader is looking at as the request leaves.
422
+ const asked = ctx.ui.getState();
423
+
424
+ const created = await createZoneRequest(ctx.api.client, {
425
+ // The schema trimmed it; an empty description is "none", which a create says by
426
+ // leaving the field out.
427
+ description: input.description ? input.description : undefined,
428
+ end_at: input.endAt ?? undefined,
429
+ // Exactly one of geojson/source rides the create (the XOR is enforced above).
430
+ // A hand-drawn zone sends its polygon wrapped in the Feature the wire takes; a
431
+ // computed zone sends its source and NO geojson, so the server computes the
432
+ // authoritative polygon and persists the source for later refresh.
433
+ geojson: input.geojson ? zoneFeature(input.geojson.geometry) : undefined,
434
+ is_private: input.isPrivate,
435
+ level: input.level,
436
+ mode: input.mode,
437
+ name: input.name,
438
+ organization_id: input.organizationId,
439
+ source: input.source,
440
+ start_at: input.startAt ?? undefined,
441
+ });
442
+ if (created === null) {
443
+ // The create surface the zone was saved from closes for a reader who stayed on it: left
444
+ // open, its Save would make the zone a second time. One who moved on keeps what they opened.
445
+ if (showingDraftSurface(ctx.ui.getState()) === null && zoneSurfaceStandsAt(ctx, asked)) {
446
+ returnFromZoneSurface(ctx);
447
+ }
448
+
449
+ await settleSavedUnnamed(ctx);
450
+
451
+ return {
452
+ data: { failedCollectionIds: [...(input.collectionIds ?? [])], opened: false, zoneId: "" },
453
+ ok: true,
454
+ summary: SAVED_UNNAMED,
455
+ };
456
+ }
457
+
458
+ // Decided from the store as it stands now, after the write: a reader who moved on while the
459
+ // request was out is not brought back to the zone surface, and what they opened stays.
460
+ const behindDraft = showingDraftSurface(ctx.ui.getState()) !== null;
461
+ const stayed = !behindDraft && zoneSurfaceStandsAt(ctx, asked);
462
+ if (stayed) {
463
+ const previousZoneId = ctx.ui.getState().activeZone?.id ?? null;
464
+ ctx.ui.getState().setActiveZone(created);
465
+ // Bind the panel to the zone that was just created. Setting the active zone
466
+ // alone leaves it bound to a panel that is not mounted, so the next click on
467
+ // that zone takes the "already bound, re-arm in place" path and arms the draw
468
+ // engine with no panel behind it: an edit cursor the user cannot see the
469
+ // reason for.
470
+ ctx.ui.getState().setOpenContent("zone");
471
+ // Drop any preview the create was configured against: the zone is persisted
472
+ // now and paints from the tiles, so leaving the transient overlay up would
473
+ // double-draw the same shape.
474
+ ctx.ui.getState().setZonePreview(null);
475
+ // A freshly-created zone becomes the edited resource; reset the co-pilot so a prior
476
+ // itinerary's or zone's conversation does not leak in (see maybeResetCopilotOnSwitch).
477
+ maybeResetCopilotOnSwitch(ctx, previousZoneId, created.id);
478
+ }
479
+
480
+ // A new zone joins every zone listing. The create has landed, so a cache that fails to mark
481
+ // them fails nothing of it.
482
+ await invalidateLanded(ctx.api.cache, { kind: "zones" });
483
+
484
+ // Refetch the zone tiles so the new zone paints at the current camera
485
+ // without a pan/zoom, exactly as the itinerary create/import flow busts the
486
+ // itinerary tiles. The map is idle here (no draw engine armed: this is the
487
+ // direct-persist path, not the editCommit teardown path), so the setTiles
488
+ // bust repaints reliably. A render-free context (no map) is a no-op.
489
+ ctx.map?.refreshZoneTiles();
490
+
491
+ // Attach the chosen collections best-effort AFTER the create succeeds: the
492
+ // zone already exists, so a failed attach must not fail or roll back the
493
+ // create. It returns the failed ids, which ride in the result data as a
494
+ // non-fatal signal while the result stays ok:true (mirroring the itinerary
495
+ // create's collection attach).
496
+ const failedCollectionIds = await attachZoneToCollections(
497
+ ctx,
498
+ created.id,
499
+ input.collectionIds ?? [],
500
+ );
501
+
502
+ return {
503
+ data: { failedCollectionIds, opened: stayed, zoneId: created.id },
504
+ ok: true,
505
+ summary: stayed
506
+ ? `Created zone “${created.name}”.`
507
+ : behindDraft
508
+ ? `Created zone “${created.name}”. A staged draft shows, so it was not opened.`
509
+ : `Created zone “${created.name}”. The user moved on while it was created, so it was not opened.`,
510
+ };
511
+ },
512
+ };
513
+
514
+ /**
515
+ * SAVED_UNNAMED is the summary of a create the API made and could not answer again, whose zone
516
+ * nothing names ({@link settleSavedUnnamed}).
517
+ */
518
+ const SAVED_UNNAMED =
519
+ "Saved the zone. Its answer could not be given again, so the zone listings are read again and it shows once they answer. It is not opened, and it was added to no collection.";
520
+
521
+ /**
522
+ * settleSavedUnnamed reconciles a create the API made and could not answer again, whose zone
523
+ * nothing names: the write's first answer carried no `Location`, or the zone it named could not
524
+ * be read.
525
+ *
526
+ * The zone is saved, so the verb answers `ok` and the create is never sent again: every zone
527
+ * listing is marked stale and the zone tiles are asked for again, so the zone shows as soon as
528
+ * those answer. With no id, nothing is bound or opened, the answer's `zoneId` is the empty
529
+ * string, and the collections chosen for it are named as not attached. The caller closes the
530
+ * surface it was saved from, so no Save there can make it a second time.
531
+ */
532
+ const settleSavedUnnamed = async (ctx: StudioToolContext): Promise<void> => {
533
+ if (ctx.api) {
534
+ await invalidateLanded(ctx.api.cache, { kind: "zones" });
535
+ }
536
+
537
+ ctx.map?.refreshZoneTiles();
538
+ };
539
+
540
+ /**
541
+ * zoneSurfaceStandsAt reports whether the reader is still where `asked` found them: the same
542
+ * content open, the same zone bound, the same create, and a zone session armed on the same zone
543
+ * or none.
544
+ *
545
+ * It is what a zone write asks once its request has answered, before it binds or opens anything:
546
+ * `asked` is the store as the request left. The bound zone and the session are each compared by
547
+ * the zone they name: a write of the bound zone replaces the object in its slot, an update's
548
+ * answer or a collaborator's change alike, and every frame of a draw replaces the session's.
549
+ */
550
+ const zoneSurfaceStandsAt = (ctx: StudioToolContext, asked: UiState): boolean => {
551
+ const now = ctx.ui.getState();
552
+
553
+ return (
554
+ now.openContent === asked.openContent &&
555
+ (now.activeZone?.id ?? null) === (asked.activeZone?.id ?? null) &&
556
+ now.zoneCreateSerial === asked.zoneCreateSerial &&
557
+ (now.zoneEditSession?.zoneId ?? null) === (asked.zoneEditSession?.zoneId ?? null)
558
+ );
559
+ };
560
+
561
+ /**
562
+ * armedDraftOf is the draft of the session armed on `zoneId` as a write leaves, or undefined
563
+ * when no session is armed on that zone. {@link reseedArmedZoneAfterPersist} reads it back.
564
+ */
565
+ const armedDraftOf = (ctx: StudioToolContext, zoneId: string): Polygon | null | undefined => {
566
+ const session = ctx.ui.getState().zoneEditSession;
567
+
568
+ return session?.zoneId === zoneId ? session.draft : undefined;
569
+ };
570
+
571
+ /**
572
+ * deletedZones names, per UI store, the zones a delete removed: this studio's own
573
+ * `studio.zone.delete`, and a collaborator's as `studio.collab.change.apply` reports it.
574
+ *
575
+ * A write of a zone can be out while the zone is deleted, and its answer lands afterwards with
576
+ * a zone the server no longer holds. Written where the studio holds that zone, it would put the
577
+ * deleted record back in the cache, and a cache that states no `evict` has nothing to compare
578
+ * it with. So a delete writes the id here once the server has confirmed it
579
+ * ({@link recordZoneDeleted}), and {@link storeWrittenZone} writes no answer for one. Keyed
580
+ * weakly by the store, so a studio that is gone keeps nothing alive.
581
+ */
582
+ const deletedZones = new WeakMap<object, Set<string>>();
583
+
584
+ /**
585
+ * recordZoneDeleted writes a zone the server has deleted into the record
586
+ * {@link storeWrittenZone} reads, so the answer of a write that was out when the zone went is
587
+ * written nowhere.
588
+ */
589
+ export const recordZoneDeleted = (ctx: Pick<StudioToolContext, "ui">, zoneId: string): void => {
590
+ const deleted = deletedZones.get(ctx.ui) ?? new Set<string>();
591
+ deleted.add(zoneId);
592
+ deletedZones.set(ctx.ui, deleted);
593
+ };
594
+
595
+ /**
596
+ * storeWrittenZone writes a zone a write just answered where the studio holds that zone: its own
597
+ * cache entry, and the panel's slot while the panel still shows it. It answers the zone that
598
+ * stands: the answer, or the newer copy the studio holds, and then it writes neither. It answers
599
+ * null for a zone deleted while the write was out ({@link deletedZones}): nothing of it stands,
600
+ * and nothing is written.
601
+ *
602
+ * Two writes of one zone can be out at once, and a zone's `revision` grows with each. An answer
603
+ * that lands after a newer one is stale: bound, it would show what the newer write replaced, and
604
+ * cached, the next open of the zone would read it. So the answer is compared with both copies
605
+ * before either is written, and one older than the bound zone or than the cached one is dropped.
606
+ * The same revision is no older: a write that changed nothing still answers the zone as it is.
607
+ *
608
+ * The server made a write whose answer is stale all the same, and the newer zone holds what it
609
+ * stored. So a caller draws what its own write changed from the zone answered here, whichever
610
+ * answer landed first: the newer write may have changed nothing the map paints, and then asked
611
+ * for no tiles and reseeded no draft.
612
+ *
613
+ * Every zone listing serves the zone's record, so each is marked stale once a write of the zone
614
+ * lands, whichever answer stands. The write has landed, so a cache that fails to mark them
615
+ * fails nothing ({@link invalidateLanded}), and nothing waits on it.
616
+ */
617
+ export const storeWrittenZone = (
618
+ ctx: StudioToolContext,
619
+ cache: StudioCache,
620
+ zone: Zone,
621
+ ): Zone | null => {
622
+ if (deletedZones.get(ctx.ui)?.has(zone.id)) {
623
+ return null;
624
+ }
625
+
626
+ void invalidateLanded(cache, { kind: "zones" });
627
+
628
+ const entry = { id: zone.id, kind: "zone" } as const;
629
+ const active = ctx.ui.getState().activeZone;
630
+ const bound = active?.id === zone.id ? active : null;
631
+ const cached = cache.get(entry) ?? null;
632
+
633
+ let newer: Zone | null = null;
634
+ for (const held of [bound, cached]) {
635
+ if (held !== null && held.revision > (newer ?? zone).revision) {
636
+ newer = held;
637
+ }
638
+ }
639
+
640
+ if (newer !== null) {
641
+ return newer;
642
+ }
643
+
644
+ cache.set(entry, zone);
645
+ if (bound !== null) {
646
+ ctx.ui.getState().setActiveZone(zone);
647
+ }
648
+
649
+ return zone;
650
+ };
651
+
652
+ /**
653
+ * deletedSinceAnswer is what a write of a zone answers when the zone was deleted while it was
654
+ * out: `ok`, since the server made the write, with `overtaken` true, since the delete came after
655
+ * it and nothing of what it stored is held, shown or drawn.
656
+ */
657
+ const deletedSinceAnswer = (written: string): ToolResult<{ overtaken: boolean }> => ({
658
+ data: { overtaken: true },
659
+ ok: true,
660
+ summary: `${written} The zone was deleted since, so nothing of it is shown.`,
661
+ });
662
+
663
+ /**
664
+ * updateZone persists a zone metadata change and, when a reshaped Feature is supplied, a new
665
+ * geometry revision, writing through to the server. Only the fields present in the partial are
666
+ * sent, so a one-field update (a rename, a level change, a new end date) leaves the siblings as
667
+ * the server holds them; a `null` description clears it, and a name another zone of the
668
+ * organization carries fails with `conflict`. On success it evicts the zone's detail cache so a
669
+ * re-open reads the new revision, and refreshes its active slot when the updated zone is the one
670
+ * the panel is bound to. This is the metadata-direct and reshape-persist path; the agent's
671
+ * metadata-only edits (level/description/time) call this directly, while a reshape goes
672
+ * through editPropose, the user's Save, then editCommit. Persisting, so it needs the api seam.
673
+ *
674
+ * This is the metadata-direct PUT: it takes its geojson reshape from the caller's input. The
675
+ * reshape-from-live-draft path is {@link zoneEditCommit}, which reads the geometry off the map's
676
+ * draw engine before persisting. The two stay separate on purpose (one is fed a Feature, the
677
+ * other harvests the draft): do not "unify" them into one persist.
678
+ *
679
+ * A zone a collaborator holds is refused with `collab-locked` and nothing is sent, as the chain
680
+ * verbs refuse a segment a collaborator holds ({@link guardCollabLock}): a write beside a
681
+ * collaborator's armed reshape would be overwritten by their save, or overwrite it. The reader's
682
+ * own lock is no refusal, so a form saves beside its own reshape.
683
+ *
684
+ * The answer's `overtaken` says whether a newer write of the zone answered first
685
+ * ({@link storeWrittenZone}).
686
+ *
687
+ * A zone whose scope takes no zone, a personal one or one of an organization whose agreement does
688
+ * not include Map Studio, is refused before anything is sent ({@link refuseZoneScope}), as the
689
+ * session knows its organization: it stays readable and deletable.
690
+ */
691
+ export const updateZone: StudioToolDefinition<"studio.zone.update"> = {
692
+ handler: async (ctx, input) => {
693
+ const locked = guardCollabLock(ctx, "zone", input.zoneId);
694
+ if (locked) {
695
+ return locked;
696
+ }
697
+
698
+ const scoped = refuseZoneScope(ctx, savedZoneOrganization(ctx, input.zoneId));
699
+ if (scoped) {
700
+ return scoped;
701
+ }
702
+
703
+ if (!ctx.api) {
704
+ return { code: "no-api", error: "update zone: no persistence seam", ok: false };
705
+ }
706
+
707
+ const { description, endAt, geojson, isPrivate, level, name, source, startAt, zoneId } = input;
708
+ // The armed draft as the write leaves, which tells a reshape recorded meanwhile from it.
709
+ const sentDraft = armedDraftOf(ctx, zoneId);
710
+ // Each member of the metadata partial (name, description, level, start/end bounds) reaches
711
+ // its wire name as given, preserving the null-vs-undefined distinction: a present null
712
+ // CLEARS a description or a bound (JSON.stringify serializes it as `null`), an omitted
713
+ // field stays undefined and is dropped (carried forward). A `?? undefined` on those would
714
+ // collapse a user's clear into an omission, so the server would keep the old value.
715
+ const updated = await updateZoneRequest(ctx.api.client, zoneId, {
716
+ description,
717
+ end_at: endAt,
718
+ geojson: geojson ? zoneFeature(geojson.geometry) : undefined,
719
+ is_private: isPrivate,
720
+ level,
721
+ name,
722
+ // A present source recomputes the geometry; undefined AND null both carry
723
+ // the source forward (the server treats null as absent): only a geojson reshape
724
+ // detaches it. Mutually exclusive with geojson (enforced above).
725
+ source,
726
+ start_at: startAt,
727
+ });
728
+
729
+ // A newer write of this zone may have answered first. Its zone is then the one cached and
730
+ // bound, and it holds what this write stored, so what follows draws from the zone that stands.
731
+ const stands = storeWrittenZone(ctx, ctx.api.cache, updated);
732
+
733
+ // The published read takes the zone's privacy from the draft at once, so a privacy change
734
+ // moves what the public is served even though nothing was published. Only that entry is
735
+ // named: the draft's key is a prefix of it, and naming the draft would also drop the answer
736
+ // just written there. The write has landed, whichever answer stands, so a cache that fails
737
+ // to mark it fails nothing.
738
+ if (isPrivate !== undefined) {
739
+ void invalidateLanded(ctx.api.cache, { id: zoneId, kind: "zone", surface: "published" });
740
+ }
741
+
742
+ if (stands === null) {
743
+ return deletedSinceAnswer(`Updated zone ${zoneId}.`);
744
+ }
745
+
746
+ const overtaken = stands !== updated;
747
+
748
+ // A geometry change (a source recompute or a geojson reshape) or a severity
749
+ // (level) change both alter what the persisted zone tile paints (its shape or
750
+ // its color), so bust the zone tile source, exactly as studio.zone.recompute
751
+ // does, for the unarmed / after-teardown case. An explicit `source: null` is a
752
+ // carry-forward ("no change", the wire treats null as absent), NOT a recompute,
753
+ // so it does not count as a geometry change. A metadata-only update that touches
754
+ // neither (a description, a date-window edit, or a carry-forward source) renders
755
+ // identically and skips the bust to avoid needless churn.
756
+ const geometryChanged = source != null || geojson !== undefined;
757
+ if (geometryChanged || level !== undefined) {
758
+ ctx.map?.refreshZoneTiles();
759
+ }
760
+
761
+ // A zone opens straight into edit mode, so the busted tile stays hidden behind
762
+ // the edit exclusion until teardown: mirror the change onto the LIVE armed
763
+ // draft so it shows at once. A geometry change re-seeds the drawn shape; a
764
+ // level change recolors through the session level, the SAME seam
765
+ // studio.zone.setLevel drives (the zone editing hook reacts and restyles the
766
+ // draft), NEVER a geometry reseed, which would clobber an in-progress reshape.
767
+ // reseedArmedZoneAfterPersist self-guards on this zone; the recolor guards here.
768
+ if (geometryChanged) {
769
+ reseedArmedZoneAfterPersist(ctx, stands, sentDraft);
770
+ }
771
+
772
+ if (level !== undefined && ctx.ui.getState().zoneEditSession?.zoneId === zoneId) {
773
+ // An overtaken write's severity may have been replaced by the newer one's.
774
+ ctx.ui.getState().setZoneEditLevel(overtaken ? stands.level : level);
775
+ }
776
+
777
+ return {
778
+ data: { overtaken },
779
+ ok: true,
780
+ summary: overtaken
781
+ ? `Updated zone ${zoneId}. A newer write of it answered first.`
782
+ : `Updated zone ${zoneId}.`,
783
+ };
784
+ },
785
+ };
786
+
787
+ /**
788
+ * recomputeZone refreshes a COMPUTED zone's geometry from its stored reachability query. It
789
+ * resolves the target (the explicit zoneId, else the active zone the panel is bound to), reads
790
+ * its `source`, and:
791
+ * - a HAND-DRAWN zone (source null) has no query to recompute, so it returns a
792
+ * structured `invalid-input` failure with a plain-language reason;
793
+ * - a COMPUTED zone re-sends the stored source through the update PUT, so the server
794
+ * regenerates the authoritative polygon (no dedicated recompute endpoint exists: a refresh
795
+ * IS a PUT of the stored source), then it evicts the zone's detail cache, rebinds the active
796
+ * slot when the recomputed zone is the open one, busts the zone tiles, and re-seeds the armed
797
+ * TerraDraw draft so the new shape paints live (a zone opens into edit mode, so the busted
798
+ * tile alone stays hidden behind the edit exclusion until a close and reopen).
799
+ *
800
+ * It regenerates parameters the user already approved (the reachability query is unchanged:
801
+ * only the world it measures may have changed), so it does NOT set requiresConfirmation.
802
+ * Agent-VISIBLE: a co-pilot can refresh a stale reachability zone. Persisting, so it needs the
803
+ * api seam.
804
+ *
805
+ * A zone a collaborator holds is refused with `collab-locked` before anything is read or sent,
806
+ * as {@link updateZone} refuses it, and a zone whose scope takes no zone once its record is read
807
+ * ({@link refuseZoneScope}). The answer's `overtaken` says whether a newer write of the zone
808
+ * answered first, as an update's does.
809
+ */
810
+ export const recomputeZone: StudioToolDefinition<"studio.zone.recompute"> = {
811
+ handler: async (ctx, input) => {
812
+ if (!ctx.api) {
813
+ return { code: "no-api", error: "recompute zone: no persistence seam", ok: false };
814
+ }
815
+
816
+ // Resolve the target: an explicit id, else the zone the panel is bound to.
817
+ const zoneId = input.zoneId ?? ctx.ui.getState().activeZone?.id ?? null;
818
+ if (!zoneId) {
819
+ return {
820
+ code: "invalid-input",
821
+ error: "recompute zone: no zone is named and none is open, so pass a zoneId",
822
+ ok: false,
823
+ };
824
+ }
825
+
826
+ const locked = guardCollabLock(ctx, "zone", zoneId);
827
+ if (locked) {
828
+ return locked;
829
+ }
830
+
831
+ // Read the source off the canonical zone: the open slot when it is the target
832
+ // (already the full Zone), else a fetch (an explicit id need not be the open one).
833
+ const activeZone = ctx.ui.getState().activeZone;
834
+ const zone = activeZone?.id === zoneId ? activeZone : await fetchZone(ctx.api.client, zoneId);
835
+
836
+ const scoped = refuseZoneScope(ctx, zone.organization_id);
837
+ if (scoped) {
838
+ return scoped;
839
+ }
840
+
841
+ const source = zone.source;
842
+ if (!source) {
843
+ return {
844
+ code: "invalid-input",
845
+ error: "this zone was drawn by hand: it has no reachability query to recompute",
846
+ ok: false,
847
+ };
848
+ }
849
+
850
+ // The armed draft as the write leaves, which tells a reshape recorded meanwhile from it.
851
+ const sentDraft = armedDraftOf(ctx, zoneId);
852
+
853
+ // Re-send the stored source: the server recomputes the polygon and returns the
854
+ // refreshed zone. No recompute endpoint exists: a refresh is a PUT of the source.
855
+ const updated = await updateZoneRequest(ctx.api.client, zoneId, { source });
856
+ // A newer write of this zone may have answered first. What it stored is then what the studio
857
+ // holds, the recomputed shape included, so what follows draws from the zone that stands.
858
+ const stands = storeWrittenZone(ctx, ctx.api.cache, updated);
859
+ if (stands === null) {
860
+ return deletedSinceAnswer(`Recomputed zone ${zoneId} from its reachability query.`);
861
+ }
862
+
863
+ const overtaken = stands !== updated;
864
+
865
+ // The recompute changes the geometry, so bust the zone tiles (unlike a
866
+ // metadata-only update): the new shape paints at the current camera without a
867
+ // pan/zoom, the same post-mutation refresh the create/delete paths run. A
868
+ // render-free context (no map) is a no-op.
869
+ ctx.map?.refreshZoneTiles();
870
+
871
+ // A zone opens into edit mode, so the recomputed shape must also re-seed the
872
+ // armed TerraDraw draft, or the busted tile stays hidden behind the edit
873
+ // exclusion and the user sees the change only after a close/reopen. A no-op
874
+ // when this zone is not the open one.
875
+ reseedArmedZoneAfterPersist(ctx, stands, sentDraft);
876
+
877
+ return {
878
+ data: { overtaken },
879
+ ok: true,
880
+ summary: overtaken
881
+ ? `Recomputed zone ${zoneId} from its reachability query. A newer write of it answered first.`
882
+ : `Recomputed zone ${zoneId} from its reachability query.`,
883
+ };
884
+ },
885
+ };
886
+
887
+ /**
888
+ * reachabilityPreview computes the reachability bands the zone panel paints on
889
+ * the map while the user configures a computed zone, WITHOUT persisting anything.
890
+ * It maps the activity to the Data-API enum, computes the isochrones in one call
891
+ * (the query returns one polygon per range value), and writes the band polygons,
892
+ * the origin and the level onto the zonePreview slot the preview-sync hook reads.
893
+ * An empty `ranges` clears the slot (the panel's close/teardown path), so no
894
+ * request fires.
895
+ *
896
+ * It SHORT-CIRCUITS when the shape inputs are unchanged. Every isochrones call is an upstream
897
+ * computation, and the panel is a live form: recoloring a band by severity, or re-picking the
898
+ * value it already holds, must not spend an upstream call to repaint something the client
899
+ * already has. The identity is {@link zonePreviewQueryKey}, which covers only what changes the SHAPE,
900
+ * so a level or origin-only redraw updates the slot in place and returns without a request.
901
+ *
902
+ * It is a Data API READ that paints a transient overlay: nothing persists. agentHidden: it is
903
+ * the panel's own preview seam, not an agent action (a co-pilot proposes a computed zone
904
+ * through editPropose, which paints its own live draft).
905
+ *
906
+ * An answer writes the slot only while it is the one awaited. The request takes a serial from
907
+ * the store as it leaves (`beginZonePreviewRequest`) and the bands are written only if the store
908
+ * still reads that serial when they land. A later preview, a repaint and a clear each move it,
909
+ * so a slow answer never replaces a newer preview and never repaints bands a clear took away.
910
+ * Such an answer is dropped with `ok: true`: its request did what it was asked.
911
+ */
912
+ export const reachabilityPreview: StudioToolDefinition<"studio.zone.reachabilityPreview"> = {
913
+ agentHidden: true,
914
+ handler: async (ctx, input) => {
915
+ // An empty band set is the clear signal: drop the overlay and skip the request.
916
+ if (input.ranges.length === 0) {
917
+ ctx.ui.getState().setZonePreview(null);
918
+
919
+ return { ok: true, summary: "Cleared the reachability preview." };
920
+ }
921
+
922
+ const queryKey = zonePreviewQueryKey(input);
923
+ const current = ctx.ui.getState().zonePreview;
924
+
925
+ // Same shape, different paint: reuse the bands already on the slot. This is
926
+ // what keeps a severity recolor off the network: the bands are identical, so
927
+ // re-requesting them would spend an upstream call to receive what we hold.
928
+ if (current !== null && current.queryKey === queryKey) {
929
+ ctx.ui.getState().setZonePreview({
930
+ ...current,
931
+ // The activity rides along with the paint, not the bands: it is folded into
932
+ // the query key, so a matching key means the same activity. Carrying it
933
+ // explicitly is what keeps the slot self-describing for the origin marker.
934
+ activity: input.activity,
935
+ level: input.level,
936
+ origin: input.location,
937
+ });
938
+
939
+ return {
940
+ data: { count: current.bands.length },
941
+ ok: true,
942
+ summary: "Repainted the reachability preview from the current bands.",
943
+ };
944
+ }
945
+
946
+ const resolved = requireData(ctx);
947
+ if ("ok" in resolved) {
948
+ return resolved;
949
+ }
950
+
951
+ // The question is numbered as it leaves, and its answer is written only while the store
952
+ // still reads the number: a later question, a write and a clear each move it.
953
+ const asked = ctx.ui.getState().beginZonePreviewRequest();
954
+
955
+ try {
956
+ // Nothing names the studio here: the session token the client carries is what the API
957
+ // records the preview under.
958
+ const result = await resolved.client.data.isochrones({
959
+ activity: toDataActivity(input.activity),
960
+ // A single origin; spread the tuple to a fresh mutable pair the query takes.
961
+ locations: [[...input.location]],
962
+ range: input.ranges,
963
+ rangeType: rangeTypeToData(input.rangeType),
964
+ speed: input.speed,
965
+ });
966
+
967
+ // Each isochrone is one preview band: its polygon and its range value. The Data API
968
+ // types the geometry as any GeoJSON geometry, so its shape is read before it is drawn.
969
+ const bands: ZonePreviewBand[] = [];
970
+ for (const iso of result.isochrones) {
971
+ if (!isPolygonGeometry(iso.geometry)) {
972
+ return {
973
+ code: "internal",
974
+ error: `reachability preview: the band at ${iso.value} is no polygon`,
975
+ ok: false,
976
+ };
977
+ }
978
+
979
+ bands.push({ geometry: iso.geometry, value: iso.value });
980
+ }
981
+
982
+ if (ctx.ui.getState().zonePreviewSerial !== asked) {
983
+ return {
984
+ ok: true,
985
+ summary: "Dropped a reachability preview that a later one, or a clear, superseded.",
986
+ };
987
+ }
988
+
989
+ ctx.ui.getState().setZonePreview({
990
+ activity: input.activity,
991
+ bands,
992
+ level: input.level,
993
+ origin: input.location,
994
+ queryKey,
995
+ });
996
+
997
+ return {
998
+ data: { count: bands.length },
999
+ ok: true,
1000
+ summary: `Previewed ${bands.length} reachability band${bands.length === 1 ? "" : "s"}.`,
1001
+ };
1002
+ } catch (error) {
1003
+ const failure = failureFromThrown(error);
1004
+
1005
+ // The upstream sentence rides as `detail`, the slot for a message the server already
1006
+ // wrote in the reader's language, and the thrown sentence stands in where the throw
1007
+ // carried none. It matters here more than elsewhere: no routable way near the origin, and
1008
+ // an activity that cannot be routed, are each fixed by changing one field, and the copy
1009
+ // of a code can only say that some details are invalid.
1010
+ return { ...failure, detail: failure.detail ?? failure.error };
1011
+ }
1012
+ },
1013
+ };
1014
+
1015
+ /**
1016
+ * deleteZone permanently deletes a zone. It is destructive, so it sets `requiresConfirmation`:
1017
+ * the bus prompts through `ctx.confirm` before the handler runs, as it does for the itinerary,
1018
+ * segment and waypoint deletes.
1019
+ *
1020
+ * Everything it decides from the store it decides before its request. When the deleted zone is
1021
+ * the one the zone surface shows, the surface is closed as its own back closes it
1022
+ * ({@link returnFromZoneSurface}), and the band preview is dropped, both at once. The surface
1023
+ * shows the zone its slot names, or the one the armed zone session names when the slot names
1024
+ * none, which is a proposal's reshape: that session ends with its engine and its lock. The
1025
+ * reader lands on what the surface was opened over: the itinerary they were editing, whose slot
1026
+ * and URL key are left as they are, or the list where there is none. A session armed on the
1027
+ * zone under another surface is torn down where it is, and a slot that outlived its surface is
1028
+ * cleared, with nothing else closed. Nothing is read before the request
1029
+ * and acted on after it, so whatever the reader opens while the request is out stays open. A
1030
+ * request that fails leaves the surface closed, with the zone still there to open again. Once
1031
+ * the zone is deleted its id is recorded ({@link recordZoneDeleted}), its own cache entry is
1032
+ * removed where the cache states an `evict` ({@link evictResources}), the zone tiles are asked
1033
+ * for again, so it disappears at the current zoom, and its entry, every zone listing, every
1034
+ * collection listing and every collection's zones are marked stale ({@link invalidateLanded}),
1035
+ * which is all a cache with no `evict` is told. A
1036
+ * cache that throws as it evicts or as it marks an entry stale fails none of it: the delete is
1037
+ * made, and it is answered `ok`. Persisting, so it needs the api seam.
1038
+ *
1039
+ * A zone a collaborator holds is refused with `collab-locked`, as {@link updateZone} refuses it.
1040
+ * The refusal is the tool's `precondition`, so the reader is not asked to confirm a delete that
1041
+ * cannot run, and the handler reads the lock again, since one may land while they are asked.
1042
+ */
1043
+ export const deleteZone: StudioToolDefinition<"studio.zone.delete"> = {
1044
+ // Deleting a whole zone is high-stakes, so it gates behind an "I understand…"
1045
+ // acknowledge and carries its own title/body/confirm copy for the shared confirm
1046
+ // dialog ("Delete zone" rather than the generic prompt).
1047
+ confirmation: {
1048
+ acknowledgeLabel: "confirm.deleteZoneAcknowledge",
1049
+ confirmLabel: "confirm.delete",
1050
+ descriptionLabel: "confirm.deleteZone.body",
1051
+ titleLabel: "confirm.deleteZone.title",
1052
+ },
1053
+ handler: async (ctx, input) => {
1054
+ // Read again: a collaborator may have taken the zone while the reader was asked.
1055
+ const locked = guardCollabLock(ctx, "zone", input.zoneId);
1056
+ if (locked) {
1057
+ return locked;
1058
+ }
1059
+
1060
+ if (!ctx.api) {
1061
+ return { code: "no-api", error: "delete zone: no persistence seam", ok: false };
1062
+ }
1063
+
1064
+ // Deleting the open zone closes its surface, since its panel has nothing left to edit, which
1065
+ // also ends an armed reshape. The itinerary the surface was opened over is left open, so the
1066
+ // reader lands back on it, and on the list where there is none. Deleting another zone leaves
1067
+ // the view as it is. Read and acted on here, before the first await: nothing is read now and
1068
+ // acted on later, so nothing the reader opens while the request is out is closed by it.
1069
+ const ui = ctx.ui.getState();
1070
+ const isBound = ui.activeZone?.id === input.zoneId;
1071
+ const isArmed = ui.zoneEditSession?.zoneId === input.zoneId;
1072
+ // The zone the surface shows: the one its slot names, or the armed session's when the slot
1073
+ // names none, which is a proposal's reshape.
1074
+ const isShown =
1075
+ ui.openContent === "zone" &&
1076
+ (ui.activeZone?.id ?? ui.zoneEditSession?.zoneId) === input.zoneId;
1077
+
1078
+ if (isShown) {
1079
+ returnFromZoneSurface(ctx);
1080
+ } else {
1081
+ if (isArmed) {
1082
+ // One authoring session is armed at a time, so the one torn down is the zone's.
1083
+ teardownActiveEditSession(ctx);
1084
+ }
1085
+
1086
+ if (isBound) {
1087
+ ctx.ui.getState().setActiveZone(null);
1088
+ }
1089
+ }
1090
+
1091
+ // The band preview goes with the zone whether or not it was the open one. The tiles hold a
1092
+ // zone's fill and its points and no line, so the contour rings and the origin marker of a
1093
+ // reachability zone are the preview overlay alone, which the tiles' refresh cannot reach.
1094
+ // Dropped before the request for the same reason as the leave: a preview the reader asks
1095
+ // for while the request is out is theirs.
1096
+ ctx.ui.getState().setZonePreview(null);
1097
+
1098
+ await deleteZoneRequest(ctx.api.client, input.zoneId);
1099
+
1100
+ // The server has confirmed the delete: from here the answer of a write of this zone that
1101
+ // was out is written nowhere, whatever the cache still holds for it.
1102
+ recordZoneDeleted(ctx, input.zoneId);
1103
+
1104
+ // No read will replace the zone's own entry: a cache that can remove it does, so no later
1105
+ // read answers a zone that is gone. A cache that fails to remove it changes nothing here,
1106
+ // since the eviction holds its own fault.
1107
+ evictResources(ctx.api.cache, { id: input.zoneId, kind: "zone" });
1108
+
1109
+ // The zone is gone from the tiles the server answers now, so asking for them again clears
1110
+ // it at the current zoom. A context with no map has nothing to refresh.
1111
+ ctx.map?.refreshZoneTiles();
1112
+
1113
+ // The zone's own entry, every zone listing, every collection listing and every collection's
1114
+ // zones are marked stale, as a collaborator's delete of it marks them: the collections that
1115
+ // held it count one fewer, and every collection listing serves those counts, as an
1116
+ // itinerary's delete marks them. A cache that states no `evict` is told through this alone.
1117
+ // The delete has landed, so a cache that fails here fails nothing.
1118
+ await invalidateLanded(
1119
+ ctx.api.cache,
1120
+ { id: input.zoneId, kind: "zone" },
1121
+ { kind: "zones" },
1122
+ { kind: "collections" },
1123
+ { kind: "collectionZones" },
1124
+ );
1125
+
1126
+ return { ok: true, summary: `Deleted zone ${input.zoneId}.` };
1127
+ },
1128
+ precondition: (ctx, input) => guardCollabLock(ctx, "zone", input.zoneId),
1129
+ requiresConfirmation: true,
1130
+ };
1131
+
1132
+ /**
1133
+ * zoneEditBegin opens the store's zone edit session: the single record the map seam and the
1134
+ * zone editing hook both read to arm the TerraDraw zone engine and surface the in-flight draft.
1135
+ * It enforces mutual exclusion across families: a dispatch while another session (segment,
1136
+ * waypoint, OR zone) is armed returns `edit-in-progress` and the store stays untouched. On
1137
+ * accept it is a pure store write: the zone editing hook drives beginZoneEdit on the map from
1138
+ * the resulting session, so the engine-arming layer stays inside the map abstraction and the
1139
+ * tool never races a not-yet-mounted map. This is the panel-driven entry point (an empty draft
1140
+ * on create, a seeded shape on edit); the agent's geometry proposal uses editPropose.
1141
+ *
1142
+ * Editing. It also mounts the zone panel. Arming a draw engine without the surface that
1143
+ * explains it leaves the user with a changed cursor and no way to read why, which is what a
1144
+ * click on a zone bound by a create produces without this. A caller that already opened the
1145
+ * surface is unaffected: the slot is idempotent.
1146
+ *
1147
+ * A scope that takes no zone is refused before anything is armed or locked
1148
+ * ({@link refuseZoneScope}): the organization a create names, and a saved zone's own.
1149
+ */
1150
+ export const zoneEditBegin: StudioToolDefinition<"studio.zone.editBegin"> = {
1151
+ handler: async (ctx, input) => {
1152
+ const scoped = refuseZoneScope(
1153
+ ctx,
1154
+ input.intent === "create" ? input.organizationId : savedZoneOrganization(ctx, input.zoneId),
1155
+ );
1156
+ if (scoped) {
1157
+ return scoped;
1158
+ }
1159
+
1160
+ // The gate, then the collaboration lock, then the gate again. A zone edit stays armed
1161
+ // across a commit, so the lock is held for the session's life and released on cancel or on
1162
+ // the teardown of a leave, never on commit. A context with no collaboration seam takes
1163
+ // none.
1164
+ const refused = await lockZoneForEdit(ctx, input.zoneId);
1165
+ if (refused) {
1166
+ return refused;
1167
+ }
1168
+
1169
+ ctx.ui.getState().beginZoneEdit({
1170
+ intent: input.intent,
1171
+ level: input.level,
1172
+ mode: input.mode,
1173
+ organizationId: input.organizationId ?? null,
1174
+ seedGeometry: input.seedGeometry,
1175
+ zoneId: input.zoneId,
1176
+ });
1177
+ ctx.ui.getState().setOpenContent("zone");
1178
+
1179
+ return { ok: true, summary: `Started editing zone ${input.zoneId}.` };
1180
+ },
1181
+ };
1182
+
1183
+ /**
1184
+ * zoneSetLevel changes the severity level on the active zone edit session. It is a pure store
1185
+ * write: the zone editing hook reacts to the session level change and recolors the live draft
1186
+ * through setZoneDraftStyle, so the engine recolor stays inside the map abstraction. A no-op
1187
+ * against no open session (the store setter guards it). It is the panel's severity-picker seam,
1188
+ * the parallel of the segment recolor; on a SAVED zone the committed level is persisted through
1189
+ * the editCommit (a reshape) or studio.zone.update (metadata-only).
1190
+ */
1191
+ export const zoneSetLevel: StudioToolDefinition<"studio.zone.setLevel"> = {
1192
+ handler: (ctx, input) => {
1193
+ ctx.ui.getState().setZoneEditLevel(input.level);
1194
+
1195
+ return { ok: true, summary: `Set the zone severity to ${input.level}.` };
1196
+ },
1197
+ };
1198
+
1199
+ /**
1200
+ * lockZoneForEdit runs what every entry into a zone's edit session runs before it arms: the
1201
+ * one-edit-at-a-time gate, then the zone's collaboration lock, then the gate again. It answers
1202
+ * the refusal, or null when the session is the caller's to arm.
1203
+ *
1204
+ * The lock is awaited, so the gate's first answer is stale by the time it is granted: an edit
1205
+ * begun meanwhile would be replaced by the session about to open. Asked again, the gate refuses
1206
+ * it, and the lock just taken is given back, since no session will hold it. The second read is
1207
+ * {@link guardEditBeginUnderLock}, the one the segment and the waypoint begins make.
1208
+ */
1209
+ const lockZoneForEdit = async (
1210
+ ctx: StudioToolContext,
1211
+ zoneId: string,
1212
+ ): Promise<ToolFailure | null> => {
1213
+ const blocked = guardEditBegin(ctx.ui.getState(), { kind: "zone", zoneId });
1214
+ if (blocked) {
1215
+ return blocked;
1216
+ }
1217
+
1218
+ const locked = await acquireCollabLock(ctx, "zone", zoneId);
1219
+ if (locked) {
1220
+ return locked;
1221
+ }
1222
+
1223
+ return guardEditBeginUnderLock(ctx, { kind: "zone", zoneId });
1224
+ };
1225
+
1226
+ /** polygonOf is a saved zone's shape when it is a Polygon, and null for a point or no zone. */
1227
+ const polygonOf = (zone: Zone | null): Polygon | null => {
1228
+ const geometry = zone?.geojson.geometry;
1229
+
1230
+ return geometry?.type === "Polygon" ? geometry : null;
1231
+ };
1232
+
1233
+ /**
1234
+ * ProposeGeometry is one resolved proposal geometry: the Polygon to seed the draft
1235
+ * and the zone mode it authors under. A Feature branch always carries a Polygon, so
1236
+ * it authors the generic "polygon" mode (a parametric circle/sector/sensor goes
1237
+ * through its own branch and fixes its own mode).
1238
+ */
1239
+ interface ProposeGeometry {
1240
+ geometry: Polygon;
1241
+ mode: ZoneMode;
1242
+ }
1243
+
1244
+ /**
1245
+ * resolveProposeGeometry turns a discriminated proposal-geometry input into the seed geometry
1246
+ * and the zone mode it implies. The parametric branches build a Polygon through the shared
1247
+ * geometry rules (the same shapes the TerraDraw circle, sector and sensor modes draw), so the
1248
+ * agent passes a spec rather than coordinates; the feature branch passes its geometry through
1249
+ * and derives the mode from its kind. Pure (no I/O and no store writes), so the handler can
1250
+ * resolve it before guarding the edit lock.
1251
+ */
1252
+ const resolveProposeGeometry = (
1253
+ input: z.infer<(typeof studioToolContracts)["studio.zone.editPropose"]["input"]>["geometry"],
1254
+ ): ProposeGeometry => {
1255
+ switch (input.kind) {
1256
+ case "circle":
1257
+ return { geometry: zoneCircleGeometry(input.circle), mode: "circle" };
1258
+ case "sector":
1259
+ return { geometry: zoneSectorGeometry(input.sector), mode: "sector" };
1260
+ case "sensor":
1261
+ return { geometry: zoneSensorGeometry(input.sensor), mode: "sensor" };
1262
+ default:
1263
+ return { geometry: input.feature.geometry, mode: "polygon" };
1264
+ }
1265
+ };
1266
+
1267
+ /**
1268
+ * zoneEditPropose is the agent's hand-off of a zone: it persists nothing, and fills a live,
1269
+ * editable draft with the proposed shape, name, severity and organization for the user to adjust
1270
+ * and to save or cancel themselves. A geometry an agent changes is always confirmed by a person.
1271
+ *
1272
+ * The id decides what the proposal is:
1273
+ *
1274
+ * - **A reshape**, when it names the zone the panel is bound to, or the saved zone a reshape is
1275
+ * already armed on. The zone stays bound, its name and organization stay its own, and the
1276
+ * session is an `edit` whose baseline is the shape the zone is saved with, so the proposal reads
1277
+ * unsaved and the user's Save updates that zone.
1278
+ * - **A new zone**, under any other id. The panel's zone is unbound and the draft is a `create`.
1279
+ * The id of a saved zone that is not open is one of these, since nothing here reads whether an
1280
+ * id is saved: the tool's description sends its caller to `studio.zone.openForEdit` first.
1281
+ *
1282
+ * **The proposal fills every field as one step, and the reader undoes it.** Over a draft armed on
1283
+ * its zone, a create or a reshape, an earlier proposal's or the reader's own, the proposal is one
1284
+ * more step of that edit's history (`pushZoneDraft`, with its shape, mode, source, severity, name
1285
+ * and organization) and is written onto the map's editing feature: one undo returns the shape and
1286
+ * every field beside it to what stood before. A proposal of a new zone over a create with nothing
1287
+ * drawn, the create surface open with no draft armed or a draw armed with no shape in it, opens
1288
+ * the draft on the reader's own fields, the severity they picked (`zoneCreatePickedLevel`, or the
1289
+ * armed draw's) and the name and organization their form shows, and lands on it as one step: the
1290
+ * map cannot drop a shape, so its undo keeps the shape and gives back what the reader had set.
1291
+ * The step is drawn in the mode its proposal came as, which the session takes with it, so a
1292
+ * create is saved under the mode of the shape that is saved and an undo restores the mode of the
1293
+ * shape it lands on. A proposal of a new zone over a reachability create switches it to a drawn
1294
+ * one and clears the band preview, since the draft now holds the shape and the query it came
1295
+ * from rides the session.
1296
+ *
1297
+ * With no create open the proposal starts one of its own (`resetZoneCreate`), which inherits
1298
+ * nothing from the last, and opens its draft. So does a reshape of a bound zone no draft is armed
1299
+ * on, a computed zone or one saved as a point, and of an edit armed with no shape, which keeps
1300
+ * the saved shape that edit compares against. None of them has a step to undo: the reader
1301
+ * cancels it.
1302
+ *
1303
+ * The answer's `stepped` says whether the proposal landed as a step.
1304
+ *
1305
+ * It resolves the discriminated geometry first (a circle, a sector or a sensor built by the
1306
+ * shared geometry rules, or the caller's Feature as it is), which states the mode the shape is
1307
+ * drawn in. It refuses, through {@link guardEditBegin}, while another engine is armed, and it
1308
+ * takes the zone's collaboration lock before arming, as `studio.zone.editBegin` does: a zone a
1309
+ * peer holds answers `collab-locked`, and the lock is held for the session's life. The gate is
1310
+ * asked again once the lock is granted, since an edit may have begun while it was awaited.
1311
+ */
1312
+ export const zoneEditPropose: StudioToolDefinition<"studio.zone.editPropose"> = {
1313
+ handler: async (ctx, input) => {
1314
+ const resolved = resolveProposeGeometry(input.geometry);
1315
+
1316
+ // The scope is read before the lock is asked for, as the reshape it proposes stands: a saved
1317
+ // zone's own, or the organization a new zone's proposal or its armed draw names.
1318
+ const before = ctx.ui.getState();
1319
+ const armedBefore =
1320
+ before.zoneEditSession?.zoneId === input.zoneId ? before.zoneEditSession : null;
1321
+ const reshaping = before.activeZone?.id === input.zoneId || armedBefore?.intent === "edit";
1322
+ const scoped = refuseZoneScope(
1323
+ ctx,
1324
+ reshaping
1325
+ ? savedZoneOrganization(ctx, input.zoneId)
1326
+ : (input.organizationId ?? armedBefore?.organizationId ?? undefined),
1327
+ );
1328
+ if (scoped) {
1329
+ return scoped;
1330
+ }
1331
+
1332
+ const refused = await lockZoneForEdit(ctx, input.zoneId);
1333
+ if (refused) {
1334
+ return refused;
1335
+ }
1336
+
1337
+ const state = ctx.ui.getState();
1338
+ // The session armed on this zone, which the gate admits a proposal onto: the co-pilot
1339
+ // iterating on its own proposal, a draw the reader began, or a reshape the reader opened.
1340
+ const armed = state.zoneEditSession?.zoneId === input.zoneId ? state.zoneEditSession : null;
1341
+ const boundZone = state.activeZone?.id === input.zoneId ? state.activeZone : null;
1342
+ const reshapes = boundZone !== null || armed?.intent === "edit";
1343
+ // The create surface a proposal of a new zone joins when no draft is armed on its zone: the
1344
+ // surface showing with no zone bound. Read before the surface is opened below.
1345
+ const joins =
1346
+ !reshapes && armed === null && state.openContent === "zone" && state.activeZone === null;
1347
+ // What the proposal fills beside the shape. A saved zone's name and organization are its own;
1348
+ // a create keeps the ones already on its draft where the proposal states none.
1349
+ const filled = {
1350
+ level: input.level,
1351
+ mode: resolved.mode,
1352
+ name: reshapes ? null : (input.name ?? armed?.name ?? null),
1353
+ organizationId: reshapes ? null : (input.organizationId ?? armed?.organizationId ?? null),
1354
+ source: input.source ?? null,
1355
+ };
1356
+
1357
+ state.setOpenContent("zone");
1358
+ // No navigation: the zone surface renders over an open itinerary, and the detail keys left
1359
+ // in the url are what a close of the surface falls back to.
1360
+ if (!reshapes) {
1361
+ state.setActiveZone(null);
1362
+ // A create the proposal fills is drawn: the draft holds the shape, and the query it came
1363
+ // from rides the session. A reachability create switches over, and its bands leave the map.
1364
+ if (state.zoneCreateMethod === "reachability") {
1365
+ state.setZoneCreateMethod("draw");
1366
+ state.setZonePreview(null);
1367
+ }
1368
+ }
1369
+
1370
+ // Whether the proposal landed as a step of a draft its reader had, which an undo takes back.
1371
+ let stepped = true;
1372
+ if (armed !== null && armed.draft !== null) {
1373
+ // The draft stays the one its reader has, with its history and its baseline, and the
1374
+ // proposal is one more step of it. The armed engine is handed the shape at once, as a
1375
+ // programmatic write that records no history of its own; where the step moved the
1376
+ // session's mode, a map binding then arms the engine again under that mode, from the draft.
1377
+ state.pushZoneDraft(resolved.geometry, filled);
1378
+ ctx.map?.applyZoneDraft(resolved.geometry);
1379
+ } else if (reshapes) {
1380
+ // A bound zone no draft is armed on, or an edit armed with no shape. The baseline is the
1381
+ // one the armed edit already compares against, and otherwise the shape the zone is saved
1382
+ // with, which a zone saved as a point has none of. Nothing stood before the shape, so there
1383
+ // is no step to undo.
1384
+ stepped = false;
1385
+ const baseline = armed === null ? polygonOf(boundZone) : armed.savedGeometry;
1386
+ state.beginZoneEdit({
1387
+ intent: "edit",
1388
+ level: filled.level,
1389
+ mode: filled.mode,
1390
+ seedGeometry: resolved.geometry,
1391
+ source: input.source,
1392
+ zoneId: input.zoneId,
1393
+ });
1394
+ ctx.ui.getState().setZoneSavedGeometry(baseline);
1395
+ } else if (armed !== null || joins) {
1396
+ // A create with nothing drawn: a draw its reader armed, or the create surface with none.
1397
+ // The draft opens on the reader's own fields, the severity they picked and the name and
1398
+ // organization the draw or the form holds, a null leaving them to the form, and the
1399
+ // proposal lands on them as one step. The map cannot drop a shape, so the step's undo keeps
1400
+ // the shape and gives back the rest.
1401
+ state.beginZoneEdit({
1402
+ intent: "create",
1403
+ level: armed?.level ?? state.zoneCreatePickedLevel ?? DEFAULT_ZONE_LEVEL,
1404
+ mode: filled.mode,
1405
+ name: armed?.name ?? null,
1406
+ organizationId: armed?.organizationId ?? null,
1407
+ seedGeometry: resolved.geometry,
1408
+ source: input.source,
1409
+ zoneId: input.zoneId,
1410
+ });
1411
+ ctx.ui.getState().pushZoneDraft(resolved.geometry, filled);
1412
+ // A draw armed under the proposal's mode stays armed, keyed on the zone and the mode, and
1413
+ // is handed the shape; under another mode a map binding arms it again from the draft.
1414
+ if (armed !== null) {
1415
+ ctx.map?.applyZoneDraft(resolved.geometry);
1416
+ }
1417
+ } else {
1418
+ // No create is open, so the proposal starts one. It inherits nothing: the proposal states
1419
+ // its own organization, and whatever an earlier create's reader picked is not this one's.
1420
+ stepped = false;
1421
+ state.resetZoneCreate({
1422
+ inheritItinerary: false,
1423
+ method: DEFAULT_ZONE_CREATE_METHOD,
1424
+ origin: null,
1425
+ });
1426
+ state.beginZoneEdit({
1427
+ intent: "create",
1428
+ level: filled.level,
1429
+ mode: filled.mode,
1430
+ name: filled.name,
1431
+ organizationId: filled.organizationId,
1432
+ seedGeometry: resolved.geometry,
1433
+ source: input.source,
1434
+ zoneId: input.zoneId,
1435
+ });
1436
+ }
1437
+
1438
+ return {
1439
+ data: { stepped },
1440
+ ok: true,
1441
+ summary: proposalSentence(resolved.mode, input.zoneId, { reshapes, stepped }),
1442
+ };
1443
+ },
1444
+ };
1445
+
1446
+ /**
1447
+ * proposalSentence is the summary of a proposal: how it landed. A step says what an undo returns
1448
+ * to; any other proposal opened the draft, as a reshape of a saved zone or as a new zone.
1449
+ */
1450
+ const proposalSentence = (
1451
+ mode: ZoneMode,
1452
+ zoneId: string,
1453
+ landed: { reshapes: boolean; stepped: boolean },
1454
+ ): string => {
1455
+ if (landed.stepped) {
1456
+ return landed.reshapes
1457
+ ? `Took the proposed ${mode} shape and severity as one step of the reshape of zone ${zoneId}. Undo returns to what stood before it.`
1458
+ : `Filled the zone draft with the proposed ${mode} shape, severity, name and organization as one step. Undo returns to what stood before it.`;
1459
+ }
1460
+
1461
+ return landed.reshapes
1462
+ ? `Opened a live ${mode} reshape of zone ${zoneId} for the user to adjust and save.`
1463
+ : `Opened a live ${mode} zone draft for the user to adjust and save.`;
1464
+ };
1465
+
1466
+ /**
1467
+ * zoneEditCommit persists the current zone draft and LEAVES THE EDIT ARMED so the saved zone
1468
+ * stays on the map in select/edit mode (the editable shape never vanishes on save). It reads
1469
+ * the drawn geometry off the map (getZoneDraft) and routes the persist by intent: createZone
1470
+ * when authoring a new zone, updateZone when editing a saved zone. Both branches carry the
1471
+ * metadata the panel's single Save collected: a create sends the full new-zone payload, an edit
1472
+ * sends the name, description and time window alongside the reshaped geometry (the level rides
1473
+ * the session), so one commit reconciles every field the edit surface changed.
1474
+ *
1475
+ * On a successful persist it does NOT dispose the engine, does NOT close the session, and does
1476
+ * NOT refetch the zone tiles: the live draft already shows the saved shape and its tile copy
1477
+ * stays suppressed, so a teardown + refetch would only flicker the zone away and back. Instead
1478
+ * it advances the dirty baseline to the just-persisted geometry (so Save disables until the
1479
+ * next reshape) and, on a create, re-keys the session onto the server's id and flips it to an
1480
+ * `edit` (reshape) session: the map re-keys its live engine in place (same shape, no camera
1481
+ * move) when the editing hook re-arms on the id change. Subsequent saves are reshape updates of
1482
+ * that saved zone. On a FAILED persist it leaves the edit open, untouched, so the user can
1483
+ * retry. It needs the api seam.
1484
+ *
1485
+ * What it writes once the persist lands is decided from the store as it stands then, since the
1486
+ * session stays live while the write is out. A reshape recorded meanwhile keeps its draft and
1487
+ * reads unsaved against the persisted baseline ({@link settleZoneCommit}). A session that ended
1488
+ * meanwhile, or gave way to another zone's, is left alone: the panel is not rebound, nothing is
1489
+ * written into the other session, and the zone tiles are asked for again, since no draft covers
1490
+ * the zone any more. On a create, the collaboration lock follows the session onto the id the
1491
+ * server gave the zone, and every zone listing is marked stale, as {@link createZone} marks them,
1492
+ * whether or not the session is still armed.
1493
+ *
1494
+ * A reshape's answer is held to the zone's `revision`, as an update's is
1495
+ * ({@link storeWrittenZone}): one a newer write of the zone overtook replaces neither the cached
1496
+ * zone nor the bound one, and the baseline it settles on is the shape that zone holds.
1497
+ */
1498
+ export const zoneEditCommit: StudioToolDefinition<"studio.zone.editCommit"> = {
1499
+ // Hidden from the model's manifest: the agent never commits an open zone session.
1500
+ // It hands the live draft to the user, who saves it.
1501
+ agentHidden: true,
1502
+ handler: async (ctx, input) => {
1503
+ if (!ctx.api) {
1504
+ return { code: "no-api", error: "commit zone edit: no persistence seam", ok: false };
1505
+ }
1506
+
1507
+ const session = ctx.ui.getState().zoneEditSession;
1508
+ if (!session || session.zoneId !== input.zoneId) {
1509
+ return {
1510
+ code: "no-session",
1511
+ error: "commit zone edit: no active session for this zone",
1512
+ ok: false,
1513
+ };
1514
+ }
1515
+
1516
+ if (!ctx.map) {
1517
+ return {
1518
+ code: "no-map",
1519
+ error: "commit zone edit: no map is mounted to read the draft from",
1520
+ ok: false,
1521
+ };
1522
+ }
1523
+
1524
+ const draft = ctx.map.getZoneDraft();
1525
+ if (!draft) {
1526
+ return {
1527
+ code: "invalid-input",
1528
+ error: "commit zone edit: nothing is drawn yet, so there is no shape to save",
1529
+ ok: false,
1530
+ };
1531
+ }
1532
+
1533
+ // The shape that is saved: the map's own reading, and inside -180 and 180 where the reader
1534
+ // dragged the zone whole past the antimeridian, as the draft seam records it.
1535
+ const drawn = wrapZoneGeometryPastRange(draft.geometry);
1536
+
1537
+ // The store's draft as the write leaves. A reshape recorded while the write is out replaces
1538
+ // it, which is how the settle below tells what the reader drew since from what was sent.
1539
+ const sentDraft = session.draft;
1540
+
1541
+ // A create names its scope, and an absent one is the reader's own space, which holds no zone;
1542
+ // a reshape is in the saved zone's.
1543
+ const scoped =
1544
+ input.intent === "create"
1545
+ ? requireWritableScope(ctx, "zone", input.organizationId)
1546
+ : refuseZoneScope(ctx, savedZoneOrganization(ctx, input.zoneId));
1547
+ if (scoped) {
1548
+ return scoped;
1549
+ }
1550
+
1551
+ if (input.intent === "create") {
1552
+ // The drawn geometry rides as the plain RFC-7946 Feature the wire takes (no
1553
+ // flatten/build: a zone is a single Feature, not a GeometryCollection). No id
1554
+ // is sent: the server mints the zone's, and the session is re-keyed onto it
1555
+ // below.
1556
+ const created = await createZoneRequest(ctx.api.client, {
1557
+ // An empty description is "none", which a create says by leaving it out.
1558
+ description: input.description ? input.description : undefined,
1559
+ end_at: input.endAt ?? undefined,
1560
+ // Honor provenance on save: a session that still carries its computed source
1561
+ // (the user confirmed the proposal without reshaping it) persists that source
1562
+ // and NO geojson, so the server computes the authoritative polygon; a
1563
+ // detached session (a hand reshape cleared the source through pushZoneDraft)
1564
+ // persists the drawn geojson. The two are mutually exclusive on the wire.
1565
+ geojson: session.source ? undefined : zoneFeature(drawn),
1566
+ is_private: input.isPrivate,
1567
+ level: session.level,
1568
+ mode: session.mode,
1569
+ name: input.name,
1570
+ organization_id: input.organizationId,
1571
+ source: session.source ?? undefined,
1572
+ start_at: input.startAt ?? undefined,
1573
+ });
1574
+
1575
+ if (created === null) {
1576
+ // Saved, and nothing names the zone it made. The create session it was drawn in ends with
1577
+ // its surface, as a deleted zone's does: left armed on the id the client minted, a second
1578
+ // Save would create the zone again.
1579
+ const now = ctx.ui.getState();
1580
+ if (now.zoneEditSession?.zoneId === input.zoneId) {
1581
+ if (now.openContent === "zone") {
1582
+ returnFromZoneSurface(ctx);
1583
+ } else {
1584
+ teardownActiveEditSession(ctx);
1585
+ }
1586
+ }
1587
+
1588
+ releaseCollabEntity(ctx, "zone", input.zoneId);
1589
+ await settleSavedUnnamed(ctx);
1590
+
1591
+ return {
1592
+ data: { failedCollectionIds: [...(input.collectionIds ?? [])], zoneId: "" },
1593
+ ok: true,
1594
+ summary: SAVED_UNNAMED,
1595
+ };
1596
+ }
1597
+
1598
+ // Everything below is decided from the store as it stands now, after the write. The
1599
+ // session the commit was sent for may have ended meanwhile, or another may be armed.
1600
+ if (ctx.ui.getState().zoneEditSession?.zoneId === input.zoneId) {
1601
+ // Bind the panel to the saved zone and promote the still-armed session from a create
1602
+ // onto the server's id, as a reshape session. The map binding re-arms on the id and
1603
+ // keeps its engine, mode and geometry, so the drawn shape stays put with no camera
1604
+ // move, and the tile copy of the new zone stays hidden under the live draft.
1605
+ ctx.ui.getState().setActiveZone(created);
1606
+ ctx.ui.getState().rekeyZoneEditSession(created.id);
1607
+ settleZoneCommit(ctx, created.id, sentDraft, drawn);
1608
+
1609
+ // The lock follows the session onto the id a peer can now meet. The one taken on the
1610
+ // id the client minted is given back, and the saved zone's is taken without waiting:
1611
+ // nobody else can hold a zone that did not exist a moment ago.
1612
+ releaseCollabEntity(ctx, "zone", input.zoneId);
1613
+ void acquireCollabLock(ctx, "zone", created.id);
1614
+ } else {
1615
+ // No draft covers the zone the write made, so it is drawn from its tiles. The map is read
1616
+ // again, since a host may have unmounted it while the write was out.
1617
+ ctx.map?.refreshZoneTiles();
1618
+ }
1619
+
1620
+ // A new zone joins every zone listing, as one made by studio.zone.create does. The create
1621
+ // has landed, so a cache that fails to mark them fails nothing of it.
1622
+ await invalidateLanded(ctx.api.cache, { kind: "zones" });
1623
+
1624
+ // Attach the chosen collections best-effort AFTER the create persists: the
1625
+ // zone exists and stays armed for further reshape, so a failed attach must
1626
+ // not fail the commit. It returns the failed ids, which ride in the result
1627
+ // data as a non-fatal signal (mirroring the itinerary create attach).
1628
+ const failedCollectionIds = await attachZoneToCollections(
1629
+ ctx,
1630
+ created.id,
1631
+ input.collectionIds ?? [],
1632
+ );
1633
+
1634
+ return {
1635
+ data: { failedCollectionIds, zoneId: created.id },
1636
+ ok: true,
1637
+ summary: `Saved zone “${created.name}”.`,
1638
+ };
1639
+ }
1640
+
1641
+ // The area is sent only where the shape on the map is not the one the zone was last saved
1642
+ // with: a save of its name, its description, its window or its severity sends none, and the
1643
+ // API carries the stored outline forward unjudged. Sent again, an outline saved before the
1644
+ // API held outlines to its rule would refuse the rename. It is decided from the map, the
1645
+ // shape the save stores and the baseline it settles on, and not from the store's draft,
1646
+ // which a reshape made while the co-pilot drives leaves behind ({@link drawnAsSaved}).
1647
+ const area = !drawnAsSaved(drawn, session.savedGeometry)
1648
+ ? {
1649
+ // Honor provenance on save: a still-computed session recomputes from its source
1650
+ // (the server regenerates the polygon), a detached session persists the drawn
1651
+ // geojson. Mutually exclusive on the wire: the source path sends no geojson.
1652
+ geojson: session.source ? undefined : zoneFeature(drawn),
1653
+ // The mode rides with the shape it describes, so a zone reshaped into a shape of
1654
+ // another kind (a circle proposed onto a polygon) reopens in the editor of the kind it
1655
+ // was saved as. The API refuses a mode sent without an area.
1656
+ mode: session.mode,
1657
+ source: session.source ?? undefined,
1658
+ }
1659
+ : {};
1660
+ const updated = await updateZoneRequest(ctx.api.client, input.zoneId, {
1661
+ ...area,
1662
+ // The single Save persists the metadata the panel edited alongside the reshaped
1663
+ // geometry: the name, the description and the time window ride here (the level
1664
+ // rides the session below), so one commit reconciles every field the edit surface
1665
+ // changed. An omitted name keeps the saved one; a null description clears it.
1666
+ description: input.description,
1667
+ // The window bounds pass through preserving the null-vs-undefined distinction:
1668
+ // a present null CLEARS the bound (JSON.stringify serializes it as `null`), an
1669
+ // absent field is omitted (carried forward). A `?? undefined` here would collapse
1670
+ // a user's clear into an omission, so the server would keep the old value.
1671
+ end_at: input.endAt,
1672
+ level: session.level,
1673
+ name: input.name,
1674
+ start_at: input.startAt,
1675
+ });
1676
+ // Decided from the store as it stands now, after the write. The answer is written to the
1677
+ // cache, and to the panel while it still shows this zone, unless a newer write of the zone
1678
+ // answered first: its zone is then the one held, and it stays.
1679
+ const stands = storeWrittenZone(ctx, ctx.api.cache, updated);
1680
+
1681
+ if (stands !== null && ctx.ui.getState().zoneEditSession?.zoneId === input.zoneId) {
1682
+ // The session stays armed: the engine is untouched and the tile copy stays hidden, so
1683
+ // the zone stays editable on the map with no teardown and no tile refetch. The baseline
1684
+ // is the shape this commit stored, or the one the zone holds where a newer write
1685
+ // answered first and carried its own.
1686
+ settleZoneCommit(
1687
+ ctx,
1688
+ input.zoneId,
1689
+ sentDraft,
1690
+ stands === updated ? drawn : (polygonOf(stands) ?? drawn),
1691
+ );
1692
+ } else {
1693
+ // The session ended while the write was out, and its teardown asked for the tiles
1694
+ // before the write landed. Asked again, they hold the shape that was saved, on the map
1695
+ // mounted now, if any.
1696
+ ctx.map?.refreshZoneTiles();
1697
+ }
1698
+
1699
+ return { ok: true, summary: `Saved zone ${input.zoneId}.` };
1700
+ },
1701
+ };
1702
+
1703
+ /**
1704
+ * DRAWN_PRECISION_DEGREES is how far a position the map answers may stand from the one it was
1705
+ * handed: an editor draws a zone's positions at nine decimals of a degree.
1706
+ */
1707
+ const DRAWN_PRECISION_DEGREES = 1e-9;
1708
+
1709
+ /**
1710
+ * drawnAsSaved reports whether the shape the map holds is the one the zone was last saved with,
1711
+ * as the map draws it: the same rings of the same positions, each longitude and latitude within
1712
+ * the precision the map draws at, and any ordinate past them aside.
1713
+ *
1714
+ * The map is what the person sees and what a save stores, so it is what says whether there is a
1715
+ * shape to store. The store's draft can stand apart from it: a reshape made while the co-pilot
1716
+ * drives is drawn and never recorded. A zone saved at more decimals, or with altitudes, is drawn
1717
+ * rounded and flat, and is still the shape it was saved with. An edit with no saved shape has
1718
+ * one to store.
1719
+ */
1720
+ const drawnAsSaved = (drawn: Polygon, saved: Polygon | null): boolean =>
1721
+ saved !== null &&
1722
+ drawn.coordinates.length === saved.coordinates.length &&
1723
+ drawn.coordinates.every((ring, index) => {
1724
+ const savedRing = saved.coordinates[index] ?? [];
1725
+
1726
+ return (
1727
+ ring.length === savedRing.length &&
1728
+ ring.every((position, at) => {
1729
+ const [lng = Number.NaN, lat = Number.NaN] = position;
1730
+ const [savedLng = Number.NaN, savedLat = Number.NaN] = savedRing[at] ?? [];
1731
+
1732
+ return (
1733
+ Math.abs(lng - savedLng) <= DRAWN_PRECISION_DEGREES &&
1734
+ Math.abs(lat - savedLat) <= DRAWN_PRECISION_DEGREES
1735
+ );
1736
+ })
1737
+ );
1738
+ });
1739
+
1740
+ /**
1741
+ * settleZoneCommit reconciles the session armed on `zoneId` with a write that just landed:
1742
+ * `persisted` is the shape the write stored and `sent` the store's draft as the write left.
1743
+ *
1744
+ * The baseline advances to the persisted shape. The draft follows it only when nothing was
1745
+ * recorded while the write was out, which writes the map's own reading of the shape into the
1746
+ * store so the two compare equal and Save is withdrawn until the next reshape. A draft recorded
1747
+ * meanwhile is what the reader drew since: it stays, the session reads unsaved against the new
1748
+ * baseline, and Save is offered again.
1749
+ */
1750
+ const settleZoneCommit = (
1751
+ ctx: StudioToolContext,
1752
+ zoneId: string,
1753
+ sent: Polygon | null,
1754
+ persisted: Polygon,
1755
+ ): void => {
1756
+ const session = ctx.ui.getState().zoneEditSession;
1757
+ if (session?.zoneId !== zoneId) {
1758
+ return;
1759
+ }
1760
+
1761
+ if (session.draft === sent) {
1762
+ ctx.ui.getState().setZoneEditDraft(persisted);
1763
+ }
1764
+
1765
+ ctx.ui.getState().setZoneSavedGeometry(persisted);
1766
+ };
1767
+
1768
+ /**
1769
+ * zoneEditCancel discards the active zone edit without persisting: it ends the
1770
+ * map edit (restoring the zone's tile copy), closes the store session, and
1771
+ * unlocks the base map. It is the Esc path. A no-op against a null map (the store
1772
+ * session still closes so the UI reflects it).
1773
+ */
1774
+ export const zoneEditCancel: StudioToolDefinition<"studio.zone.editCancel"> = {
1775
+ // Hidden from the model's manifest: the agent never cancels an open zone session.
1776
+ // It hands the live draft to the user, who saves or discards it.
1777
+ agentHidden: true,
1778
+ handler: (ctx) => {
1779
+ // Capture the locked zone id before cancelZoneEdit clears the session.
1780
+ const lockedZoneId = ctx.ui.getState().zoneEditSession?.zoneId ?? null;
1781
+
1782
+ // endZoneEdit disposes the engine, restores the zone's hidden tile copy (drops
1783
+ // the exclusion filter), and lowers the terrain block. Then refresh the zone
1784
+ // tiles so a zone whose geometry was saved during this still-armed edit (a
1785
+ // reshape commit keeps the session armed and refetches nothing) repaints its
1786
+ // CURRENT geometry rather than the stale tile the cache still holds. The bust
1787
+ // runs AFTER endZoneEdit on purpose: the engine is disposed and the map idle,
1788
+ // so setTiles reliably refetches the current-viewport tile (the same
1789
+ // setTiles-mid-edit constraint the itinerary commit path observes). A cancel
1790
+ // without a prior save is a harmless no-op refetch. The teardown, not
1791
+ // editCommit, owns this refresh (editCommit stays armed; the live draft
1792
+ // covers the in-edit view).
1793
+ ctx.map?.endZoneEdit();
1794
+ ctx.map?.refreshZoneTiles();
1795
+ ctx.ui.getState().cancelZoneEdit();
1796
+
1797
+ // Release the collaboration hold the armed session held (a zone lock spans the
1798
+ // whole session, never released on commit): clear the draft ghost and release
1799
+ // the soft-lock. Best-effort; inert on a personal zone.
1800
+ if (lockedZoneId) {
1801
+ releaseCollabEntity(ctx, "zone", lockedZoneId);
1802
+ }
1803
+
1804
+ return { ok: true, summary: "Cancelled the zone edit." };
1805
+ },
1806
+ };
1807
+
1808
+ /**
1809
+ * zoneEditUndo steps the active edit's draft history back one entry and replays the restored
1810
+ * draft on the map.
1811
+ *
1812
+ * The store is the source of truth: it moves the current draft onto the redo stack and restores
1813
+ * the previous one, and `applyZoneDraft` then writes that shape onto the map's editing feature,
1814
+ * a programmatic write the draft seam flags so it records no history. With nothing behind, the
1815
+ * store does not move and the map is told nothing. That includes a create with one shape drawn:
1816
+ * its empty start is no step, so an undo never leaves a shape on the map that the store has
1817
+ * dropped.
1818
+ */
1819
+ export const zoneEditUndo: StudioToolDefinition<"studio.zone.editUndo"> = {
1820
+ handler: (ctx) => {
1821
+ const stepped = stepZoneDraft(ctx, () => ctx.ui.getState().undoZoneDraft());
1822
+
1823
+ return {
1824
+ ok: true,
1825
+ summary: stepped ? "Undid the last zone edit change." : "Nothing to undo in the zone edit.",
1826
+ };
1827
+ },
1828
+ };
1829
+
1830
+ /**
1831
+ * zoneEditRedo steps the active edit's draft history forward one entry and replays the restored
1832
+ * draft on the map, as {@link zoneEditUndo} does backward. With nothing ahead, the store does
1833
+ * not move and the map is told nothing.
1834
+ */
1835
+ export const zoneEditRedo: StudioToolDefinition<"studio.zone.editRedo"> = {
1836
+ handler: (ctx) => {
1837
+ const stepped = stepZoneDraft(ctx, () => ctx.ui.getState().redoZoneDraft());
1838
+
1839
+ return {
1840
+ ok: true,
1841
+ summary: stepped ? "Redid the last zone edit change." : "Nothing to redo in the zone edit.",
1842
+ };
1843
+ },
1844
+ };
1845
+
1846
+ /**
1847
+ * stepZoneDraft runs one step of the store's draft history and, when the session moved, replays
1848
+ * its draft on the map. It answers whether the session moved.
1849
+ *
1850
+ * A step that finds nothing replaces no session, which is how a no-op is told from a step. The
1851
+ * draft a step restores always holds a shape, since no history entry is empty. A context with no
1852
+ * map still steps the store.
1853
+ */
1854
+ const stepZoneDraft = (ctx: StudioToolContext, step: () => void): boolean => {
1855
+ const before = ctx.ui.getState().zoneEditSession;
1856
+ step();
1857
+ const session = ctx.ui.getState().zoneEditSession;
1858
+
1859
+ if (session === before || session === null) {
1860
+ return false;
1861
+ }
1862
+
1863
+ if (session.draft !== null) {
1864
+ ctx.map?.applyZoneDraft(session.draft);
1865
+ }
1866
+
1867
+ return true;
1868
+ };
1869
+
1870
+ /**
1871
+ * reseedArmedZoneAfterPersist re-seeds the armed zone edit engine after a persist changed the
1872
+ * zone's geometry (a recompute, or a source/geojson update), so the live TerraDraw draft
1873
+ * shows the new shape immediately instead of the geometry the session was armed with: the zone
1874
+ * twin of a directions segment reshaping live on the map. A zone opens straight into edit mode,
1875
+ * so without this the busted tile stays hidden behind the edit exclusion and the user sees the
1876
+ * change only after a close and reopen. It no-ops unless a session is armed on THIS zone (a
1877
+ * persist of a zone that is not the open one has no stale draft) and unless the persisted
1878
+ * geometry is an editable Polygon (a Point zone has no draw shape).
1879
+ *
1880
+ * It drives the SOURCE-PRESERVING seams: applyZoneDraft pushes the shape onto the engine (the
1881
+ * programmatic replace undo/redo also drives), setZoneEditDraft advances the store draft
1882
+ * without clearing source or looping history, and setZoneSavedGeometry marks it saved so the
1883
+ * Save button stays disabled, since the geometry is already persisted. A render-free context
1884
+ * (no map) still advances the store. ctx is first.
1885
+ *
1886
+ * `sent` is the armed draft as the write left ({@link armedDraftOf}). A draft that is another one
1887
+ * now is what the reader drew while the write was out: it stays on the map and in the session,
1888
+ * and reads unsaved against the persisted shape, which becomes the baseline alone. A session
1889
+ * armed since the write left is reseeded only while nothing was drawn in it.
1890
+ */
1891
+ const reseedArmedZoneAfterPersist = (
1892
+ ctx: StudioToolContext,
1893
+ zone: Zone,
1894
+ sent: Polygon | null | undefined,
1895
+ ): void => {
1896
+ const session = ctx.ui.getState().zoneEditSession;
1897
+ if (session?.zoneId !== zone.id) {
1898
+ return;
1899
+ }
1900
+
1901
+ const geometry = zone.geojson.geometry;
1902
+ if (geometry.type !== "Polygon") {
1903
+ return;
1904
+ }
1905
+
1906
+ const drawnSince =
1907
+ sent === undefined
1908
+ ? session.past.length > 0 || session.gestureStart !== null
1909
+ : session.draft !== sent;
1910
+ if (drawnSince) {
1911
+ ctx.ui.getState().setZoneSavedGeometry(geometry);
1912
+
1913
+ return;
1914
+ }
1915
+
1916
+ ctx.map?.applyZoneDraft(geometry);
1917
+ ctx.ui.getState().setZoneEditDraft(geometry);
1918
+ ctx.ui.getState().setZoneSavedGeometry(geometry);
1919
+ };
1920
+
1921
+ /**
1922
+ * latestZoneOpens names, per UI store, the open of a saved zone asked last: a
1923
+ * `studio.zone.openForEdit` or a `studio.zone.openForView`.
1924
+ *
1925
+ * An open is a read, and two can be out at once. The mark is what lets the one that answers
1926
+ * late see that another was asked after it. Keyed weakly by the store, so a studio that is gone
1927
+ * keeps nothing alive.
1928
+ */
1929
+ const latestZoneOpens = new WeakMap<object, symbol>();
1930
+
1931
+ /**
1932
+ * overtakenZoneOpen is what an open of a saved zone answers when another was asked after it:
1933
+ * `ok`, since nothing failed, with `data.opened` false, since it bound, framed and armed nothing.
1934
+ */
1935
+ const overtakenZoneOpen = (zoneId: string): ToolResult<z.infer<typeof openedOutputSchema>> => ({
1936
+ data: { opened: false },
1937
+ ok: true,
1938
+ summary: `Left the zone surface to a newer open: zone ${zoneId} was not opened.`,
1939
+ });
1940
+
1941
+ /**
1942
+ * openForEdit loads a saved zone into the editor: it fetches the CANONICAL zone
1943
+ * (GET /v1/zones/{id}: the full, unclipped geometry, NOT the simplified tile feature) so the
1944
+ * engine seeds from the authoritative shape, opens the zone panel bound to it, frames its
1945
+ * bounds, and, for a HAND-DRAWN zone, opens the edit session in the zone's own mode and level.
1946
+ * A COMPUTED zone binds without arming: its geometry follows a stored query, so the panel edits
1947
+ * that query and an explicit action arms the draw engine. It is the activation chain a
1948
+ * search-result zone row or an agent "edit this zone" dispatch drives. It enforces mutual
1949
+ * exclusion through guardEditBegin (a second session while another engine is armed is
1950
+ * refused), and refuses a zone whose canonical geometry is not a Polygon (a bare Point zone is
1951
+ * not editable by the draw engine). ctx is the first positional parameter.
1952
+ *
1953
+ * A hand-drawn zone is armed, so its collaboration lock is taken first, as
1954
+ * `studio.zone.editBegin` takes it: a zone a peer holds answers `collab-locked` and nothing is
1955
+ * bound, and the lock is held for the session's life. A computed zone arms nothing and takes no
1956
+ * lock. The gate is asked again once the read and the lock have answered, since an edit may
1957
+ * have begun meanwhile: it is then refused here, and the lock is given back.
1958
+ *
1959
+ * Only the open asked last lands, whichever read answers first, and `studio.zone.openForView`
1960
+ * counts as an open here. One that another was asked after binds nothing, frames nothing, takes
1961
+ * no lock and arms nothing, and says so: it answers `ok` with `data.opened` false, where an open
1962
+ * that landed answers `data.opened` true.
1963
+ *
1964
+ * Over a staged import or suggestion it leaves that surface before anything else, as
1965
+ * {@link open} does: ending the session ends an edit armed on its draft, which the gate would
1966
+ * otherwise refuse the open for.
1967
+ */
1968
+ export const openForEdit: StudioToolDefinition<"studio.zone.openForEdit"> = {
1969
+ handler: async (ctx, input) => {
1970
+ // A zone whose scope the session already knows takes no edit is refused before anything is
1971
+ // left, bound or armed, and once its record is read below, for one it did not know.
1972
+ const known = refuseZoneScope(ctx, savedZoneOrganization(ctx, input.zoneId));
1973
+ if (known) {
1974
+ return known;
1975
+ }
1976
+
1977
+ const left = await leaveStagedSurface(ctx, "studio.zone.openForEdit", input, "zone");
1978
+ if (left) {
1979
+ return left;
1980
+ }
1981
+
1982
+ // The one-edit-at-a-time check is a pure state read, so it runs before the
1983
+ // persistence seam check: a blocked open must report `edit-in-progress`
1984
+ // (which routes the human click through the switch modal) regardless of
1985
+ // whether the api seam is present.
1986
+ const blocked = guardEditBegin(ctx.ui.getState(), { kind: "zone", zoneId: input.zoneId });
1987
+ if (blocked) {
1988
+ return blocked;
1989
+ }
1990
+
1991
+ if (!ctx.api) {
1992
+ return { code: "no-api", error: "open zone for edit: no persistence seam", ok: false };
1993
+ }
1994
+
1995
+ const open = Symbol("open");
1996
+ latestZoneOpens.set(ctx.ui, open);
1997
+
1998
+ const zone = await fetchZone(ctx.api.client, input.zoneId);
1999
+
2000
+ // Another open was asked while this one loaded. The reader is on their way to that zone, so
2001
+ // this one writes nothing: not the slot, not the camera, not a session.
2002
+ if (latestZoneOpens.get(ctx.ui) !== open) {
2003
+ return overtakenZoneOpen(input.zoneId);
2004
+ }
2005
+
2006
+ const scoped = refuseZoneScope(ctx, zone.organization_id);
2007
+ if (scoped) {
2008
+ return scoped;
2009
+ }
2010
+
2011
+ // The canonical geometry seeds the engine. A zone draw engine edits the Polygon
2012
+ // every zone mode draws; a bare Point zone has no editable draw shape, so it is
2013
+ // refused rather than opening a session the engine cannot arm.
2014
+ const geometry = zone.geojson.geometry;
2015
+ if (geometry.type !== "Polygon") {
2016
+ return {
2017
+ code: "invalid-input",
2018
+ error: `open zone for edit: zone ${input.zoneId} is saved as a point, which no draw can reshape`,
2019
+ ok: false,
2020
+ };
2021
+ }
2022
+
2023
+ const seedGeometry: Polygon = geometry;
2024
+
2025
+ // A hand-drawn zone opens armed, so it is locked as every armed zone is. The read above was
2026
+ // awaited, and the lock is too, so the gate is asked again before anything is written.
2027
+ const refused = zone.source
2028
+ ? guardEditBegin(ctx.ui.getState(), { kind: "zone", zoneId: zone.id })
2029
+ : await lockZoneForEdit(ctx, zone.id);
2030
+ if (refused) {
2031
+ return refused;
2032
+ }
2033
+
2034
+ // Bind the panel to the saved zone and open the zone surface. Capture the prior active
2035
+ // zone first so the co-pilot resets when this opens a DIFFERENT zone and its
2036
+ // conversation cannot leak in (see maybeResetCopilotOnSwitch).
2037
+ const previousZoneId = ctx.ui.getState().activeZone?.id ?? null;
2038
+ ctx.ui.getState().setActiveZone(zone);
2039
+ maybeResetCopilotOnSwitch(ctx, previousZoneId, zone.id);
2040
+ ctx.ui.getState().setOpenContent("zone");
2041
+ // Deliberately no navigate. The sidenav cascade resolves the open content slot
2042
+ // BEFORE the url's itinerary detail, so the zone panel already renders over an
2043
+ // open itinerary, and keeping the detail keys is what lets closing the zone
2044
+ // panel fall back to the itinerary the user was editing rather than dropping
2045
+ // them on the collections list.
2046
+
2047
+ // Frame the zone: prefer the canonical geometry's own bounds; fall back to a
2048
+ // caller-supplied anchor (a search row knows where to look pre-fetch).
2049
+ const bounds = boundsOf([seedGeometry]) ?? input.bounds ?? null;
2050
+ if (bounds) {
2051
+ ctx.map?.fitBounds(bounds);
2052
+ } else if (input.point) {
2053
+ ctx.map?.setViewport({ center: input.point, zoom: POINT_ZOOM });
2054
+ }
2055
+
2056
+ // A COMPUTED zone opens unarmed. Its shape is derived from a stored query, and
2057
+ // any hand reshape detaches that query one-way, so arming a draw engine on
2058
+ // open makes a stray drag enough to silently destroy the provenance the zone
2059
+ // exists for. The panel offers its reachability parameters instead, and an
2060
+ // explicit "reshape by hand" action arms the engine behind a warning. A
2061
+ // hand-drawn zone has nothing to lose and keeps opening ready to reshape.
2062
+ if (zone.source) {
2063
+ // Seed the authoring origin from the stored query so the panel opens showing
2064
+ // the point the zone is actually measured from, and so moving it is an edit
2065
+ // of this zone rather than of an unrelated leftover from a previous create.
2066
+ ctx.ui.getState().resetZoneCreate({
2067
+ // Opening a SAVED zone inherits nothing: its organization, collections and
2068
+ // activity are on the record.
2069
+ inheritItinerary: false,
2070
+ method: "reachability",
2071
+ origin: [zone.source.location[0] ?? 0, zone.source.location[1] ?? 0],
2072
+ });
2073
+
2074
+ return {
2075
+ data: { opened: true },
2076
+ ok: true,
2077
+ summary: `Opened computed zone ${input.zoneId}. Its shape follows its reachability query: reshaping by hand replaces it.`,
2078
+ };
2079
+ }
2080
+
2081
+ // Arm the edit session in the zone's own mode + level, seeded with the
2082
+ // canonical shape. The zone editing hook drives beginZoneEdit on the map.
2083
+ ctx.ui.getState().beginZoneEdit({
2084
+ intent: "edit",
2085
+ level: zone.level,
2086
+ mode: zone.mode,
2087
+ seedGeometry,
2088
+ zoneId: zone.id,
2089
+ });
2090
+
2091
+ return {
2092
+ data: { opened: true },
2093
+ ok: true,
2094
+ summary: `Opened zone ${input.zoneId} for editing.`,
2095
+ };
2096
+ },
2097
+ };
2098
+
2099
+ /**
2100
+ * openForView opens a saved zone in READ-ONLY view: the read-only counterpart of openForEdit
2101
+ * for a viewer who may see a zone but not edit it. It fetches the CANONICAL zone
2102
+ * (GET /v1/zones/{id}), binds the panel to it, and frames its bounds, but deliberately does
2103
+ * NOT open an edit session: no engine is armed, no draw cursor is locked, and the panel's
2104
+ * permission gate renders the details disabled. The editable-vs-view decision is made by the
2105
+ * caller (the zone selection hook reads the tile feature's creator/org against the
2106
+ * user's writable organizations); this is the branch it dispatches when the zone is not
2107
+ * editable.
2108
+ *
2109
+ * It still honors the one-edit-at-a-time invariant: opening a read-only view while another
2110
+ * authoring engine (a segment, waypoint, OR zone edit) is armed would silently abandon that
2111
+ * edit, so it returns the structured `edit-in-progress` failure instead. That routes the human
2112
+ * selection hook's click through the cross-entity switch modal: discard the current edit, then
2113
+ * the modal replays this open, which then proceeds with nothing armed. It does NOT pass through
2114
+ * guardEditBegin (that gate has an idempotent "same target" branch for re-arming an edit; a
2115
+ * view never arms, so any armed engine blocks): it reads selectActiveEditEngine directly and
2116
+ * blocks on any non-null engine. It reads it twice, before its read of the zone and once that
2117
+ * read has answered, since an edit may have begun meanwhile. ctx is the first positional
2118
+ * parameter.
2119
+ *
2120
+ * Only the open asked last lands, as {@link openForEdit} sets out: an open for view that
2121
+ * another open was asked after binds nothing, frames nothing and answers `ok` with
2122
+ * `data.opened` false.
2123
+ *
2124
+ * Over a staged import or suggestion it leaves that surface before anything else, as
2125
+ * {@link open} does.
2126
+ */
2127
+ export const openForView: StudioToolDefinition<"studio.zone.openForView"> = {
2128
+ handler: async (ctx, input) => {
2129
+ const left = await leaveStagedSurface(ctx, "studio.zone.openForView", input, "zone");
2130
+ if (left) {
2131
+ return left;
2132
+ }
2133
+
2134
+ // Binding the panel to a different zone while an edit is armed would abandon
2135
+ // that edit silently; block on any armed engine so a human click routes
2136
+ // through the switch modal instead. (A view never arms an engine, so there
2137
+ // is no idempotent same-target case to allow: any non-null engine blocks.)
2138
+ // This pure state check runs before the persistence seam check so the block
2139
+ // is reported regardless of whether the api seam is present.
2140
+ const active = selectActiveEditEngine(ctx.ui.getState());
2141
+ if (active !== null) {
2142
+ return editInProgressError(active.kind);
2143
+ }
2144
+
2145
+ if (!ctx.api) {
2146
+ return { code: "no-api", error: "open zone for view: no persistence seam", ok: false };
2147
+ }
2148
+
2149
+ const open = Symbol("open");
2150
+ latestZoneOpens.set(ctx.ui, open);
2151
+
2152
+ const zone = await fetchZone(ctx.api.client, input.zoneId);
2153
+
2154
+ if (latestZoneOpens.get(ctx.ui) !== open) {
2155
+ return overtakenZoneOpen(input.zoneId);
2156
+ }
2157
+
2158
+ // Asked again, now that the read is done: an edit armed while the zone loaded would be
2159
+ // abandoned by the bind below.
2160
+ const activeSince = selectActiveEditEngine(ctx.ui.getState());
2161
+ if (activeSince !== null) {
2162
+ return editInProgressError(activeSince.kind);
2163
+ }
2164
+
2165
+ // Bind the panel to the saved zone and open the zone surface. No edit session
2166
+ // opens, so the panel shows the bound zone's details under its read-only gate. Reset
2167
+ // the co-pilot when this opens a DIFFERENT zone (see maybeResetCopilotOnSwitch).
2168
+ const previousZoneId = ctx.ui.getState().activeZone?.id ?? null;
2169
+ ctx.ui.getState().setActiveZone(zone);
2170
+ maybeResetCopilotOnSwitch(ctx, previousZoneId, zone.id);
2171
+ ctx.ui.getState().setOpenContent("zone");
2172
+ // Deliberately no navigate. The sidenav cascade resolves the open content slot
2173
+ // BEFORE the url's itinerary detail, so the zone panel already renders over an
2174
+ // open itinerary, and keeping the detail keys is what lets closing the zone
2175
+ // panel fall back to the itinerary the user was editing rather than dropping
2176
+ // them on the collections list.
2177
+
2178
+ // Frame the zone: prefer the canonical geometry's own bounds; fall back to a
2179
+ // caller-supplied anchor (a row knows where to look pre-fetch).
2180
+ const bounds = boundsOf([zone.geojson.geometry]) ?? input.bounds ?? null;
2181
+ if (bounds) {
2182
+ ctx.map?.fitBounds(bounds);
2183
+ } else if (input.point) {
2184
+ ctx.map?.setViewport({ center: input.point, zoom: POINT_ZOOM });
2185
+ }
2186
+
2187
+ // Seed the authoring origin from a computed zone's stored query, so its
2188
+ // parameters read back the point it is measured from: the same seeding the
2189
+ // editable open does, since a viewer sees the same fields, disabled.
2190
+ if (zone.source) {
2191
+ ctx.ui.getState().resetZoneCreate({
2192
+ // Opening a SAVED zone inherits nothing: its organization, collections and
2193
+ // activity are on the record.
2194
+ inheritItinerary: false,
2195
+ method: "reachability",
2196
+ origin: [zone.source.location[0] ?? 0, zone.source.location[1] ?? 0],
2197
+ });
2198
+ }
2199
+
2200
+ return {
2201
+ data: { opened: true },
2202
+ ok: true,
2203
+ summary: `Opened zone ${input.zoneId} for viewing.`,
2204
+ };
2205
+ },
2206
+ };
2207
+
2208
+ /**
2209
+ * addZone adds one zone to a collection, then invalidates the zone's membership picker and the
2210
+ * collection's tile specification so both the checkbox and the maps rendered from that
2211
+ * collection reflect the new membership. Persisting, so it needs the api seam: absent, it
2212
+ * returns a failure. Mirrors the itinerary collection-add tool.
2213
+ */
2214
+ export const addZone: StudioToolDefinition<"studio.collection.addZone"> = {
2215
+ handler: async (ctx, input) => {
2216
+ if (!ctx.api) {
2217
+ return { code: "no-api", error: "add zone to collection: no persistence seam", ok: false };
2218
+ }
2219
+
2220
+ await addZoneToCollection(ctx.api.client, input.collectionId, [input.zoneId]);
2221
+ await invalidateZoneMembership(ctx, input.collectionId);
2222
+
2223
+ return {
2224
+ ok: true,
2225
+ summary: `Added zone ${input.zoneId} to collection ${input.collectionId}.`,
2226
+ };
2227
+ },
2228
+ };
2229
+
2230
+ /**
2231
+ * removeZone removes one zone from a collection, then invalidates the same two caches as the
2232
+ * add so the membership picker and the collection's rendered layers both update. Persisting, so
2233
+ * it needs the api seam: absent, it returns a failure. Mirrors the itinerary collection-remove
2234
+ * tool.
2235
+ */
2236
+ export const removeZone: StudioToolDefinition<"studio.collection.removeZone"> = {
2237
+ handler: async (ctx, input) => {
2238
+ if (!ctx.api) {
2239
+ return {
2240
+ code: "no-api",
2241
+ error: "remove zone from collection: no persistence seam",
2242
+ ok: false,
2243
+ };
2244
+ }
2245
+
2246
+ await removeZoneFromCollection(ctx.api.client, input.collectionId, input.zoneId);
2247
+ await invalidateZoneMembership(ctx, input.collectionId);
2248
+
2249
+ return {
2250
+ ok: true,
2251
+ summary: `Removed zone ${input.zoneId} from collection ${input.collectionId}.`,
2252
+ };
2253
+ },
2254
+ };