@mountaya/studio 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (521) hide show
  1. package/CHANGELOG.md +69 -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 +2600 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1237 -0
  8. package/dist/agent/index.d.ts +1237 -0
  9. package/dist/agent/index.js +2581 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/chunk-3Oi_Zrtm.js +9 -0
  12. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  13. package/dist/chunk-B18OPIu_.js +6 -0
  14. package/dist/chunk-B18OPIu_.js.map +1 -0
  15. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  16. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  17. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  18. package/dist/chunk-BIEc_SkR.cjs +29 -0
  19. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  20. package/dist/chunk-BKMFOe-N.js +171 -0
  21. package/dist/chunk-BKMFOe-N.js.map +1 -0
  22. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  23. package/dist/chunk-BSHTsFiB.js +1403 -0
  24. package/dist/chunk-BSHTsFiB.js.map +1 -0
  25. package/dist/chunk-BTUUABGI.js +17 -0
  26. package/dist/chunk-BTUUABGI.js.map +1 -0
  27. package/dist/chunk-BaPiaz5X.cjs +115 -0
  28. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  29. package/dist/chunk-BeCVpkYr.cjs +542 -0
  30. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  31. package/dist/chunk-BgngsvK8.cjs +6202 -0
  32. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  33. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  34. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  35. package/dist/chunk-By9ZnkVI.js +60 -0
  36. package/dist/chunk-By9ZnkVI.js.map +1 -0
  37. package/dist/chunk-BzqPhxsz.cjs +367 -0
  38. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  39. package/dist/chunk-C2mMX81q.d.ts +443 -0
  40. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  41. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  42. package/dist/chunk-CDJCbwIQ.d.cts +78 -0
  43. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  44. package/dist/chunk-COdw1dc6.d.ts +525 -0
  45. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  46. package/dist/chunk-CSyHY67q.cjs +353 -0
  47. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  48. package/dist/chunk-CiK1Iqrv.js +950 -0
  49. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  50. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  51. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  52. package/dist/chunk-CnrsRK2u.cjs +83 -0
  53. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  54. package/dist/chunk-Co782_9r.js +326 -0
  55. package/dist/chunk-Co782_9r.js.map +1 -0
  56. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  57. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  58. package/dist/chunk-CwkmccXv.js +89 -0
  59. package/dist/chunk-CwkmccXv.js.map +1 -0
  60. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  61. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  62. package/dist/chunk-DFwiSzUS.cjs +72 -0
  63. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  64. package/dist/chunk-DIFayl2P.d.cts +443 -0
  65. package/dist/chunk-DIGF58ux.d.cts +525 -0
  66. package/dist/chunk-DKuuuld5.js +101 -0
  67. package/dist/chunk-DKuuuld5.js.map +1 -0
  68. package/dist/chunk-DMePkFEo.js +5054 -0
  69. package/dist/chunk-DMePkFEo.js.map +1 -0
  70. package/dist/chunk-DO5SIBgu.js +305 -0
  71. package/dist/chunk-DO5SIBgu.js.map +1 -0
  72. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  73. package/dist/chunk-DThaaNeb.d.cts +15 -0
  74. package/dist/chunk-DThaaNeb.d.ts +15 -0
  75. package/dist/chunk-DUQzjUJy.d.ts +78 -0
  76. package/dist/chunk-DX37IPhV.cjs +1903 -0
  77. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  78. package/dist/chunk-Damps5Tk.cjs +155 -0
  79. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  80. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  81. package/dist/chunk-De0vAASv.d.ts +253 -0
  82. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  83. package/dist/chunk-DjEvqvPA.cjs +43 -0
  84. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  85. package/dist/chunk-DkwDzwvu.d.cts +121 -0
  86. package/dist/chunk-DkwDzwvu.d.ts +121 -0
  87. package/dist/chunk-Dmszv9If.js +71 -0
  88. package/dist/chunk-Dmszv9If.js.map +1 -0
  89. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  90. package/dist/chunk-DsHQySz0.js +31 -0
  91. package/dist/chunk-DsHQySz0.js.map +1 -0
  92. package/dist/chunk-DwoUyHHh.js +281 -0
  93. package/dist/chunk-DwoUyHHh.js.map +1 -0
  94. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  95. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  96. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  97. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  98. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  99. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  100. package/dist/chunk-o9jaxhCO.js +8852 -0
  101. package/dist/chunk-o9jaxhCO.js.map +1 -0
  102. package/dist/chunk-p-Tt_Lwz.js +14 -0
  103. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  104. package/dist/engines/index.cjs +2091 -0
  105. package/dist/engines/index.cjs.map +1 -0
  106. package/dist/engines/index.d.cts +2176 -0
  107. package/dist/engines/index.d.ts +2176 -0
  108. package/dist/engines/index.js +2075 -0
  109. package/dist/engines/index.js.map +1 -0
  110. package/dist/handlers/index.cjs +53 -0
  111. package/dist/handlers/index.cjs.map +1 -0
  112. package/dist/handlers/index.d.cts +403 -0
  113. package/dist/handlers/index.d.ts +403 -0
  114. package/dist/handlers/index.js +33 -0
  115. package/dist/handlers/index.js.map +1 -0
  116. package/dist/index.cjs +3511 -0
  117. package/dist/index.cjs.map +1 -0
  118. package/dist/index.d.cts +8 -0
  119. package/dist/index.d.ts +8 -0
  120. package/dist/index.js +3033 -0
  121. package/dist/index.js.map +1 -0
  122. package/dist/plugins/index.cjs +510 -0
  123. package/dist/plugins/index.cjs.map +1 -0
  124. package/dist/plugins/index.d.cts +296 -0
  125. package/dist/plugins/index.d.ts +296 -0
  126. package/dist/plugins/index.js +489 -0
  127. package/dist/plugins/index.js.map +1 -0
  128. package/dist/seams/index.cjs +89 -0
  129. package/dist/seams/index.cjs.map +1 -0
  130. package/dist/seams/index.d.cts +452 -0
  131. package/dist/seams/index.d.ts +452 -0
  132. package/dist/seams/index.js +49 -0
  133. package/dist/seams/index.js.map +1 -0
  134. package/dist/strings/fr/index.cjs +2135 -0
  135. package/dist/strings/fr/index.cjs.map +1 -0
  136. package/dist/strings/fr/index.d.cts +17 -0
  137. package/dist/strings/fr/index.d.ts +17 -0
  138. package/dist/strings/fr/index.js +2130 -0
  139. package/dist/strings/fr/index.js.map +1 -0
  140. package/dist/strings/index.cjs +2384 -0
  141. package/dist/strings/index.cjs.map +1 -0
  142. package/dist/strings/index.d.cts +3 -0
  143. package/dist/strings/index.d.ts +3 -0
  144. package/dist/strings/index.js +2353 -0
  145. package/dist/strings/index.js.map +1 -0
  146. package/dist/testing/index.cjs +230 -0
  147. package/dist/testing/index.cjs.map +1 -0
  148. package/dist/testing/index.d.cts +246 -0
  149. package/dist/testing/index.d.ts +246 -0
  150. package/dist/testing/index.js +219 -0
  151. package/dist/testing/index.js.map +1 -0
  152. package/dist/time/index.cjs +28 -0
  153. package/dist/time/index.cjs.map +1 -0
  154. package/dist/time/index.d.cts +41 -0
  155. package/dist/time/index.d.ts +41 -0
  156. package/dist/time/index.js +23 -0
  157. package/dist/time/index.js.map +1 -0
  158. package/package.json +224 -4
  159. package/src/agent/engines/agentThreads.ts +1601 -0
  160. package/src/agent/engines/directorChat.ts +500 -0
  161. package/src/agent/index.ts +67 -0
  162. package/src/agent/rules/agentEditLock.ts +115 -0
  163. package/src/agent/rules/agentErrorCopy.ts +44 -0
  164. package/src/agent/rules/copilotOrganization.ts +36 -0
  165. package/src/agent/rules/playbook.gen.ts +444 -0
  166. package/src/agent/rules/router.ts +518 -0
  167. package/src/agent/rules/stateDelta.ts +29 -0
  168. package/src/agent/rules/studioRouter.ts +123 -0
  169. package/src/agent/rules/surfaces.gen.ts +633 -0
  170. package/src/agent/rules/threadsUrl.ts +48 -0
  171. package/src/agent/rules/transcriptObserver.ts +90 -0
  172. package/src/agent/stores/agentThreads.ts +451 -0
  173. package/src/bus/contracts/noData.ts +18 -0
  174. package/src/bus/contracts/shared.ts +172 -0
  175. package/src/bus/contracts/studioTools.ts +224 -0
  176. package/src/bus/rules/bus.ts +857 -0
  177. package/src/bus/rules/confirmation.ts +22 -0
  178. package/src/bus/rules/defineRegistry.ts +24 -0
  179. package/src/bus/rules/errors.ts +401 -0
  180. package/src/bus/rules/handlerErrors.ts +103 -0
  181. package/src/bus/rules/handlerRegistry.ts +627 -0
  182. package/src/bus/rules/inputSchema.ts +232 -0
  183. package/src/bus/rules/invalidInput.ts +441 -0
  184. package/src/bus/rules/lateBoundTools.ts +100 -0
  185. package/src/bus/rules/studioRegistry.ts +324 -0
  186. package/src/bus/rules/studioToolBus.ts +73 -0
  187. package/src/bus/rules/types.ts +804 -0
  188. package/src/chrome/contracts/alert.ts +42 -0
  189. package/src/chrome/contracts/itinerary.ts +26 -0
  190. package/src/chrome/contracts/map.ts +23 -0
  191. package/src/chrome/contracts/overlay.ts +46 -0
  192. package/src/chrome/contracts/panel.ts +29 -0
  193. package/src/chrome/contracts/question.ts +52 -0
  194. package/src/chrome/contracts/selection.ts +26 -0
  195. package/src/chrome/contracts/sidenav.ts +23 -0
  196. package/src/chrome/contracts/snapshot.ts +319 -0
  197. package/src/chrome/contracts/state.ts +22 -0
  198. package/src/chrome/contracts/tabs.ts +56 -0
  199. package/src/chrome/handlers/alert.ts +91 -0
  200. package/src/chrome/handlers/introspection.ts +180 -0
  201. package/src/chrome/handlers/panels.ts +42 -0
  202. package/src/chrome/handlers/question.ts +24 -0
  203. package/src/chrome/handlers/sidenav.ts +116 -0
  204. package/src/chrome/handlers/snapshot.ts +451 -0
  205. package/src/chrome/handlers/stateDelta.ts +125 -0
  206. package/src/chrome/handlers/tabs.ts +143 -0
  207. package/src/chrome/handlers/timestamp.ts +19 -0
  208. package/src/chrome/rules/agentSelectors.ts +210 -0
  209. package/src/chrome/rules/mapAlert.ts +13 -0
  210. package/src/chrome/rules/question.ts +25 -0
  211. package/src/chrome/rules/tabs.ts +13 -0
  212. package/src/chrome/stores/activeDraftSession.ts +134 -0
  213. package/src/chrome/stores/chrome.ts +527 -0
  214. package/src/chrome/stores/uiStore.ts +575 -0
  215. package/src/collab/contracts/collab.ts +261 -0
  216. package/src/collab/handlers/collab.ts +468 -0
  217. package/src/collab/rules/toolNames.ts +33 -0
  218. package/src/collab/stores/collab.ts +899 -0
  219. package/src/collections/contracts/collection.ts +182 -0
  220. package/src/collections/handlers/collectionAttach.ts +141 -0
  221. package/src/collections/handlers/collections.ts +499 -0
  222. package/src/collections/handlers/heldCollection.ts +42 -0
  223. package/src/collections/handlers/restCollections.ts +386 -0
  224. package/src/collections/rules/collections.ts +138 -0
  225. package/src/collections/rules/entityCollections.ts +53 -0
  226. package/src/collections/stores/collections.ts +133 -0
  227. package/src/data/contracts/data.ts +233 -0
  228. package/src/data/contracts/itinerary.ts +71 -0
  229. package/src/data/handlers/activityResolve.ts +76 -0
  230. package/src/data/handlers/data.ts +200 -0
  231. package/src/data/handlers/graphql.ts +26 -0
  232. package/src/data/handlers/mutationSink.ts +1577 -0
  233. package/src/data/handlers/profile.ts +83 -0
  234. package/src/data/handlers/writeThrough.ts +417 -0
  235. package/src/data/rules/cache.ts +181 -0
  236. package/src/data/rules/dataTypes.ts +40 -0
  237. package/src/data/rules/keys.ts +106 -0
  238. package/src/data/rules/persistence.ts +1058 -0
  239. package/src/data/rules/requestBody.ts +43 -0
  240. package/src/data/rules/restErrors.ts +354 -0
  241. package/src/data/rules/sessionSurface.ts +156 -0
  242. package/src/data/rules/toolResultData.ts +73 -0
  243. package/src/data/rules/uuid.ts +24 -0
  244. package/src/edit/contracts/edit.ts +37 -0
  245. package/src/edit/contracts/itinerary.ts +57 -0
  246. package/src/edit/handlers/draftCommit.ts +257 -0
  247. package/src/edit/handlers/editDiscard.ts +34 -0
  248. package/src/edit/handlers/editLock.ts +949 -0
  249. package/src/edit/handlers/editor.ts +203 -0
  250. package/src/edit/handlers/formUnsaved.ts +24 -0
  251. package/src/edit/rules/draftMetadata.ts +117 -0
  252. package/src/edit/rules/editKeyboard.ts +222 -0
  253. package/src/edit/rules/editShortcuts.ts +102 -0
  254. package/src/edit/rules/editTooltip.ts +174 -0
  255. package/src/edit/rules/editorTaken.ts +49 -0
  256. package/src/edit/rules/history.ts +26 -0
  257. package/src/edit/rules/unsavedWork.ts +60 -0
  258. package/src/edit/stores/editorReservation.ts +70 -0
  259. package/src/edit/stores/formsUnsaved.ts +54 -0
  260. package/src/embed/contracts/embed.ts +48 -0
  261. package/src/embed/engines/embedFraming.ts +1329 -0
  262. package/src/embed/engines/embedReady.ts +353 -0
  263. package/src/embed/engines/framingPageSession.ts +169 -0
  264. package/src/embed/handlers/embed.ts +130 -0
  265. package/src/embed/rules/allowedDomains.ts +71 -0
  266. package/src/embed/rules/bridgeMessages.ts +224 -0
  267. package/src/embed/rules/defaults.ts +173 -0
  268. package/src/embed/rules/displaySeed.ts +115 -0
  269. package/src/embed/rules/embedAllowlist.ts +146 -0
  270. package/src/embed/rules/embedConstraints.ts +215 -0
  271. package/src/embed/rules/embedElements.ts +277 -0
  272. package/src/embed/rules/embedSectionFields.ts +126 -0
  273. package/src/embed/rules/embedSecurity.ts +116 -0
  274. package/src/embed/rules/fieldDependencies.ts +89 -0
  275. package/src/embed/rules/fieldOptions.ts +138 -0
  276. package/src/embed/rules/layerOptions.ts +161 -0
  277. package/src/embed/rules/readyProtocol.ts +66 -0
  278. package/src/embed/rules/safetyRules.ts +215 -0
  279. package/src/embed/rules/snippet.ts +531 -0
  280. package/src/embed/rules/tableCode.ts +270 -0
  281. package/src/embed/stores/embed.ts +60 -0
  282. package/src/embed/stores/embedContent.ts +77 -0
  283. package/src/engines/index.ts +81 -0
  284. package/src/handlers/index.ts +66 -0
  285. package/src/index.ts +1065 -0
  286. package/src/itinerary/contracts/itinerary.ts +705 -0
  287. package/src/itinerary/engines/itineraryPace.ts +612 -0
  288. package/src/itinerary/engines/profileMarker.ts +238 -0
  289. package/src/itinerary/handlers/importStaging.ts +352 -0
  290. package/src/itinerary/handlers/itinerary.ts +572 -0
  291. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  292. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  293. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  294. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  295. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  296. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  297. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  298. package/src/itinerary/handlers/publicationScope.ts +118 -0
  299. package/src/itinerary/handlers/restItineraries.ts +752 -0
  300. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  301. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  302. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  303. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  304. package/src/itinerary/handlers/suggestParams.ts +379 -0
  305. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  306. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  307. package/src/itinerary/rules/activity.ts +139 -0
  308. package/src/itinerary/rules/analysis.ts +42 -0
  309. package/src/itinerary/rules/ceiling.ts +49 -0
  310. package/src/itinerary/rules/createFlow.ts +107 -0
  311. package/src/itinerary/rules/densify.ts +440 -0
  312. package/src/itinerary/rules/draftSurface.ts +219 -0
  313. package/src/itinerary/rules/editorView.ts +83 -0
  314. package/src/itinerary/rules/export.ts +159 -0
  315. package/src/itinerary/rules/friendlyName.ts +77 -0
  316. package/src/itinerary/rules/import.ts +1050 -0
  317. package/src/itinerary/rules/importFiles.ts +140 -0
  318. package/src/itinerary/rules/importTotals.ts +77 -0
  319. package/src/itinerary/rules/liveSegment.ts +712 -0
  320. package/src/itinerary/rules/lngLat.ts +17 -0
  321. package/src/itinerary/rules/mapSync.ts +100 -0
  322. package/src/itinerary/rules/previewRender.ts +416 -0
  323. package/src/itinerary/rules/profileReadout.ts +216 -0
  324. package/src/itinerary/rules/routing.ts +707 -0
  325. package/src/itinerary/rules/suggest.ts +522 -0
  326. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  327. package/src/itinerary/rules/view.ts +61 -0
  328. package/src/itinerary/stores/importSession.ts +319 -0
  329. package/src/itinerary/stores/itinerary.ts +331 -0
  330. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  331. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  332. package/src/itinerary/stores/suggestSession.ts +418 -0
  333. package/src/layers/contracts/itinerary.ts +46 -0
  334. package/src/layers/contracts/overlay.ts +132 -0
  335. package/src/layers/handlers/enrichment.ts +36 -0
  336. package/src/layers/handlers/overlay.ts +406 -0
  337. package/src/layers/handlers/restLayers.ts +94 -0
  338. package/src/layers/handlers/tiles.ts +25 -0
  339. package/src/layers/rules/layers.ts +212 -0
  340. package/src/layers/rules/overlayInstant.ts +12 -0
  341. package/src/layers/rules/reachabilityIcon.ts +18 -0
  342. package/src/layers/rules/readout.ts +102 -0
  343. package/src/layers/stores/layers.ts +262 -0
  344. package/src/map/contracts/contextmenu.ts +33 -0
  345. package/src/map/contracts/geolocate.ts +37 -0
  346. package/src/map/contracts/map.ts +146 -0
  347. package/src/map/contracts/streetview.ts +53 -0
  348. package/src/map/contracts/terrain.ts +152 -0
  349. package/src/map/handlers/contextMenu.ts +135 -0
  350. package/src/map/handlers/geolocate.ts +52 -0
  351. package/src/map/handlers/map.ts +391 -0
  352. package/src/map/handlers/streetview.ts +94 -0
  353. package/src/map/handlers/terrain.ts +663 -0
  354. package/src/map/rules/baseTerrain.ts +75 -0
  355. package/src/map/rules/clickTargets.ts +464 -0
  356. package/src/map/rules/constraints.ts +32 -0
  357. package/src/map/rules/contextMenuReadout.ts +67 -0
  358. package/src/map/rules/coordinates.ts +71 -0
  359. package/src/map/rules/itineraryFit.ts +8 -0
  360. package/src/map/rules/mapEvents.ts +64 -0
  361. package/src/map/rules/mapProjection.ts +476 -0
  362. package/src/map/rules/terrainReading.ts +62 -0
  363. package/src/plugins/contracts/ids.ts +66 -0
  364. package/src/plugins/contracts/plugin.ts +202 -0
  365. package/src/plugins/contracts/slots.ts +137 -0
  366. package/src/plugins/engines/studioPlugin.ts +1365 -0
  367. package/src/plugins/index.ts +111 -0
  368. package/src/plugins/rules/contributions.ts +152 -0
  369. package/src/plugins/rules/errors.ts +60 -0
  370. package/src/plugins/rules/ids.ts +42 -0
  371. package/src/plugins/rules/validation.ts +249 -0
  372. package/src/rules/listeners.ts +57 -0
  373. package/src/rules/origin.ts +13 -0
  374. package/src/rules/storeWrite.ts +37 -0
  375. package/src/rules/types.ts +136 -0
  376. package/src/seams/index.ts +79 -0
  377. package/src/seams/rules/clock.ts +28 -0
  378. package/src/seams/rules/formatters.ts +211 -0
  379. package/src/seams/rules/ids.ts +102 -0
  380. package/src/seams/rules/links.ts +66 -0
  381. package/src/seams/rules/navigation.ts +222 -0
  382. package/src/seams/rules/notify.ts +49 -0
  383. package/src/seams/rules/persistenceDrawer.ts +220 -0
  384. package/src/seams/rules/saveFile.ts +101 -0
  385. package/src/seams/rules/seams.ts +156 -0
  386. package/src/seams/rules/storage.ts +116 -0
  387. package/src/search/contracts/overlay.ts +74 -0
  388. package/src/search/contracts/search.ts +197 -0
  389. package/src/search/handlers/pois.ts +57 -0
  390. package/src/search/handlers/search.ts +280 -0
  391. package/src/search/rules/params.ts +925 -0
  392. package/src/search/rules/poiGroups.ts +138 -0
  393. package/src/search/rules/searchFetch.ts +139 -0
  394. package/src/search/rules/timeWindow.ts +30 -0
  395. package/src/search/stores/search.ts +51 -0
  396. package/src/segments/contracts/itinerary.ts +433 -0
  397. package/src/segments/contracts/segment.ts +35 -0
  398. package/src/segments/engines/segmentDraft.ts +926 -0
  399. package/src/segments/handlers/chainGuards.ts +67 -0
  400. package/src/segments/handlers/directions.ts +44 -0
  401. package/src/segments/handlers/itineraryEcho.ts +45 -0
  402. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  403. package/src/segments/handlers/segment.ts +111 -0
  404. package/src/segments/handlers/segmentEdit.ts +1341 -0
  405. package/src/segments/handlers/segmentGroups.ts +347 -0
  406. package/src/segments/handlers/segmentStructure.ts +1144 -0
  407. package/src/segments/rules/chain.ts +196 -0
  408. package/src/segments/rules/chainModel.ts +217 -0
  409. package/src/segments/rules/colors.ts +11 -0
  410. package/src/segments/rules/commit.ts +76 -0
  411. package/src/segments/rules/draft.ts +90 -0
  412. package/src/segments/rules/draftDisposition.ts +43 -0
  413. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  414. package/src/segments/rules/engine.ts +222 -0
  415. package/src/segments/rules/groupSave.ts +234 -0
  416. package/src/segments/rules/hazardPrompt.ts +60 -0
  417. package/src/segments/rules/itineraryEcho.ts +40 -0
  418. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  419. package/src/segments/rules/merge.ts +51 -0
  420. package/src/segments/rules/metrics.ts +456 -0
  421. package/src/segments/rules/naming.ts +168 -0
  422. package/src/segments/rules/segmentArming.ts +144 -0
  423. package/src/segments/rules/splitPick.ts +84 -0
  424. package/src/segments/rules/viaSimplify.ts +230 -0
  425. package/src/segments/stores/directions.ts +77 -0
  426. package/src/segments/stores/roadAccessDialog.ts +58 -0
  427. package/src/segments/stores/segmentEdit.ts +922 -0
  428. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  429. package/src/segments/stores/segmentSplit.ts +77 -0
  430. package/src/share/contracts/share.ts +39 -0
  431. package/src/share/contracts/shareLink.ts +63 -0
  432. package/src/share/engines/shareLink.ts +1053 -0
  433. package/src/share/handlers/share.ts +47 -0
  434. package/src/share/handlers/shareLink.ts +231 -0
  435. package/src/share/handlers/shareScope.ts +54 -0
  436. package/src/share/rules/link.ts +89 -0
  437. package/src/share/rules/shareLink.ts +218 -0
  438. package/src/share/rules/targets.ts +92 -0
  439. package/src/share/rules/viewConfig.ts +95 -0
  440. package/src/share/stores/share.ts +58 -0
  441. package/src/strings/fr/index.ts +18 -0
  442. package/src/strings/fr/rules/fr.ts +2368 -0
  443. package/src/strings/index.ts +98 -0
  444. package/src/strings/rules/confirmCopy.ts +156 -0
  445. package/src/strings/rules/draftToolNames.ts +94 -0
  446. package/src/strings/rules/en.ts +2519 -0
  447. package/src/strings/rules/failureAlert.ts +115 -0
  448. package/src/strings/rules/formError.ts +400 -0
  449. package/src/strings/rules/maneuvers.ts +107 -0
  450. package/src/strings/rules/outputOptions.ts +126 -0
  451. package/src/strings/rules/publicationState.ts +100 -0
  452. package/src/strings/rules/routeHazardCopy.ts +62 -0
  453. package/src/strings/rules/searchLabels.ts +50 -0
  454. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  455. package/src/strings/rules/studioCopy.ts +130 -0
  456. package/src/strings/rules/unitOptions.ts +119 -0
  457. package/src/testing/checkedBus.ts +226 -0
  458. package/src/testing/index.ts +30 -0
  459. package/src/testing/plugins.ts +106 -0
  460. package/src/testing/studio.ts +267 -0
  461. package/src/testing/urlSeam.ts +153 -0
  462. package/src/time/index.ts +12 -0
  463. package/src/time/rules/sun.ts +78 -0
  464. package/src/video/contracts/cameraSchemas.ts +266 -0
  465. package/src/video/contracts/profileSchemas.ts +37 -0
  466. package/src/video/contracts/video.ts +601 -0
  467. package/src/video/handlers/video.ts +1638 -0
  468. package/src/video/handlers/videoDirector.ts +114 -0
  469. package/src/video/rules/previewRefresh.ts +76 -0
  470. package/src/video/rules/profileSource.ts +51 -0
  471. package/src/video/rules/routeSpans.ts +79 -0
  472. package/src/video/rules/shotDefaults.ts +28 -0
  473. package/src/video/rules/stepOrder.ts +17 -0
  474. package/src/video/rules/videoSnapshot.ts +136 -0
  475. package/src/video/stores/directorThreads.ts +167 -0
  476. package/src/video/stores/videoExport.ts +290 -0
  477. package/src/viewer/contracts/preferences.ts +40 -0
  478. package/src/viewer/handlers/preferences.ts +91 -0
  479. package/src/viewer/rules/capabilities.ts +42 -0
  480. package/src/viewer/rules/config.ts +266 -0
  481. package/src/viewer/rules/context.ts +375 -0
  482. package/src/viewer/rules/ownership.ts +134 -0
  483. package/src/viewer/rules/platformViewer.ts +199 -0
  484. package/src/viewer/rules/scope.ts +197 -0
  485. package/src/viewer/rules/url.ts +145 -0
  486. package/src/viewer/rules/viewer.ts +307 -0
  487. package/src/viewer/rules/viewerSeam.ts +49 -0
  488. package/src/viewer/rules/viewerUnits.ts +34 -0
  489. package/src/waypoints/contracts/itinerary.ts +417 -0
  490. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  491. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  492. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  493. package/src/waypoints/rules/amenities.ts +30 -0
  494. package/src/waypoints/rules/defaults.ts +31 -0
  495. package/src/waypoints/rules/details.ts +213 -0
  496. package/src/waypoints/rules/detailsDraft.ts +312 -0
  497. package/src/waypoints/rules/detailsPreview.ts +76 -0
  498. package/src/waypoints/rules/detailsSave.ts +356 -0
  499. package/src/waypoints/rules/draftDirty.ts +45 -0
  500. package/src/waypoints/rules/icons.ts +32 -0
  501. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  502. package/src/waypoints/rules/naming.ts +185 -0
  503. package/src/waypoints/rules/sections.ts +77 -0
  504. package/src/waypoints/rules/waypointDraft.ts +62 -0
  505. package/src/waypoints/stores/waypointDetails.ts +62 -0
  506. package/src/waypoints/stores/waypointEdit.ts +566 -0
  507. package/src/zones/contracts/collection.ts +37 -0
  508. package/src/zones/contracts/zone.ts +528 -0
  509. package/src/zones/engines/zoneForm.ts +1773 -0
  510. package/src/zones/handlers/restZones.ts +287 -0
  511. package/src/zones/handlers/zonePublish.ts +206 -0
  512. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  513. package/src/zones/handlers/zones.ts +2254 -0
  514. package/src/zones/rules/geometry.ts +946 -0
  515. package/src/zones/rules/zoneDefaults.ts +34 -0
  516. package/src/zones/rules/zoneDraft.ts +54 -0
  517. package/src/zones/rules/zoneForm.ts +563 -0
  518. package/src/zones/rules/zoneMetadata.ts +29 -0
  519. package/src/zones/rules/zoneSource.ts +87 -0
  520. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  521. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1341 @@
1
+ import type { Geometry, Position } from "geojson";
2
+
3
+ import type { ItinerarySegment } from "@mountaya/client";
4
+ import {
5
+ buildSegmentGeometry,
6
+ DIRECTIONS_VIA_MAX,
7
+ extractLines,
8
+ extractVias,
9
+ SEGMENT_MIN_VIAS,
10
+ } from "@mountaya/elements/geo";
11
+ import { DEFAULT_SEGMENT_COLOR, pickLivelyColor } from "@mountaya/elements/style";
12
+
13
+ import type { StudioToolOutputs } from "../../bus/contracts/studioTools.js";
14
+ import type { ToolFailure, ToolResult } from "../../bus/rules/types.js";
15
+ import {
16
+ guardNoActiveDraft,
17
+ resolveMutationSink,
18
+ sinkCreatedSegment,
19
+ } from "../../data/handlers/mutationSink.js";
20
+ import { writeThrough } from "../../data/handlers/writeThrough.js";
21
+ import {
22
+ acquireCollabLock,
23
+ editBeginSubject,
24
+ editBeginSubjectLeft,
25
+ guardCollabLock,
26
+ guardEditBegin,
27
+ guardEditBeginUnderLock,
28
+ releaseCollabEntity,
29
+ } from "../../edit/handlers/editLock.js";
30
+ import { refuseReadOnlyItinerary } from "../../edit/handlers/editor.js";
31
+ import { showingDraft } from "../../itinerary/rules/draftSurface.js";
32
+ import type { StudioToolContext, StudioToolDefinition } from "../../viewer/rules/context.js";
33
+ import { refuseUngrantedItinerary } from "../../viewer/rules/ownership.js";
34
+ import { draftCoordinates } from "../rules/draft.js";
35
+ import { activityForId, clampSeedPoint, defaultEngineForActivity } from "../rules/engine.js";
36
+ import {
37
+ type SegmentEditSession,
38
+ type SegmentInsertAnchor,
39
+ segmentEditSessionMark,
40
+ } from "../stores/segmentEdit.js";
41
+ import {
42
+ activeChain,
43
+ guardNoArmedSegmentEdit,
44
+ notHeldFailure,
45
+ notOpenFailure,
46
+ } from "./chainGuards.js";
47
+
48
+ /**
49
+ * toViaPositions widens validated [lng, lat] tuples to the Position[] the GeoJSON
50
+ * builders and the data-API input expect. The tuple form proves the 2-length at
51
+ * the boundary; Position is the structural array GeoJSON types accept.
52
+ */
53
+ const toViaPositions = (vias: [number, number][]): Position[] => vias.map((via) => [...via]);
54
+
55
+ /**
56
+ * applySegmentDraftFromStore re-seeds the map's editable feature from the
57
+ * store's current edit draft after an undo/redo. The store holds the draft as
58
+ * a GeometryCollection (or null at the empty seed); the map's editable handles
59
+ * are the via/vertex coordinates, so the draft's leaves are flattened back to
60
+ * coordinates and pushed through applySegmentDraft (a programmatic write the
61
+ * draft-change seam flags so it does not loop back into history). A null draft
62
+ * is the start of the edit, so the session's seed is applied: a reshape's saved
63
+ * handles, or none for a segment drawn from scratch. A no-op against a null map
64
+ * and with no session open. ctx is the first positional parameter.
65
+ */
66
+ const applySegmentDraftFromStore = (ctx: StudioToolContext): void => {
67
+ const session = ctx.ui.getState().segmentEditSession;
68
+ if (!session) {
69
+ return;
70
+ }
71
+
72
+ // The store holds the start of an edit as no draft at all, and the map drew that start from
73
+ // the session's seed: a reshape's saved vias, or nothing for a segment drawn from scratch.
74
+ ctx.map?.applySegmentDraft(
75
+ session.draft ? draftCoordinates(session.draft) : toViaPositions(session.seedVias),
76
+ );
77
+ };
78
+
79
+ /**
80
+ * createSegment appends a segment to an itinerary, writing through to the API. It builds the wire
81
+ * GeometryCollection from the draft: a MultiPoint of vias in directions mode (the router routes
82
+ * them, its via range enforced at the boundary), a LineString in linestring mode. The API computes
83
+ * the routed geometry and metrics and snaps the start to the previous segment's end. The append
84
+ * result is only knowable after the API routes and cascades, so it patches nothing optimistically;
85
+ * the refetch fills the new segment in. A 409 is surfaced as a conflict. It persists, so it needs
86
+ * the api seam.
87
+ *
88
+ * The freehand `linestring` branch is a HUMAN path: the user draws the line on the map. The agent
89
+ * has no drawing surface, so an agent-origin dispatch (ctx.origin === "agent") is refused before
90
+ * any write: a `directions` append (routed vias) is the agent's only create. A human draw-engine
91
+ * create leaves ctx.origin unset and is untouched.
92
+ */
93
+ export const createSegment: StudioToolDefinition<"studio.itinerary.segment.create"> = {
94
+ handler: (ctx, input) => {
95
+ // Refuse a freehand create on the agent path: the user draws linestrings on
96
+ // the map, the agent proposes routed geometry only. A human draw-engine create
97
+ // (ctx.origin unset) falls straight through to the write.
98
+ if (input.mode === "linestring" && ctx.origin === "agent") {
99
+ return {
100
+ code: "invalid-input",
101
+ error:
102
+ "freehand (linestring) segments are drawn by the user in the studio, not created by the agent; propose a directions segment through routed vias instead",
103
+ ok: false,
104
+ };
105
+ }
106
+
107
+ const coordinates =
108
+ input.mode === "directions" ? toViaPositions(input.vias) : toViaPositions(input.line);
109
+ const geojson = buildSegmentGeometry(input.mode, coordinates);
110
+
111
+ // Every segment gets a vivid color, distinct from the one it continues. Omitting it falls back
112
+ // to the activity default, so a route built segment by segment would read as one uniformly grey
113
+ // line on the map: the caller may name a color, and when it does not, one is picked rather than
114
+ // skipped.
115
+ const previous = ctx.ui.getState().activeItinerary?.segments?.at(-1)?.color ?? null;
116
+ const color = input.color ?? pickLivelyColor(previous);
117
+
118
+ return writeThrough(ctx, {
119
+ itineraryId: input.itineraryId,
120
+ // The API routes and cascades neighbours, so the appended segment's geometry/metrics are only
121
+ // knowable after the refetch: patch nothing.
122
+ optimistic: () => {},
123
+ persist: (api) =>
124
+ api.persistence.createSegment(input.itineraryId, {
125
+ color,
126
+ geojson,
127
+ mode: input.mode,
128
+ name: input.name,
129
+ }),
130
+ summary: (segment) => `Added segment “${segment.name}”.`,
131
+ });
132
+ },
133
+ };
134
+
135
+ /** UpdateSegmentGeometryInput is the parsed input of `studio.itinerary.segment.updateGeometry`. */
136
+ type UpdateSegmentGeometryInput = Parameters<
137
+ StudioToolDefinition<"studio.itinerary.segment.updateGeometry">["handler"]
138
+ >[1];
139
+
140
+ /**
141
+ * updateGeometryRefusal answers why a segment's geometry cannot be replaced, from what the studio
142
+ * holds, or null for a replacement that can be sent: a draft that shows, an itinerary that is not
143
+ * the one open, a reader who holds no write grant on it (`forbidden`), a segment the open chain
144
+ * does not hold, a geometry edit of another segment the
145
+ * reader has armed, and a collaborator's lock on the segment or on either neighbour. The API
146
+ * re-routes both neighbours with the segment, so each is read as the merge reads the pair it fuses.
147
+ * An edit armed on this segment is the reader's own and is refused nothing here.
148
+ */
149
+ const updateGeometryRefusal = (
150
+ ctx: StudioToolContext,
151
+ input: UpdateSegmentGeometryInput,
152
+ ): ToolFailure | null => {
153
+ const drafting = guardNoActiveDraft(ctx, "update segment geometry");
154
+ if (drafting) {
155
+ return drafting;
156
+ }
157
+
158
+ const chain = activeChain(ctx, input.itineraryId);
159
+ if (!chain) {
160
+ return notOpenFailure("update segment geometry", input.itineraryId);
161
+ }
162
+
163
+ // A reader who holds no write grant on the open itinerary is refused before any request.
164
+ const ungranted = refuseUngrantedItinerary(ctx, input.itineraryId);
165
+ if (ungranted) {
166
+ return ungranted;
167
+ }
168
+
169
+ const index = chain.findIndex((segment) => segment.id === input.segmentId);
170
+ if (index === -1) {
171
+ return notHeldFailure("update segment geometry", input.segmentId);
172
+ }
173
+
174
+ const own = ctx.ui.getState().segmentEditSession?.segmentId === input.segmentId;
175
+ const editing = own ? null : guardNoArmedSegmentEdit(ctx);
176
+ if (editing) {
177
+ return editing;
178
+ }
179
+
180
+ for (const segment of [chain[index - 1], chain[index], chain[index + 1]]) {
181
+ const blocked = segment ? guardCollabLock(ctx, "segment", segment.id) : null;
182
+ if (blocked) {
183
+ return blocked;
184
+ }
185
+ }
186
+
187
+ return null;
188
+ };
189
+
190
+ /**
191
+ * updateSegmentGeometry persists a new geometry for one segment, writing through to the API. It
192
+ * builds the same wire GeometryCollection as create (a vias MultiPoint or a freehand LineString)
193
+ * and the API re-routes/re-analyzes the edited segment AND re-routes its prev + next neighbours
194
+ * (the edited segment is the cascade anchor). The neighbour cascade is only knowable after the
195
+ * refetch, so it patches nothing optimistically: the whole itinerary is refetched and the edited
196
+ * segment plus its reshaped neighbours come back together. A 409 (the revision the edit was built
197
+ * on is stale, e.g. a concurrent cascade) is surfaced as a conflict after a reload. It persists, so
198
+ * it needs the api seam.
199
+ *
200
+ * It re-routes both neighbours, so it takes the guards a chain verb takes
201
+ * ({@link updateGeometryRefusal}): `draft-open`, `not-found`, `edit-in-progress` while another
202
+ * segment's geometry edit is armed, and `collab-locked` while a collaborator holds the segment or
203
+ * a neighbour.
204
+ */
205
+ export const updateSegmentGeometry: StudioToolDefinition<"studio.itinerary.segment.updateGeometry"> =
206
+ {
207
+ // Hidden from the LLM manifest: the agent reshapes a segment through the live
208
+ // editPropose hand-off (the user saves), never a direct geometry persist.
209
+ agentHidden: true,
210
+ handler: (ctx, input) => {
211
+ const refused = updateGeometryRefusal(ctx, input);
212
+ if (refused) {
213
+ return refused;
214
+ }
215
+
216
+ const coordinates =
217
+ input.mode === "directions" ? toViaPositions(input.vias) : toViaPositions(input.line);
218
+ const geojson = buildSegmentGeometry(input.mode, coordinates);
219
+
220
+ return writeThrough(ctx, {
221
+ itineraryId: input.itineraryId,
222
+ // The API cascades an edit to the prev/next neighbours; their reshaped geometry is only
223
+ // knowable on the refetch, so patch nothing optimistically.
224
+ optimistic: () => {},
225
+ persist: (api) =>
226
+ api.persistence.updateSegment(input.itineraryId, input.segmentId, {
227
+ geojson,
228
+ }),
229
+ summary: () => `Updated segment ${input.segmentId} geometry.`,
230
+ });
231
+ },
232
+ precondition: updateGeometryRefusal,
233
+ };
234
+
235
+ /**
236
+ * recolorSegment persists a new color for one segment, writing through to the API. The optimistic
237
+ * patch recolors the segment in the open itinerary so the change shows instantly: on the tile
238
+ * render after the refetch, and live on the editing render when that segment is being edited (a
239
+ * color change mid-edit must recolor the editable draft + routed preview, which the tile copy
240
+ * cannot show because it is hidden during the edit, so it also calls setSegmentDraftStyle). The
241
+ * color carries no neighbour cascade, so the optimistic recolor is exact. Persisting + editing, so
242
+ * it needs the api seam and the "editor" capability.
243
+ */
244
+ export const recolorSegment: StudioToolDefinition<"studio.itinerary.segment.recolor"> = {
245
+ handler: (ctx, input) => {
246
+ // Recolor the live editing render when this segment is the one being edited: its
247
+ // tile copy is hidden, so setSegmentDraftStyle recolors the map draft + preview and
248
+ // recolorSegmentEditLive recolors the liveSegment the elevation panel plots. These
249
+ // are edit-state seams, not persistence, so they stay in the tool ahead of the sink
250
+ // write.
251
+ if (ctx.ui.getState().segmentEditSession?.segmentId === input.segmentId) {
252
+ ctx.map?.setSegmentDraftStyle({ color: input.color });
253
+ ctx.ui.getState().recolorSegmentEditLive(input.color);
254
+ }
255
+
256
+ return resolveMutationSink(ctx).recolorSegment(ctx, {
257
+ color: input.color,
258
+ itineraryId: input.itineraryId,
259
+ segmentId: input.segmentId,
260
+ });
261
+ },
262
+ };
263
+
264
+ /**
265
+ * setSegmentSpeed sets a new travel speed (km/h, null = the activity default) for one segment,
266
+ * routing the persistence side through the sink: the RestSink writes through to the API (which
267
+ * recomputes the duration, so it patches nothing optimistically), the DraftSink writes the speed
268
+ * onto the import draft, so the SAME tool serves a persisted edit and an import-draft edit.
269
+ * Editing. ctx is the first positional parameter.
270
+ */
271
+ export const setSegmentSpeed: StudioToolDefinition<"studio.itinerary.segment.setSpeed"> = {
272
+ handler: (ctx, input) =>
273
+ resolveMutationSink(ctx).setSegmentSpeed(ctx, {
274
+ itineraryId: input.itineraryId,
275
+ segmentId: input.segmentId,
276
+ speed: input.speed,
277
+ }),
278
+ };
279
+
280
+ /**
281
+ * guardDirectionsBegin refuses a directions edit the map's editor cannot route, before a session
282
+ * opens: one that names no activity to route for, and one in a context with no API client to
283
+ * route through.
284
+ *
285
+ * The map client refuses both when it is armed, which is after the session opened and where no
286
+ * result carries the reason. Refused here, the caller reads which of the two is missing and
287
+ * nothing is left to close. A freehand edit routes nothing and is never refused.
288
+ *
289
+ * @returns The refusal, or null when the edit can be routed.
290
+ */
291
+ const guardDirectionsBegin = (
292
+ ctx: StudioToolContext,
293
+ activitySlug: string | undefined,
294
+ ): ToolFailure | null => {
295
+ if (activitySlug === undefined || activitySlug === "") {
296
+ return {
297
+ code: "invalid-input",
298
+ error:
299
+ "begin segment edit: a directions edit routes for one activity and activitySlug names none; pass the slug of the itinerary's activity, or begin the edit in linestring mode",
300
+ ok: false,
301
+ };
302
+ }
303
+
304
+ if (!ctx.api) {
305
+ return {
306
+ code: "no-api",
307
+ error:
308
+ "begin segment edit: a directions edit routes through the API client and the context holds none; set the studio's data seam, or begin the edit in linestring mode",
309
+ ok: false,
310
+ };
311
+ }
312
+
313
+ return null;
314
+ };
315
+
316
+ /**
317
+ * savedSegment reads one segment from the open itinerary, or undefined when no itinerary is open
318
+ * or the open one does not hold it. A segment drawn from scratch and a segment of an import's or
319
+ * a suggestion's draft are not found here.
320
+ */
321
+ const savedSegment = (ctx: StudioToolContext, segmentId: string): ItinerarySegment | undefined =>
322
+ ctx.ui.getState().activeItinerary?.segments.find((entry) => entry.id === segmentId);
323
+
324
+ /**
325
+ * giveBackSegmentLock releases the soft-lock a segment begin was granted and will not use, since
326
+ * what it was asked on changed while the lock was out.
327
+ *
328
+ * One segment has one lock. A session armed on that segment holds it, and releasing it would
329
+ * leave that session unlocked, so the lock stays with it.
330
+ */
331
+ const giveBackSegmentLock = (ctx: StudioToolContext, segmentId: string): void => {
332
+ if (ctx.ui.getState().segmentEditSession?.segmentId !== segmentId) {
333
+ releaseCollabEntity(ctx, "segment", segmentId);
334
+ }
335
+ };
336
+
337
+ /**
338
+ * segmentEditBegin opens the store's segment edit session: the single record the map seam and
339
+ * SegmentDraftEngine, which the editor hook drives, read to arm the per-mode engine and surface the
340
+ * in-flight edit. It enforces mutual exclusion across families: a dispatch while another session
341
+ * (segment OR waypoint) is armed returns `edit-in-progress` and the store stays untouched, so the
342
+ * one-engine invariant holds at the bus surface where the invariant tests exercise it. On accept it
343
+ * is a pure store write: the tool persists the segment, the mode, the color the edit renders in,
344
+ * the optional draft name + activity slug + pinned boundaries + seed vias, then returns;
345
+ * SegmentDraftEngine, which the editor hook drives, arms beginSegmentEdit on the map from the
346
+ * resulting session, so the arming layer stays inside the engine abstraction and the tool never
347
+ * races a not-yet-mounted map. Editing. ctx is the first positional parameter.
348
+ *
349
+ * A directions edit the map's editor could not route is refused before anything is taken, as
350
+ * {@link guardDirectionsBegin} sets out. The one-edit guard runs twice, before the lock is asked
351
+ * for and once it is held ({@link guardEditBeginUnderLock}), so two begins in flight open one
352
+ * session.
353
+ *
354
+ * The soft-lock is a round trip, and the begin arms on what it was asked on
355
+ * ({@link editBeginSubject}): the draft an import or a suggestion holds, else the open itinerary.
356
+ * When another draft or itinerary, or none, is open as the lock answers, or when the open
357
+ * itinerary held the segment and does not hold it then, the begin answers `not-found`, arms
358
+ * nothing and gives the lock back. An itinerary that leaves from behind a staged draft leaves
359
+ * the draft open, and the begin arms.
360
+ */
361
+ export const segmentEditBegin: StudioToolDefinition<"studio.itinerary.segment.editBegin"> = {
362
+ // Hidden from the LLM manifest: the agent opens a segment edit through
363
+ // editPropose (which resolves color/activity/pinned-start itself), not the raw
364
+ // human editBegin, and never drives the edit-session lifecycle directly.
365
+ agentHidden: true,
366
+ handler: async (ctx, input) => {
367
+ // An itinerary the reader may not edit opens read-only, for want of a write role or of a
368
+ // scope that takes the write: refused before anything is armed or locked.
369
+ const readOnly = refuseReadOnlyItinerary(ctx);
370
+ if (readOnly) {
371
+ return readOnly;
372
+ }
373
+
374
+ const unroutable =
375
+ input.mode === "directions" ? guardDirectionsBegin(ctx, input.activitySlug) : null;
376
+ if (unroutable) {
377
+ return unroutable;
378
+ }
379
+
380
+ const blocked = guardEditBegin(ctx.ui.getState(), {
381
+ kind: input.mode,
382
+ segmentId: input.segmentId,
383
+ });
384
+ if (blocked) {
385
+ return blocked;
386
+ }
387
+
388
+ // What the begin is asked on, read before the lock: the staged draft or the open itinerary,
389
+ // and whether that itinerary holds the segment. A segment drawn from scratch has a fresh id
390
+ // and a draft's segment is the draft's, so neither is held, and a begin asked with nothing
391
+ // open names none.
392
+ const askedOn = editBeginSubject(ctx.ui.getState());
393
+ const savedWhenAsked =
394
+ askedOn.itineraryId !== null && savedSegment(ctx, input.segmentId) !== undefined;
395
+
396
+ // Take the collaboration soft-lock before arming: a peer editing this segment blocks entry (the
397
+ // local slice fails fast, then the collaboration seam's authoritative acquire), and a personal
398
+ // itinerary or a collab-off surface has no seam, so this is inert.
399
+ const locked = await acquireCollabLock(ctx, "segment", input.segmentId);
400
+ if (locked) {
401
+ return locked;
402
+ }
403
+
404
+ const overtaken = guardEditBeginUnderLock(ctx, {
405
+ kind: input.mode,
406
+ segmentId: input.segmentId,
407
+ });
408
+ if (overtaken) {
409
+ return overtaken;
410
+ }
411
+
412
+ // The same two reads again, in the turn that arms. The reader may have opened another
413
+ // itinerary or dropped the draft while the lock was out, or a collaborator may have deleted
414
+ // the segment: the session would be armed over what the begin was never asked on, or on a
415
+ // segment that is gone.
416
+ const leftSubject = editBeginSubjectLeft(askedOn, ctx.ui.getState());
417
+ const lostSegment = savedWhenAsked && savedSegment(ctx, input.segmentId) === undefined;
418
+ if (leftSubject || lostSegment) {
419
+ giveBackSegmentLock(ctx, input.segmentId);
420
+
421
+ return {
422
+ code: "not-found",
423
+ error: `begin segment edit: what segment ${input.segmentId} was asked on is not what is open, or does not hold it, so begin again on the itinerary or the draft that is open`,
424
+ ok: false,
425
+ };
426
+ }
427
+
428
+ ctx.ui.getState().beginSegmentEdit({
429
+ activitySlug: input.activitySlug,
430
+ draftColor: input.color,
431
+ draftName: input.name,
432
+ insertAnchor: input.insertAnchor,
433
+ mode: input.mode,
434
+ pinnedEnd: input.pinnedEnd,
435
+ pinnedStart: input.pinnedStart,
436
+ seedVias: input.seedVias,
437
+ segmentId: input.segmentId,
438
+ });
439
+
440
+ return { ok: true, summary: `Started editing segment ${input.segmentId}.` };
441
+ },
442
+ };
443
+
444
+ /**
445
+ * SegmentProposalTarget is what a proposal arms from, read out of the open itinerary: the segment
446
+ * as it is saved, whether it leads the chain, and the slug of the activity that routes it.
447
+ */
448
+ interface SegmentProposalTarget {
449
+ readonly activitySlug: string;
450
+ readonly isFirst: boolean;
451
+ readonly segment: ItinerarySegment;
452
+ }
453
+
454
+ /**
455
+ * resolveSegmentProposal reads what a proposal on `segmentId` arms from, out of the itinerary
456
+ * open now, or answers why none can be armed: the open itinerary does not hold the segment, the
457
+ * segment is not a directions one, or its activity cannot be shown to route.
458
+ */
459
+ const resolveSegmentProposal = (
460
+ ctx: StudioToolContext,
461
+ segmentId: string,
462
+ ): SegmentProposalTarget | ToolFailure => {
463
+ const itinerary = ctx.ui.getState().activeItinerary;
464
+ const segment = savedSegment(ctx, segmentId);
465
+ if (!itinerary || !segment) {
466
+ return {
467
+ code: "not-found",
468
+ error: `propose segment edit: segment ${segmentId} not in the active itinerary`,
469
+ ok: false,
470
+ };
471
+ }
472
+
473
+ // The verb reshapes a routed segment by its vias. A segment drawn by hand has none, and
474
+ // opening it in a directions session would save it as a routed one, whatever its activity
475
+ // can route.
476
+ if (segment.mode !== "directions") {
477
+ return {
478
+ code: "invalid-input",
479
+ error: `propose segment edit: segment ${segmentId} is a ${segment.mode} segment, and only a directions segment is reshaped by its vias`,
480
+ ok: false,
481
+ };
482
+ }
483
+
484
+ // Resolve the itinerary's activity from the catalog the cache seam holds at
485
+ // `{ kind: "activities" }` (the itinerary carries only the immutable activity_id). The agent
486
+ // edits directions-mode segments only, so a missing catalog (cannot prove routable) or a
487
+ // non-directions activity is refused here rather than opening a session the engine cannot route.
488
+ const categories = ctx.api?.cache.get({ kind: "activities" });
489
+ const activity = categories ? activityForId(categories, itinerary.activity_id) : null;
490
+ if (!activity || defaultEngineForActivity(activity.capabilities) !== "directions") {
491
+ return {
492
+ code: "invalid-input",
493
+ error: `propose segment edit: segment ${segmentId} is not directions-routable`,
494
+ ok: false,
495
+ };
496
+ }
497
+
498
+ return {
499
+ activitySlug: activity.slug,
500
+ isFirst: itinerary.segments[0]?.id === segmentId,
501
+ segment,
502
+ };
503
+ };
504
+
505
+ /**
506
+ * segmentEditPropose is the agent's hand-off reshape of an existing directions-mode segment: rather
507
+ * than persisting (updateGeometry) and closing, it opens a LIVE, draggable edit session seeded with
508
+ * the agent's proposed vias and hands it to the user to adjust and Save/Cancel themselves. It
509
+ * resolves the parameters editBegin needs the same way a segment menu's "Edit" does: the segment's
510
+ * color (its explicit color or the neutral default), the pinned start (the head of a later
511
+ * segment's SAVED geometry, so the chain's continuity is preserved rather than moved by the agent;
512
+ * the first segment has no predecessor, so its start is left unpinned and freely reshapeable), and
513
+ * the itinerary's activity slug, read off the catalog the cache seam holds at
514
+ * `{ kind: "activities" }` (the itinerary carries only the immutable activity_id). It refuses a
515
+ * segment whose activity is not directions-routable (the agent edits directions-mode segments
516
+ * only; linestring reshapes are the user's), an unknown segment, and, through guardEditBegin, a
517
+ * second session while another engine is armed. A segment whose own mode is not `directions` is
518
+ * refused too, whatever its activity can route: a line drawn by hand has no vias to reshape, and
519
+ * saving it from a directions session would store it as a routed segment.
520
+ *
521
+ * It takes the SAME collaboration soft-lock a human editBegin does, and for the same reason: the
522
+ * draft it opens is a real live edit of a shared entity, so a peer must be blocked from opening a
523
+ * competing one. The lock is held by the driving user, not by "the agent" (they are the one who
524
+ * will save or cancel it), so a peer sees the ordinary "{name} is editing" badge and cannot tell
525
+ * the co-pilot apart from a human edit, which is deliberate. Release is the edit session's, not the
526
+ * run's: the draft outlives the turn that opened it, and teardownActiveEditSession releases on
527
+ * commit, cancel, and navigate-away.
528
+ *
529
+ * The segment is read twice ({@link resolveSegmentProposal}): before the lock, so a proposal the
530
+ * open itinerary cannot take holds none, and again in the turn that arms, from the itinerary open
531
+ * then. The session opens in the colour and on the start saved at that moment. A segment that is
532
+ * gone by then, or is not a directions one, with another itinerary opened or a collaborator's
533
+ * change landed during the lock's round trip, is answered as the first read answers it, and the
534
+ * lock is given back.
535
+ *
536
+ * An itinerary the reader may not edit refuses the proposal before anything is armed or locked,
537
+ * as it refuses the human begin ({@link refuseReadOnlyItinerary}).
538
+ *
539
+ * On accept it is otherwise a pure store write that leaves the session OPEN: no persist, no commit.
540
+ * ctx is the first positional parameter.
541
+ */
542
+ export const segmentEditPropose: StudioToolDefinition<"studio.itinerary.segment.editPropose"> = {
543
+ handler: async (ctx, input) => {
544
+ // A proposal opens a live edit as a begin does, so an itinerary the reader may not edit
545
+ // refuses it as it refuses the begin: before anything is armed or locked.
546
+ const readOnly = refuseReadOnlyItinerary(ctx);
547
+ if (readOnly) {
548
+ return readOnly;
549
+ }
550
+
551
+ // Asked before the lock, so a proposal the open itinerary cannot take holds none.
552
+ const asked = resolveSegmentProposal(ctx, input.segmentId);
553
+ if ("ok" in asked) {
554
+ return asked;
555
+ }
556
+
557
+ const blocked = guardEditBegin(ctx.ui.getState(), {
558
+ kind: "directions",
559
+ segmentId: input.segmentId,
560
+ });
561
+ if (blocked) {
562
+ return blocked;
563
+ }
564
+
565
+ // Take the collaboration soft-lock before arming, exactly as the human editBegin
566
+ // does: the draft this opens is a live edit of a shared entity, so a peer must be
567
+ // blocked from opening a competing one. guardEditBegin above already allows an
568
+ // idempotent re-propose on the SAME segment, and re-acquiring a lock the driving
569
+ // user already holds is a no-op refresh, so iteration is unaffected.
570
+ const locked = await acquireCollabLock(ctx, "segment", input.segmentId);
571
+ if (locked) {
572
+ return locked;
573
+ }
574
+
575
+ const overtaken = guardEditBeginUnderLock(ctx, {
576
+ kind: "directions",
577
+ segmentId: input.segmentId,
578
+ });
579
+ if (overtaken) {
580
+ return overtaken;
581
+ }
582
+
583
+ // The segment is read again in the turn that arms, from the itinerary open now. The lock is
584
+ // a round trip: the reader may have opened another itinerary during it, or a collaborator
585
+ // may have deleted or changed the segment. A session armed from the earlier read would edit
586
+ // a segment the editor does not show, or open in a colour and on a start it no longer has.
587
+ const target = resolveSegmentProposal(ctx, input.segmentId);
588
+ if ("ok" in target) {
589
+ giveBackSegmentLock(ctx, input.segmentId);
590
+
591
+ return target;
592
+ }
593
+
594
+ const { activitySlug, isFirst, segment } = target;
595
+
596
+ // pinnedStart is the head of the SAVED geometry (the directions vias, or the routed line when a
597
+ // saved segment carries no via leaf), NOT the agent's new vias: a later segment's start is
598
+ // locked to the previous segment's end and the agent's reshape must not move it. The FIRST
599
+ // segment has no predecessor to anchor to, so it is left unpinned (undefined) and the agent may
600
+ // reshape its start freely, matching a human first-segment edit.
601
+ //
602
+ // A stored position carries an elevation and more decimals than the editor takes, so it passes
603
+ // through the one clamp every begin's coordinates do.
604
+ const savedHead =
605
+ extractVias(segment.geojson)[0] ?? extractLines(segment.geojson)[0]?.coordinates[0];
606
+
607
+ ctx.ui.getState().beginSegmentEdit({
608
+ activitySlug,
609
+ draftColor: segment.color ?? DEFAULT_SEGMENT_COLOR,
610
+ mode: "directions",
611
+ pinnedStart: isFirst || !savedHead ? undefined : clampSeedPoint(savedHead),
612
+ // A proposal is the co-pilot's change, saved as nothing: leaving it untouched still loses
613
+ // it, so it reads as unsaved work from the moment it opens.
614
+ savedVias: [],
615
+ seedVias: input.vias,
616
+ segmentId: input.segmentId,
617
+ });
618
+
619
+ // Name the hand-off so the run lock's carve-out can find it. The run keeps driving after this
620
+ // returns, and every other control is inert for its duration: without this slot the draft just
621
+ // opened would have no Save, no cancel and no Escape until the run yielded. Raised only here
622
+ // and in the waypoint twin, never by the agent's other editor verbs, so a draft the run is
623
+ // still building stays locked.
624
+ //
625
+ // Deliberately NOT gated on the agent origin. This verb is also the chain behind a user's own
626
+ // suggestion pick, and that pick submits its label as the next message, so the run that would
627
+ // freeze the draft is one the tap itself started. Gating here would open a draft and take its
628
+ // Save away in the same gesture. A slot raised by a human propose cannot leak either: the
629
+ // carve-out is the CONJUNCTION of the slot and the armed engine, and teardownActiveEditSession
630
+ // lowers the slot at every leave site, so a later run can only read it as armed while that same
631
+ // draft is still open in front of the user, where a live Save is the correct answer.
632
+ ctx.ui.getState().setAgentHandoff({ id: input.segmentId, kind: "segment" });
633
+
634
+ return {
635
+ ok: true,
636
+ summary: `Opened a live edit of segment ${input.segmentId} for the user to adjust and save.`,
637
+ };
638
+ },
639
+ };
640
+
641
+ /**
642
+ * resolveCommitInsertBefore turns a session's insert anchor
643
+ * ("the new segment lands after this row", or null for the head) into the wire's
644
+ * "it lands before that row". The two spellings name the same gap: the gutter knows the row above
645
+ * it, the endpoint names the row below it. Returns undefined when there is no anchor at all (an
646
+ * ordinary reshape or tail append, both of which leave the chain's shape alone) and when the anchor
647
+ * is the tail, where the gap below it IS the tail and appending is the create path's job.
648
+ *
649
+ * A head anchor over a chain that holds no segment is the tail as well: there is no row to land
650
+ * before, so the draw is appended, which is how an append opens on an empty chain
651
+ * (`studio.itinerary.segment.insertBegin` with a null anchor). The chain is read when the save is
652
+ * asked, so a row that joined meanwhile is the row the draw lands before.
653
+ *
654
+ * An anchor row the chain no longer holds is refused as `not-found`. The draw was pinned to both
655
+ * neighbours of a gap that is gone, and appending it at the tail would store it where it was not
656
+ * drawn for without saying so.
657
+ *
658
+ * The chain is the one the editor shows: the draft's while a staged draft's surface shows, where
659
+ * the commit lands on the draft, and the open itinerary's otherwise.
660
+ */
661
+ const resolveCommitInsertBefore = (
662
+ ctx: StudioToolContext,
663
+ anchor: SegmentInsertAnchor | null,
664
+ ): { segmentId: string } | ToolFailure | undefined => {
665
+ if (!anchor) {
666
+ return undefined;
667
+ }
668
+
669
+ const state = ctx.ui.getState();
670
+ const chain: readonly { readonly id: string }[] =
671
+ showingDraft(state)?.segments ?? state.activeItinerary?.segments ?? [];
672
+ if (anchor.afterSegmentId === null) {
673
+ const head = chain[0];
674
+
675
+ return head ? { segmentId: head.id } : undefined;
676
+ }
677
+
678
+ const index = chain.findIndex((segment) => segment.id === anchor.afterSegmentId);
679
+ if (index === -1) {
680
+ return {
681
+ code: "not-found",
682
+ error: `commit segment edit: segment ${anchor.afterSegmentId}, which this one was drawn to follow, is no longer in the itinerary; cancel the edit and draw the segment where it belongs`,
683
+ ok: false,
684
+ };
685
+ }
686
+
687
+ const successor = chain[index + 1];
688
+
689
+ return successor ? { segmentId: successor.id } : undefined;
690
+ };
691
+
692
+ /** SegmentCommitPayload is what one segment commit hands the sink. */
693
+ type SegmentCommitPayload = Parameters<ReturnType<typeof resolveMutationSink>["commitSegment"]>[1];
694
+
695
+ /** SegmentCommitResult is what one segment commit answers: whether its session is closed. */
696
+ type SegmentCommitResult = ToolResult<StudioToolOutputs["studio.itinerary.segment.editCommit"]>;
697
+
698
+ /**
699
+ * SegmentCommitInFlight is one segment commit whose write has not landed: the session it was sent
700
+ * for, by its mark, the write it sent, and the answer that write will give.
701
+ */
702
+ interface SegmentCommitInFlight {
703
+ /** Whether the write creates the segment, as a commit that names none does. */
704
+ readonly creates: boolean;
705
+ readonly result: Promise<SegmentCommitResult>;
706
+ readonly sessionMark: object;
707
+ /** What the write sent, as {@link segmentWriteOf} spells it. */
708
+ readonly write: string;
709
+ }
710
+
711
+ /**
712
+ * commitsInFlight holds the latest commit in flight for each studio, by its store. A commit of
713
+ * the session that entry names, which would send the write it sent, is answered by that write
714
+ * and makes no request of its own. The entry leaves when the write lands. Until then it answers
715
+ * the session it was sent for and no other: a session begun since carries another mark.
716
+ */
717
+ const commitsInFlight = new WeakMap<StudioToolContext["ui"], SegmentCommitInFlight>();
718
+
719
+ /**
720
+ * segmentWriteOf spells a commit payload as one string, so that two commits send one write
721
+ * exactly when their strings are equal.
722
+ *
723
+ * Every payload is built by {@link segmentEditCommit}, which writes its members in one order, so
724
+ * the serialisation reads every member the sink is handed and compares none by identity: a handle
725
+ * dragged back to where it was sends the same write.
726
+ */
727
+ const segmentWriteOf = (payload: SegmentCommitPayload): string => JSON.stringify(payload);
728
+
729
+ /** sessionMarkOf answers the mark of a segment session, or null for no session. */
730
+ const sessionMarkOf = (session: SegmentEditSession | null): object | null =>
731
+ session === null ? null : segmentEditSessionMark(session);
732
+
733
+ /**
734
+ * sameDraft reports whether two drafts of one session hold the same handles.
735
+ *
736
+ * The same object is the same draft, which is the answer for a session nothing touched and for
737
+ * an undo followed by its redo. Two objects are compared by what they spell, so a handle dragged
738
+ * away and put back where it was reads as no change.
739
+ */
740
+ const sameDraft = (a: Geometry | null, b: Geometry | null): boolean =>
741
+ a === b || JSON.stringify(a) === JSON.stringify(b);
742
+
743
+ /**
744
+ * adoptCreatedSegment turns the open session of a segment drawn from scratch into an edit of
745
+ * `created`, the segment its save created, on the store, on the map and in the collaboration
746
+ * session.
747
+ *
748
+ * The store keys the session on the saved id and gives the open itinerary the saved segment (the
749
+ * store's `adoptCreatedSegment`). A `SegmentDraftEngine` following the store arms the map again
750
+ * under that id as the write lands, from the session's seed, so the draft the session holds is put
751
+ * back on the map. The soft-lock moves with the id: the hold on the minted one is given back and
752
+ * the saved one is asked for. A lock that is not granted changes nothing here, since the segment
753
+ * did not exist a round trip ago and the save of the change is the API's to judge by its revision.
754
+ *
755
+ * For an append onto a staged draft, `created` is the segment as the draft holds it, under the id
756
+ * the draft sink minted, and the session is keyed on that one.
757
+ *
758
+ * @param mintedId The id the client minted, which the session was keyed on.
759
+ */
760
+ const adoptCreatedSegment = (
761
+ ctx: StudioToolContext,
762
+ mintedId: string,
763
+ created: ItinerarySegment,
764
+ ): void => {
765
+ ctx.ui.getState().adoptCreatedSegment(created);
766
+ applySegmentDraftFromStore(ctx);
767
+
768
+ releaseCollabEntity(ctx, "segment", mintedId);
769
+ void acquireCollabLock(ctx, "segment", created.id);
770
+ };
771
+
772
+ /**
773
+ * commitSegmentDraft sends one segment commit through the sink, then tears down the session it
774
+ * was sent for, unless that session holds a change the write does not.
775
+ *
776
+ * The write is a request, and the reader goes on editing while it is out. The teardown is for the
777
+ * session `session` is, the one open when the commit was sent and told by its mark: a commit that
778
+ * lands after that session closed, or after another one took its place on the same segment or on
779
+ * another, ends no map edit, closes no session and releases no lock, since each belongs to
780
+ * whatever is open then.
781
+ *
782
+ * A session whose draft is no longer the one it held when the write was sent ({@link sameDraft})
783
+ * has been changed since: a handle dragged, a point added, a step undone. The session's own draft
784
+ * is what is compared, at the two moments, and never the coordinates the commit carried: a
785
+ * caller may commit other coordinates than the store recorded.
786
+ *
787
+ * On a saved segment the write lands and the session stays as it is, with its handles, its
788
+ * history and its lock, and the answer is `closed: false`: a commit sent again saves the change,
789
+ * where closing would drop it unsaid. A route that resolves meanwhile, or a recolour, moves no
790
+ * draft.
791
+ *
792
+ * A segment drawn from scratch stays open the same way, as an edit of the segment its create
793
+ * saved ({@link adoptCreatedSegment}): the session stands for an id the API never saw, so it is
794
+ * keyed on the saved one, and its next save updates that segment where it would create a second.
795
+ * Where the write's answer does not hold the segment it created, there is nothing to go on
796
+ * editing and the session closes, whatever its draft holds by then.
797
+ */
798
+ const commitSegmentDraft = async (
799
+ ctx: StudioToolContext,
800
+ payload: SegmentCommitPayload,
801
+ session: SegmentEditSession | null,
802
+ ): Promise<SegmentCommitResult> => {
803
+ const sessionMark = sessionMarkOf(session);
804
+ const draftWhenSent = session?.draft ?? null;
805
+
806
+ // Whether the session the commit was sent for closed or was replaced while the write was out.
807
+ // Read from every store write and by the session's mark: a proposal or a begin may replace the
808
+ // session on the same segment, and its id alone would read as the one that was committed.
809
+ let left = false;
810
+ const unwatch = ctx.ui.subscribe((state) => {
811
+ if (sessionMarkOf(state.segmentEditSession) !== sessionMark) {
812
+ left = true;
813
+ }
814
+ });
815
+
816
+ // Route the geometry commit through the sink: the RestSink writes through to the API (update or
817
+ // create), the DraftSink recomputes the candidate on the import draft. The map/session teardown
818
+ // below is map state, not persistence, so it stays in the tool and runs only on a successful
819
+ // commit.
820
+ let committed: ToolResult<undefined>;
821
+ try {
822
+ committed = await resolveMutationSink(ctx).commitSegment(ctx, payload);
823
+ } finally {
824
+ unwatch();
825
+ }
826
+
827
+ if (!committed.ok) {
828
+ // Keep the edit open so the user can correct it against the surfaced error.
829
+ return committed;
830
+ }
831
+
832
+ const closed: SegmentCommitResult = {
833
+ data: { closed: true },
834
+ ok: true,
835
+ summary: committed.summary,
836
+ };
837
+
838
+ if (left) {
839
+ // The write is saved and the edit it came from is gone. With nothing armed the map draws
840
+ // tiles, so they are refreshed for the saved segment to show; under another edit the bust
841
+ // waits for that edit's own teardown.
842
+ if (ctx.ui.getState().segmentEditSession === null) {
843
+ ctx.map?.refreshItineraryTilesWhenSettled();
844
+ }
845
+
846
+ return closed;
847
+ }
848
+
849
+ // The session open now is the one the commit was sent for.
850
+ const open = ctx.ui.getState().segmentEditSession;
851
+ const changed = open !== null && !sameDraft(open.draft, draftWhenSent);
852
+ if (changed && payload.segmentId !== undefined) {
853
+ // Saved, and the edit holds a change made since. Nothing is torn down: the map goes on
854
+ // editing, the lock stays held, and the tiles are refreshed when the edit closes. What was
855
+ // sent is what leaving would no longer lose.
856
+ ctx.ui.getState().markSegmentDraftSaved(draftWhenSent);
857
+
858
+ return {
859
+ data: { closed: false },
860
+ ok: true,
861
+ summary: `${committed.summary} The edit stays open: its draft changed while the save was out, so commit it again to save the change.`,
862
+ };
863
+ }
864
+
865
+ const created = changed ? sinkCreatedSegment(committed) : null;
866
+ if (open !== null && created !== null) {
867
+ // Created, and the edit holds a change made since: it goes on as an edit of the saved segment,
868
+ // whose saved handles are the ones the create sent.
869
+ adoptCreatedSegment(ctx, open.segmentId, created);
870
+ ctx.ui.getState().markSegmentDraftSaved(draftWhenSent);
871
+
872
+ return {
873
+ data: { closed: false },
874
+ ok: true,
875
+ summary: `${committed.summary} The edit stays open on the saved segment: its draft changed while the save was out, so commit it again to save the change.`,
876
+ };
877
+ }
878
+
879
+ // Committed: tear the edit down. endSegmentEdit releases the base-map-switch
880
+ // block the edit held internally.
881
+ ctx.map?.endSegmentEdit();
882
+ ctx.ui.getState().commitSegmentEdit();
883
+
884
+ // Release the collaboration hold now the edit is persisted: clear the live draft (a peer's ghost
885
+ // drops at once) and release the soft-lock. Best-effort; inert on a personal itinerary. Only on a
886
+ // successful commit: a failed persist returned above with the edit still open, so the lock is
887
+ // still needed.
888
+ //
889
+ // The id is the session's and not the input's: a from-scratch create's input carries no segment
890
+ // id, and the session holds the client-minted one the lock was taken on.
891
+ if (session?.segmentId) {
892
+ releaseCollabEntity(ctx, "segment", session.segmentId);
893
+ }
894
+
895
+ // Refresh the itinerary tiles now that the engine is disposed and the normal paint is restored:
896
+ // the sink skipped the bust mid-edit (a bust fired during the dual-render does not repaint the
897
+ // saved geometry at the current zoom), so it runs here, post-teardown. endSegmentEdit reapplies
898
+ // paint synchronously, so the map is still mid-render this tick: refreshItineraryTilesWhenSettled
899
+ // defers the setTiles bust to the next settled frame, where MapLibre reliably refetches the
900
+ // current-viewport tiles and the saved segment shows without a pan/zoom.
901
+ ctx.map?.refreshItineraryTilesWhenSettled();
902
+
903
+ return closed;
904
+ };
905
+
906
+ /**
907
+ * segmentEditCommit persists the current edit draft, then tears the edit down.
908
+ * It routes the draft to the right write, reusing the same write-through path so
909
+ * the conflict/cascade handling is identical. The segment is the open session's:
910
+ * a commit that names no segment while the session stands for a saved one is
911
+ * that segment's update, a commit that names another segment is refused with
912
+ * `invalid-input`, and a session for a segment drawn from scratch is a create,
913
+ * which needs a name. On a successful persist it ends the
914
+ * map edit (restoring the tile copy), closes the store edit session, and
915
+ * unlocks the map; on a failed persist it leaves the edit open so the user can
916
+ * retry against the surfaced error. It needs the api seam and declares the
917
+ * "editor" capability. ctx is the first positional parameter.
918
+ *
919
+ * No write is sent twice: a commit dispatched while a write of the open session is in flight,
920
+ * which would send what that write sent, makes no request and answers what that write answers,
921
+ * so a key held down saves a new segment once. A draft changed since is another save. On an
922
+ * existing segment it goes out for itself. On a segment drawn from scratch it is refused with
923
+ * `conflict`, since a second create is a second segment and the write in flight does not hold
924
+ * the change.
925
+ *
926
+ * The teardown is the committed session's alone, as {@link commitSegmentDraft} sets out. The
927
+ * answer's `closed` says whether that session is closed once the write has landed. A saved
928
+ * segment whose draft changed while its write was out stays open on the change and answers
929
+ * `closed: false`. So does a segment drawn from scratch, whose session then stands for the
930
+ * segment its create saved: a commit sent again names that segment and updates it.
931
+ */
932
+ export const segmentEditCommit: StudioToolDefinition<"studio.itinerary.segment.editCommit"> = {
933
+ // Hidden from the LLM manifest: the agent never commits an open edit session. It hands the live
934
+ // draft to the user, who saves it.
935
+ agentHidden: true,
936
+ handler: (ctx, input) => {
937
+ if (!ctx.api) {
938
+ return { code: "no-api", error: "commit segment edit: no persistence seam", ok: false };
939
+ }
940
+
941
+ // The session is read before any teardown clears it: the commit is sent for this one, and
942
+ // its teardown reads the segment id and the draft it holds now.
943
+ const state = ctx.ui.getState();
944
+ const session = state.segmentEditSession;
945
+ const draft = showingDraft(state);
946
+
947
+ // A commit names the edit it saves. One that names another segment than the open edit's
948
+ // would write that segment and then close an edit it did not save.
949
+ if (
950
+ session !== null &&
951
+ input.segmentId !== undefined &&
952
+ input.segmentId !== session.segmentId
953
+ ) {
954
+ return {
955
+ code: "invalid-input",
956
+ error: `commit segment edit: segment ${input.segmentId} is not the segment being edited (${session.segmentId}); commit the open edit or cancel it first`,
957
+ ok: false,
958
+ };
959
+ }
960
+
961
+ // The itinerary is the one open in the editor, which a commit may leave out. Naming another
962
+ // one while another is open and no staged draft shows names a chain the editor does not
963
+ // hold. While a draft shows, the draft's sink answers and keys on the segment's own id.
964
+ if (
965
+ draft === null &&
966
+ input.itineraryId !== undefined &&
967
+ input.itineraryId !== null &&
968
+ state.activeItinerary !== null &&
969
+ input.itineraryId !== state.activeItinerary.id
970
+ ) {
971
+ return notOpenFailure("commit segment edit", input.itineraryId);
972
+ }
973
+
974
+ const itineraryId = input.itineraryId ?? state.activeItinerary?.id ?? "";
975
+
976
+ // A commit that names no segment while the open edit stands for a saved one means that
977
+ // segment: a reshape, or a segment drawn from scratch whose create has landed. Its create
978
+ // input was built before the create landed, and sending it would make a second segment.
979
+ const chain: readonly { readonly id: string }[] =
980
+ draft?.segments ?? state.activeItinerary?.segments ?? [];
981
+ const savedSessionId =
982
+ session !== null &&
983
+ input.segmentId === undefined &&
984
+ chain.some((segment) => segment.id === session.segmentId)
985
+ ? session.segmentId
986
+ : undefined;
987
+ const segmentId = input.segmentId ?? savedSessionId;
988
+
989
+ // A draw opened from a gutter between two rows carries the anchor naming where in the chain it
990
+ // lands. The session holds it in the "after this row" spelling the gutter has in hand; the wire
991
+ // names the row BELOW the gap, so resolve it here: the sink writes the request, it does not
992
+ // read chain positions.
993
+ const insertBefore = resolveCommitInsertBefore(ctx, session?.insertAnchor ?? null);
994
+ if (insertBefore !== undefined && "ok" in insertBefore) {
995
+ return insertBefore;
996
+ }
997
+
998
+ const coordinates =
999
+ input.mode === "directions" ? toViaPositions(input.vias) : toViaPositions(input.line);
1000
+
1001
+ // A from-scratch segment needs a name; an existing-segment update keeps its own.
1002
+ if (segmentId === undefined && input.name === undefined) {
1003
+ return {
1004
+ code: "invalid-input",
1005
+ error: "commit segment edit: a new segment needs a name",
1006
+ ok: false,
1007
+ };
1008
+ }
1009
+
1010
+ // The routing graph's distance ceiling is deliberately NOT pre-checked here. A refusal minted
1011
+ // client-side would carry a code and no localized sentence, where the commit that travels gets
1012
+ // the API's own sentence back on result.detail, which names the limit and what to do about it.
1013
+ // A round trip is the cheaper of the two costs.
1014
+
1015
+ // An update sends the geometry alone, so the name and the colour ride on a create only.
1016
+ const payload: SegmentCommitPayload = {
1017
+ color: segmentId === undefined ? input.color : undefined,
1018
+ coordinates,
1019
+ insertBefore,
1020
+ itineraryId,
1021
+ mode: input.mode,
1022
+ name: segmentId === undefined ? input.name : undefined,
1023
+ segmentId,
1024
+ };
1025
+
1026
+ // A write of this session may be out. The segment id cannot say so: a session begun again on
1027
+ // the same segment is another session, and its commit is its own. A commit with no session
1028
+ // open is a write of its own too, and nothing ties a second one to it.
1029
+ const sessionMark = sessionMarkOf(session);
1030
+ const write = segmentWriteOf(payload);
1031
+ const inFlight = commitsInFlight.get(ctx.ui);
1032
+ const ofThisSession =
1033
+ sessionMark !== null && inFlight !== undefined && inFlight.sessionMark === sessionMark
1034
+ ? inFlight
1035
+ : null;
1036
+ if (ofThisSession?.write === write) {
1037
+ // This commit would send what that write sent, for the session it was sent for, so the
1038
+ // write is its answer too.
1039
+ return ofThisSession.result;
1040
+ }
1041
+
1042
+ // A segment drawn from scratch is created once. Its create is out and is not this commit's
1043
+ // answer, since the draft changed since: the write in flight does not hold what this commit
1044
+ // would save, and a create sent again is a second segment.
1045
+ if (ofThisSession?.creates && payload.segmentId === undefined) {
1046
+ return {
1047
+ code: "conflict",
1048
+ error:
1049
+ "commit segment edit: the save that creates this segment is still out, so change the saved segment once it lands",
1050
+ ok: false,
1051
+ };
1052
+ }
1053
+
1054
+ const result = commitSegmentDraft(ctx, payload, session);
1055
+
1056
+ // The write stands for its session until it lands, and a later write of the session takes
1057
+ // its place, so a commit is only ever answered by the latest one.
1058
+ if (sessionMark !== null) {
1059
+ const flight: SegmentCommitInFlight = {
1060
+ creates: payload.segmentId === undefined,
1061
+ result,
1062
+ sessionMark,
1063
+ write,
1064
+ };
1065
+ const forget = (): void => {
1066
+ if (commitsInFlight.get(ctx.ui) === flight) {
1067
+ commitsInFlight.delete(ctx.ui);
1068
+ }
1069
+ };
1070
+ commitsInFlight.set(ctx.ui, flight);
1071
+ void result.then(forget, forget);
1072
+ }
1073
+
1074
+ return result;
1075
+ },
1076
+ };
1077
+
1078
+ /**
1079
+ * segmentEditCancel discards the active segment edit without persisting: it
1080
+ * ends the map edit (which restores the segment's tile copy, undoing the
1081
+ * dual-render hide), closes the store edit session, and unlocks the base map.
1082
+ * It is the Esc path. A no-op against a null map (the store edit still closes
1083
+ * so the UI reflects it). ctx is the first positional parameter.
1084
+ *
1085
+ * The verb takes no segment id: it closes the segment edit open when its handler runs, and gives
1086
+ * back that edit's lock. A cancel dispatched for one edit, which runs after that edit closed and
1087
+ * another opened, closes the other. With no edit open it gives no lock back and answers `ok`:
1088
+ * the map's edit is ended and the itinerary's tiles are asked for again all the same.
1089
+ */
1090
+ export const segmentEditCancel: StudioToolDefinition<"studio.itinerary.segment.editCancel"> = {
1091
+ // Hidden from the LLM manifest: the agent never cancels an open edit session. It hands the live
1092
+ // draft to the user, who decides to save or discard it.
1093
+ agentHidden: true,
1094
+ handler: (ctx) => {
1095
+ // Capture the locked segment id before cancelSegmentEdit clears the session.
1096
+ const lockedSegmentId = ctx.ui.getState().segmentEditSession?.segmentId ?? null;
1097
+
1098
+ // endSegmentEdit releases the base-map-switch block the edit held and restores
1099
+ // the segment's tile copy to full opacity.
1100
+ ctx.map?.endSegmentEdit();
1101
+ ctx.ui.getState().cancelSegmentEdit();
1102
+
1103
+ // Release the collaboration hold: a cancel always tears down, so unlike commit
1104
+ // it releases unconditionally (clear the draft ghost + release the soft-lock).
1105
+ if (lockedSegmentId) {
1106
+ releaseCollabEntity(ctx, "segment", lockedSegmentId);
1107
+ }
1108
+
1109
+ // Refresh the itinerary tiles post-teardown, exactly as segmentEditCommit
1110
+ // does: ending the edit restores the dual-render paint but does not refetch
1111
+ // the current-zoom tiles, so without this the segment stays hidden until a
1112
+ // pan/zoom. endSegmentEdit reapplies paint synchronously, so the settled
1113
+ // variant defers the setTiles bust to the next idle frame, where MapLibre
1114
+ // repaints the saved geometry in place.
1115
+ ctx.map?.refreshItineraryTilesWhenSettled();
1116
+
1117
+ return { ok: true, summary: "Cancelled the segment edit." };
1118
+ },
1119
+ };
1120
+
1121
+ /**
1122
+ * segmentEditUndo steps the active edit's draft-geometry history back one
1123
+ * entry: it asks the store to undo (moving the current draft onto the redo
1124
+ * stack and restoring the previous draft), then re-applies the restored draft
1125
+ * to the map's editable feature (applySegmentDraft re-seeds the handles +
1126
+ * re-pins vertex 0). The store's restored draft is the source of truth;
1127
+ * applySegmentDraft is a programmatic write the draft-change seam flags so it
1128
+ * does not re-enter history. It is a no-op when there is nothing to undo: the
1129
+ * map is left as it is. ctx is the first positional parameter.
1130
+ */
1131
+ export const segmentEditUndo: StudioToolDefinition<"studio.itinerary.segment.editUndo"> = {
1132
+ handler: (ctx) => {
1133
+ const before = ctx.ui.getState().segmentEditSession;
1134
+ ctx.ui.getState().undoSegmentDraft();
1135
+
1136
+ // The store writes a session only when it stepped. With no step the map already shows what
1137
+ // the store holds, and applying it again would draw the store's empty start over the seed.
1138
+ if (ctx.ui.getState().segmentEditSession === before) {
1139
+ return { ok: true, summary: "Nothing to undo in the segment edit." };
1140
+ }
1141
+
1142
+ applySegmentDraftFromStore(ctx);
1143
+
1144
+ return { ok: true, summary: "Undid the last segment edit change." };
1145
+ },
1146
+ };
1147
+
1148
+ /**
1149
+ * segmentEditRedo steps the active edit's draft-geometry history forward one
1150
+ * entry: it asks the store to redo (restoring the draft that was undone), then
1151
+ * re-applies the restored draft to the map's editable feature. Like
1152
+ * segmentEditUndo, the store is the source of truth and applySegmentDraft is
1153
+ * the programmatic replay. It is a no-op when there is nothing to redo. ctx is
1154
+ * the first positional parameter.
1155
+ */
1156
+ export const segmentEditRedo: StudioToolDefinition<"studio.itinerary.segment.editRedo"> = {
1157
+ handler: (ctx) => {
1158
+ const before = ctx.ui.getState().segmentEditSession;
1159
+ ctx.ui.getState().redoSegmentDraft();
1160
+
1161
+ // As for an undo: with no step taken the map is left as it is.
1162
+ if (ctx.ui.getState().segmentEditSession === before) {
1163
+ return { ok: true, summary: "Nothing to redo in the segment edit." };
1164
+ }
1165
+
1166
+ applySegmentDraftFromStore(ctx);
1167
+
1168
+ return { ok: true, summary: "Redid the last segment edit change." };
1169
+ },
1170
+ };
1171
+
1172
+ /**
1173
+ * openSegmentViaPrompt opens the ask-the-user prompt for a clicked handle of the segment being
1174
+ * edited. Clicking a handle is ambiguous (remove that point, or route through it again to close a
1175
+ * loop), so the engine refuses its own destructive default and hands the gesture here; this tool
1176
+ * projects the coordinate to a container pixel, writes the prompt slot the popup renders from, and
1177
+ * suspends the engine's click grammar so the click that dismisses the popup cannot also append the
1178
+ * next point.
1179
+ *
1180
+ * It guards on a mounted map and on an armed session, returning a structured failure rather than
1181
+ * throwing, so a stale emit after a commit is a clean no-op. ctx is the first positional parameter.
1182
+ */
1183
+ export const openSegmentViaPrompt: StudioToolDefinition<"studio.itinerary.segment.via.promptOpen"> =
1184
+ {
1185
+ agentHidden: true,
1186
+ handler: (ctx, input) => {
1187
+ if (!ctx.map) {
1188
+ return { code: "no-map", error: "no map is currently mounted", ok: false };
1189
+ }
1190
+
1191
+ if (!ctx.ui.getState().segmentEditSession) {
1192
+ return { code: "no-session", error: "no segment edit is active", ok: false };
1193
+ }
1194
+
1195
+ ctx.ui.getState().setSegmentViaPrompt({
1196
+ index: input.index,
1197
+ lngLat: input.lngLat,
1198
+ point: ctx.map.project(input.lngLat),
1199
+ });
1200
+ ctx.map.setSegmentViaPromptPending(true);
1201
+
1202
+ return { ok: true, summary: `Asked what to do with point ${input.index + 1}.` };
1203
+ },
1204
+ };
1205
+
1206
+ /**
1207
+ * closeSegmentViaPrompt dismisses the handle prompt without changing the draft (the Escape /
1208
+ * click-outside path) and resumes the engine's click grammar. A no-op when nothing is open, so a
1209
+ * defensive dispatch is safe. ctx is the first positional parameter.
1210
+ */
1211
+ export const closeSegmentViaPrompt: StudioToolDefinition<"studio.itinerary.segment.via.promptClose"> =
1212
+ {
1213
+ agentHidden: true,
1214
+ handler: (ctx) => {
1215
+ ctx.ui.getState().setSegmentViaPrompt(null);
1216
+ ctx.map?.setSegmentViaPromptPending(false);
1217
+
1218
+ return { ok: true, summary: "Dismissed the segment point prompt." };
1219
+ },
1220
+ };
1221
+
1222
+ /**
1223
+ * resolveViaAction is the shared body of the two prompt resolutions. It reads the live draft off
1224
+ * the map, hands `next` the chance to rewrite it, then applies the rewrite and records it:
1225
+ *
1226
+ * - the map is re-seeded through `applySegmentDraft`, a PROGRAMMATIC write, so the engine's
1227
+ * draft-change seam does not push it into history a second time;
1228
+ * - the history entry is written here instead, so the resolution is one undo step: the same shape
1229
+ * `applySegmentDraftFromStore` gives undo/redo, inverted.
1230
+ *
1231
+ * `next` returns null to refuse (a bound the caller enforces), which surfaces as a structured
1232
+ * failure with the caller's reason and leaves the draft untouched. The prompt is dismissed on every
1233
+ * path that changes something, so the popup never outlives the geometry it described.
1234
+ */
1235
+ const resolveViaAction = (
1236
+ ctx: StudioToolContext,
1237
+ index: number,
1238
+ next: (vias: Position[]) => { error: string } | { vias: Position[] },
1239
+ ): ToolFailure | null => {
1240
+ if (!ctx.map) {
1241
+ return { code: "no-map", error: "no map is currently mounted", ok: false };
1242
+ }
1243
+
1244
+ const session = ctx.ui.getState().segmentEditSession;
1245
+ if (!session) {
1246
+ return { code: "no-session", error: "no segment edit is active", ok: false };
1247
+ }
1248
+
1249
+ const vias = ctx.map.getSegmentDraft() ?? [];
1250
+ if (!vias[index]) {
1251
+ return { code: "not-found", error: "that point is no longer part of the segment", ok: false };
1252
+ }
1253
+
1254
+ const result = next(vias);
1255
+ if ("error" in result) {
1256
+ return { code: "invalid-input", error: result.error, ok: false };
1257
+ }
1258
+
1259
+ ctx.map.applySegmentDraft(result.vias);
1260
+ ctx.ui.getState().pushSegmentDraft(buildSegmentGeometry(session.mode, result.vias));
1261
+ ctx.ui.getState().setSegmentViaPrompt(null);
1262
+ ctx.map.setSegmentViaPromptPending(false);
1263
+
1264
+ return null;
1265
+ };
1266
+
1267
+ /**
1268
+ * removeSegmentVia resolves the handle prompt by dropping the clicked point. It
1269
+ * refuses to take the draft below the two-coordinate floor (a single point is not
1270
+ * a segment) and refuses to remove either pinned boundary: index 0 while the
1271
+ * session carries a pinned start (that coordinate IS the previous segment's end),
1272
+ * and the last index while it carries a pinned end (that coordinate IS the next
1273
+ * segment's start). The chain's continuity depends on both. ctx is the first
1274
+ * positional parameter.
1275
+ */
1276
+ export const removeSegmentVia: StudioToolDefinition<"studio.itinerary.segment.via.remove"> = {
1277
+ agentHidden: true,
1278
+ handler: (ctx, input) => {
1279
+ const session = ctx.ui.getState().segmentEditSession;
1280
+ const failure = resolveViaAction(ctx, input.index, (vias) => {
1281
+ if (input.index === 0 && session?.pinnedStart) {
1282
+ return { error: "the first point continues the previous segment and cannot be removed" };
1283
+ }
1284
+
1285
+ if (input.index === vias.length - 1 && session?.pinnedEnd) {
1286
+ return { error: "the last point meets the next segment and cannot be removed" };
1287
+ }
1288
+
1289
+ if (vias.length - 1 < SEGMENT_MIN_VIAS) {
1290
+ return { error: "a segment needs at least two points" };
1291
+ }
1292
+
1293
+ return { vias: vias.filter((_via, at) => at !== input.index) };
1294
+ });
1295
+
1296
+ return failure ?? { ok: true, summary: `Removed point ${input.index + 1}.` };
1297
+ },
1298
+ };
1299
+
1300
+ /**
1301
+ * repeatSegmentVia resolves the handle prompt the other way: it adds the clicked
1302
+ * point's coordinate to the END of the draft, so the line runs on and passes
1303
+ * through it a second time. Clicking the start point is how a loop is closed. An
1304
+ * insert whose end is pinned to the next segment lands the repeat just BEFORE that
1305
+ * pin, so the drawn line still finishes on its neighbour. It refuses an append that
1306
+ * would push a directions draft past the router's via cap. ctx is the first
1307
+ * positional parameter.
1308
+ */
1309
+ export const repeatSegmentVia: StudioToolDefinition<"studio.itinerary.segment.via.repeat"> = {
1310
+ agentHidden: true,
1311
+ handler: (ctx, input) => {
1312
+ const session = ctx.ui.getState().segmentEditSession;
1313
+ const failure = resolveViaAction(ctx, input.index, (vias) => {
1314
+ const via = vias[input.index];
1315
+ if (!via) {
1316
+ return { error: "that point is no longer part of the segment" };
1317
+ }
1318
+
1319
+ if (session?.mode === "directions" && vias.length + 1 > DIRECTIONS_VIA_MAX) {
1320
+ return { error: `a routed segment holds at most ${DIRECTIONS_VIA_MAX} points` };
1321
+ }
1322
+
1323
+ // The pinned end is the next segment's start and must stay last, so the repeat
1324
+ // is spliced in front of it rather than appended past it.
1325
+ if (session?.pinnedEnd) {
1326
+ const at = vias.length - 1;
1327
+
1328
+ return { vias: [...vias.slice(0, at), [...via], ...vias.slice(at)] };
1329
+ }
1330
+
1331
+ return { vias: [...vias, [...via]] };
1332
+ });
1333
+
1334
+ return (
1335
+ failure ?? {
1336
+ ok: true,
1337
+ summary: `Extended the segment back through point ${input.index + 1}.`,
1338
+ }
1339
+ );
1340
+ },
1341
+ };