@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,1144 @@
1
+ import type { z } from "zod";
2
+
3
+ import type { ItinerarySegment, ItineraryWithDetails } from "@mountaya/client";
4
+ import { groundMetersPerPixel } from "@mountaya/elements/camera";
5
+ import { buildSegmentGeometry, DIRECTIONS_VIA_MAX, extractLines } from "@mountaya/elements/geo";
6
+ import { formatDistance, type UnitFormatOptions } from "@mountaya/elements/profile";
7
+ import { pickLivelyColor } from "@mountaya/elements/style";
8
+ import { convertProportion } from "@mountaya/elements/units";
9
+
10
+ import type { studioToolContracts } from "../../bus/contracts/studioTools.js";
11
+ import type { ConfirmationValues, ToolFailure, ToolResult } from "../../bus/rules/types.js";
12
+ import { selectActiveEditEngine } from "../../chrome/rules/agentSelectors.js";
13
+ import { guardNoActiveDraft } from "../../data/handlers/mutationSink.js";
14
+ import { writeThrough } from "../../data/handlers/writeThrough.js";
15
+ import {
16
+ editInProgressError,
17
+ guardCollabLock,
18
+ guardSplitPickBehindSurface,
19
+ } from "../../edit/handlers/editLock.js";
20
+ import { refuseReadOnlyItinerary } from "../../edit/handlers/editor.js";
21
+ import { showingDraft } from "../../itinerary/rules/draftSurface.js";
22
+ import { draftToView, type ItineraryDraft } from "../../itinerary/rules/import.js";
23
+ import { studioSeamAbsences } from "../../seams/rules/seams.js";
24
+ import type {
25
+ StudioApi,
26
+ StudioToolContext,
27
+ StudioToolDefinition,
28
+ } from "../../viewer/rules/context.js";
29
+ import { refuseUngrantedItinerary } from "../../viewer/rules/ownership.js";
30
+ import { resolveViewerUnits } from "../../viewer/rules/viewerUnits.js";
31
+ import { clampSeedPoint } from "../rules/engine.js";
32
+ import { exceedsMergeViaCeiling } from "../rules/merge.js";
33
+ import {
34
+ SPLIT_MIN_END_DISTANCE_METERS,
35
+ SPLIT_PICK_TOLERANCE_PX,
36
+ segmentLengthMeters,
37
+ } from "../rules/metrics.js";
38
+ import { defaultSegmentName, splitSegmentNames } from "../rules/naming.js";
39
+ import { isSplitOnEnd, splitPickVerdict } from "../rules/splitPick.js";
40
+ import {
41
+ activeChain,
42
+ guardNoArmedSegmentEdit,
43
+ notHeldFailure,
44
+ notOpenFailure,
45
+ } from "./chainGuards.js";
46
+ import { installItineraryEcho } from "./itineraryEcho.js";
47
+
48
+ /**
49
+ * unitFormat resolves the viewer's distance/locale preferences from the viewer seam, so a confirm
50
+ * prompt can state a distance in the units the rest of the editor shows. The handlers carry no
51
+ * i18n, but the preference values themselves are plain data on the seam they already hold, and Intl
52
+ * does the rendering, which is exactly how the sidenav's own formatter works.
53
+ */
54
+ const unitFormat = (ctx: StudioToolContext): UnitFormatOptions =>
55
+ resolveViewerUnits(ctx.viewer.getPreferences());
56
+
57
+ /**
58
+ * missingPersistenceFailure is the refusal a chain-shaping verb answers a context that states no
59
+ * persistence seam: the write it stands for has nowhere to go. One sentence for the write path
60
+ * and for the two preconditions that read the seam before the reader is asked.
61
+ */
62
+ const missingPersistenceFailure = (): ToolFailure => ({
63
+ code: "no-api",
64
+ error: "reshape segment chain: no persistence seam",
65
+ ok: false,
66
+ });
67
+
68
+ /**
69
+ * applyChainMutation is the single write path behind every verb that re-shapes the segment chain.
70
+ * Those endpoints all answer with the WHOLE refreshed itinerary rather than one segment (a merge,
71
+ * split, insert, or engine change renumbers every following position and can rewrite the adjoining
72
+ * segments' geometry), so the answer is mirrored straight into the open editor and seeded into the
73
+ * detail cache instead of being thrown away and refetched, unless the editor already shows a later
74
+ * copy ({@link installItineraryEcho}). The itinerary tiles are then busted so the map repaints the
75
+ * new chain at the current camera without a pan/zoom.
76
+ *
77
+ * The bust is the SETTLED one, the same seam every other geometry-changing write takes. These verbs
78
+ * are reached from a gesture that is tearing down as they run (a split arms a point-pick engine
79
+ * whose disarm and whose confirm dialog both unmount around the frame the write resolves on), and
80
+ * MapLibre's setTiles evicts the cache but does not refetch the current-zoom tile until the view is
81
+ * idle. A bust fired on that still-rendering frame is swallowed, leaving the pre-split feature in
82
+ * the tiles: hover emphasis paints off the tile feature's segment_id, so both halves would light
83
+ * the whole original line until a reload.
84
+ *
85
+ * A throw is normalized through the shared classifier, so a stale revision reads as `conflict` and
86
+ * a refusal of the API (mismatched modes, a split at a boundary) reads as `invalid-input` rather
87
+ * than an opaque internal error. A reader who holds no write grant on the open itinerary is
88
+ * refused with `forbidden` before the request (`refuseUngrantedItinerary`).
89
+ *
90
+ * Every verb that reaches this path, and every gesture that arms one, is PERSISTED-ITINERARY-ONLY,
91
+ * so each runs {@link guardNoActiveDraft} first and refuses as `draft-open` while an import or
92
+ * suggestion draft owns the editor. A draft is a proposal held in memory: its segments carry client
93
+ * ids these endpoints have never seen, and there is no stored chain to renumber. Without the guard
94
+ * the write would land on the persisted itinerary the user is NOT looking at, or (since the draft
95
+ * displaces the active itinerary {@link activeChain} reads) bottom out in a `not-found` naming an
96
+ * itinerary that is simply not on screen. Re-shaping a draft is the draft sink's business (see
97
+ * resolveMutationSink), and these verbs deliberately have no counterpart there.
98
+ */
99
+ const applyChainMutation = async (
100
+ ctx: StudioToolContext,
101
+ itineraryId: string,
102
+ persist: (api: StudioApi) => Promise<ItineraryWithDetails>,
103
+ summary: (itinerary: ItineraryWithDetails) => string,
104
+ ): Promise<ToolResult<undefined>> => {
105
+ if (!ctx.api) {
106
+ return missingPersistenceFailure();
107
+ }
108
+
109
+ const ungranted = refuseUngrantedItinerary(ctx, itineraryId);
110
+ if (ungranted) {
111
+ return ungranted;
112
+ }
113
+
114
+ const api = ctx.api;
115
+
116
+ const itinerary = await persist(api);
117
+ installItineraryEcho(ctx, api, itineraryId, itinerary);
118
+ ctx.map?.refreshItineraryTilesWhenSettled();
119
+
120
+ return { ok: true, summary: summary(itinerary) };
121
+ };
122
+
123
+ /** MergeSegmentInput is the parsed input of `studio.itinerary.segment.merge`. */
124
+ type MergeSegmentInput = z.infer<
125
+ (typeof studioToolContracts)["studio.itinerary.segment.merge"]["input"]
126
+ >;
127
+
128
+ /**
129
+ * mergeSegmentNames resolves the pair of display names a merge confirm prompt reads (the segment
130
+ * being merged and the successor it absorbs), so the body names the two rows the user is looking at
131
+ * instead of describing them generically. A chain the store cannot resolve yields empty strings,
132
+ * and the prompt then renders its placeholders verbatim rather than failing to open.
133
+ */
134
+ const mergeSegmentNames = (ctx: StudioToolContext, input: MergeSegmentInput) => {
135
+ const chain = activeChain(ctx, input.itineraryId) ?? [];
136
+ const index = chain.findIndex((segment) => segment.id === input.segmentId);
137
+
138
+ return {
139
+ first: chain[index]?.name ?? "",
140
+ second: chain[index + 1]?.name ?? "",
141
+ } satisfies ConfirmationValues;
142
+ };
143
+
144
+ /**
145
+ * mergeRefusal answers why a merge cannot be made, from what the studio holds, or null for one
146
+ * that can be sent.
147
+ *
148
+ * It is every refusal the verb gives without a request, in the order a surface reads them: a
149
+ * draft that shows, an itinerary that is not the one open, a reader who holds no write grant on
150
+ * it (`forbidden`), a segment the open chain does not hold ({@link notHeldFailure}), a segment
151
+ * with nothing after it, then
152
+ * the reasons the chain model greys a merge out for (`buildSegmentChainMerges`: two engines,
153
+ * a group boundary, the router's via ceiling, a collaborator's lock on either segment), with a
154
+ * segment's geometry edit the reader has armed ({@link guardNoArmedSegmentEdit}) ahead of the
155
+ * collaborator's lock, and last a context with no persistence seam, which has nowhere to send the
156
+ * merge.
157
+ *
158
+ * It reads state and writes nothing, so it is both the verb's precondition, which the bus runs
159
+ * before the reader is asked, and the first thing the handler does once they have answered: a
160
+ * collaborator may take a segment, or the chain may change, while the prompt is on screen.
161
+ */
162
+ const mergeRefusal = (ctx: StudioToolContext, input: MergeSegmentInput): ToolFailure | null => {
163
+ const drafting = guardNoActiveDraft(ctx, "merge segment");
164
+ if (drafting) {
165
+ return drafting;
166
+ }
167
+
168
+ const chain = activeChain(ctx, input.itineraryId);
169
+ if (!chain) {
170
+ return notOpenFailure("merge segment", input.itineraryId);
171
+ }
172
+
173
+ // A reader who holds no write grant on the open itinerary is refused before any request.
174
+ const ungranted = refuseUngrantedItinerary(ctx, input.itineraryId);
175
+ if (ungranted) {
176
+ return ungranted;
177
+ }
178
+
179
+ const index = chain.findIndex((segment) => segment.id === input.segmentId);
180
+ const head = chain[index];
181
+ if (!head) {
182
+ return notHeldFailure("merge segment", input.segmentId);
183
+ }
184
+
185
+ const tail = chain[index + 1];
186
+ if (!tail) {
187
+ return {
188
+ code: "invalid-input",
189
+ error: `merge segment: segment ${input.segmentId} has no following segment to merge with`,
190
+ ok: false,
191
+ };
192
+ }
193
+
194
+ // A merge re-derives ONE geometry from both halves, so a routed segment and a
195
+ // freehand one have no single engine to re-derive under.
196
+ if (head.mode !== tail.mode) {
197
+ return {
198
+ code: "invalid-input",
199
+ error: "merge segment: the two segments use different engines",
200
+ ok: false,
201
+ };
202
+ }
203
+
204
+ // A group is a display run over a contiguous stretch of the chain, so fusing
205
+ // across its edge would silently move ground in or out of it. Comparing the ids
206
+ // covers the one-grouped-one-not case too, since an ungrouped segment carries a
207
+ // null group rather than no group.
208
+ if (head.group_id !== tail.group_id) {
209
+ return {
210
+ code: "invalid-input",
211
+ error: "merge segment: the two segments belong to different groups",
212
+ ok: false,
213
+ };
214
+ }
215
+
216
+ // The fused route would ask the router for more waypoints than it accepts.
217
+ // Refusing here is a sentence the caller reads instead of a round-trip 400.
218
+ if (exceedsMergeViaCeiling(head, tail)) {
219
+ return {
220
+ code: "invalid-input",
221
+ error: `merge segment: the two segments carry more than ${DIRECTIONS_VIA_MAX} combined vias`,
222
+ ok: false,
223
+ };
224
+ }
225
+
226
+ const editing = guardNoArmedSegmentEdit(ctx);
227
+ if (editing) {
228
+ return editing;
229
+ }
230
+
231
+ // Both segments are lock-guarded, not just the named one: the merge consumes
232
+ // the successor's geometry too, so a peer editing EITHER of them blocks it.
233
+ const blocked =
234
+ guardCollabLock(ctx, "segment", input.segmentId) ?? guardCollabLock(ctx, "segment", tail.id);
235
+ if (blocked) {
236
+ return blocked;
237
+ }
238
+
239
+ return ctx.api ? null : missingPersistenceFailure();
240
+ };
241
+
242
+ /**
243
+ * mergeSegment folds one segment into the one that FOLLOWS it, leaving a single segment where there
244
+ * were two. The direction is fixed and takes no parameter: on an ordered chain, merging i with i-1
245
+ * is the same operation as merging i-1 with its next, so a direction field would be a second way to
246
+ * express one request. The gutter between two rows dispatches it on the upper one.
247
+ *
248
+ * Both segments are lock-guarded, not just the named one: the merge consumes the successor's
249
+ * geometry too, so a peer editing EITHER of them must block it. The API re-routes the union of both
250
+ * segments' vias in a single call and renumbers the chain, so the answer is the whole refreshed
251
+ * itinerary.
252
+ *
253
+ * It is destructive (one of the two segments stops existing and its name goes with it), so it
254
+ * confirms in the destructive tone. Persisted-itinerary-only (see {@link applyChainMutation}): an
255
+ * open draft refuses as `draft-open`. It persists, so it needs the api seam. ctx is the first
256
+ * positional parameter.
257
+ *
258
+ * Every refusal it can give without a request ({@link mergeRefusal}) is its `precondition`, so the
259
+ * reader is never asked to approve a merge that the studio can already tell it refuses, and each is
260
+ * read again once they have answered. The API can still turn an approved merge down: a freehand
261
+ * pair whose joined line holds more drawn vertices than a segment stores is refused there, on a
262
+ * count the studio cannot take (see `SegmentMergeRefusal`). That refusal answers `invalid-input`
263
+ * with the API's own sentence, in the viewer's language, as its `detail`.
264
+ */
265
+ export const mergeSegment: StudioToolDefinition<"studio.itinerary.segment.merge"> = {
266
+ confirmation: {
267
+ confirmLabel: "confirm.merge",
268
+ descriptionLabel: "confirm.mergeSegments.body",
269
+ titleLabel: "confirm.mergeSegments.title",
270
+ tone: "destructive",
271
+ },
272
+ confirmationValues: mergeSegmentNames,
273
+ handler: async (ctx, input) => {
274
+ // Read again after the prompt: what the precondition read may have changed meanwhile.
275
+ const refused = mergeRefusal(ctx, input);
276
+ if (refused) {
277
+ return refused;
278
+ }
279
+
280
+ return await applyChainMutation(
281
+ ctx,
282
+ input.itineraryId,
283
+ (api) => api.persistence.mergeSegment(input.itineraryId, input.segmentId),
284
+ () => `Merged segment ${input.segmentId} into the one that follows it.`,
285
+ );
286
+ },
287
+ precondition: mergeRefusal,
288
+ requiresConfirmation: true,
289
+ };
290
+
291
+ /** SplitSegmentInput is the parsed input of `studio.itinerary.segment.split`. */
292
+ type SplitSegmentInput = z.infer<
293
+ (typeof studioToolContracts)["studio.itinerary.segment.split"]["input"]
294
+ >;
295
+
296
+ /**
297
+ * splitSegmentValues resolves the name of the segment being cut and how far along
298
+ * it the cut lands, in the viewer's units, so the confirm body states the actual
299
+ * distance rather than a bare percentage. An unresolvable segment yields empty
300
+ * strings and the prompt renders its placeholders verbatim.
301
+ */
302
+ const splitSegmentValues = (ctx: StudioToolContext, input: SplitSegmentInput) => {
303
+ const segment = (activeChain(ctx, input.itineraryId) ?? []).find(
304
+ (entry) => entry.id === input.segmentId,
305
+ );
306
+ const meters = segment ? segmentLengthMeters(segment.geojson) * input.fraction : null;
307
+
308
+ return {
309
+ distance: formatDistance(meters, unitFormat(ctx)),
310
+ name: segment?.name ?? "",
311
+ } satisfies ConfirmationValues;
312
+ };
313
+
314
+ /**
315
+ * SplitSubject is what a split that can be sent reads from the open chain: the chain, and the
316
+ * segment of it the cut is made in.
317
+ */
318
+ interface SplitSubject {
319
+ readonly chain: readonly ItinerarySegment[];
320
+ readonly segment: ItinerarySegment;
321
+ }
322
+
323
+ /**
324
+ * readSplit answers what a split is made of, from what the studio holds, or why it cannot be made.
325
+ *
326
+ * A refusal is every one the verb gives without a request: a draft that shows, an itinerary that is
327
+ * not the one open, a reader who holds no write grant on it (`forbidden`), a segment the open
328
+ * chain does not hold, a segment's geometry edit the reader
329
+ * has armed ({@link guardNoArmedSegmentEdit}), a collaborator's lock on the segment, the end
330
+ * floor, since the API refuses a piece shorter than {@link SPLIT_MIN_END_DISTANCE_METERS}, and
331
+ * last a context with no
332
+ * persistence seam, which has nowhere to send the cut. The first two after the draft are the
333
+ * merge's, with its code: `not-found` for the itinerary and for the segment.
334
+ *
335
+ * It reads state and writes nothing, so the verb reads it twice: as its precondition
336
+ * ({@link splitRefusal}), which the bus runs before the reader is asked, and as the first thing the
337
+ * handler does once they have answered. A collaborator may take the segment, or the segment may
338
+ * leave the chain, while the prompt is on screen.
339
+ */
340
+ const readSplit = (
341
+ ctx: StudioToolContext,
342
+ input: SplitSegmentInput,
343
+ ): SplitSubject | ToolFailure => {
344
+ const drafting = guardNoActiveDraft(ctx, "split segment");
345
+ if (drafting) {
346
+ return drafting;
347
+ }
348
+
349
+ const chain = activeChain(ctx, input.itineraryId);
350
+ if (!chain) {
351
+ return notOpenFailure("split segment", input.itineraryId);
352
+ }
353
+
354
+ // A reader who holds no write grant on the open itinerary is refused before any request.
355
+ const ungranted = refuseUngrantedItinerary(ctx, input.itineraryId);
356
+ if (ungranted) {
357
+ return ungranted;
358
+ }
359
+
360
+ const segment = chain.find((entry) => entry.id === input.segmentId);
361
+ if (!segment) {
362
+ return notHeldFailure("split segment", input.segmentId);
363
+ }
364
+
365
+ const blocked = guardNoArmedSegmentEdit(ctx) ?? guardCollabLock(ctx, "segment", input.segmentId);
366
+ if (blocked) {
367
+ return blocked;
368
+ }
369
+
370
+ // The end floor a pick is held to holds for a fraction given outright too.
371
+ if (isSplitOnEnd(segment.geojson, input.fraction)) {
372
+ return {
373
+ code: "split-on-end",
374
+ error: `split segment: a cut at ${input.fraction} of segment ${input.segmentId} leaves less than ${SPLIT_MIN_END_DISTANCE_METERS}m of it on one side`,
375
+ ok: false,
376
+ };
377
+ }
378
+
379
+ return ctx.api ? { chain, segment } : missingPersistenceFailure();
380
+ };
381
+
382
+ /**
383
+ * splitRefusal answers why a split cannot be made, or null for one that can be sent: the refusal
384
+ * half of {@link readSplit}, in the shape a verb's `precondition` takes.
385
+ */
386
+ const splitRefusal = (ctx: StudioToolContext, input: SplitSegmentInput): ToolFailure | null => {
387
+ const read = readSplit(ctx, input);
388
+
389
+ return "segment" in read ? null : read;
390
+ };
391
+
392
+ /**
393
+ * splitSegment cuts one segment into two consecutive segments at a fraction of its length. The
394
+ * first half keeps the original identity; the second is created after it and the chain renumbers,
395
+ * so the answer is the whole refreshed itinerary. The API projects the fraction onto the stored
396
+ * geometry and makes the projected point the shared junction vertex of both halves, so the two stay
397
+ * exactly connected and no neighbour recompute fires. Both halves are renamed from the original, so
398
+ * the split never leaves two rows the user cannot tell apart.
399
+ *
400
+ * Nothing is lost (the same ground is still covered by two rows instead of one), so it confirms in
401
+ * the cautionary tone rather than the destructive one, even though re-merging is a separate
402
+ * deliberate act. Persisted-itinerary-only (see {@link applyChainMutation}): an open draft refuses
403
+ * as `draft-open`. It persists, so it needs the api seam. ctx is the first positional parameter.
404
+ *
405
+ * Every refusal it can give without a request ({@link readSplit}) is its `precondition`, so the
406
+ * reader is never asked to approve a cut that the studio can already tell it refuses, and each is
407
+ * read again once they have answered. The API can still turn an approved cut down.
408
+ */
409
+ export const splitSegment: StudioToolDefinition<"studio.itinerary.segment.split"> = {
410
+ confirmation: {
411
+ confirmLabel: "confirm.split",
412
+ descriptionLabel: "confirm.splitSegment.body",
413
+ titleLabel: "confirm.splitSegment.title",
414
+ tone: "cautionary",
415
+ },
416
+ confirmationValues: splitSegmentValues,
417
+ handler: async (ctx, input) => {
418
+ // Read again after the prompt: what the precondition read may have changed meanwhile.
419
+ const read = readSplit(ctx, input);
420
+ if (!("segment" in read)) {
421
+ return read;
422
+ }
423
+
424
+ const { chain, segment } = read;
425
+
426
+ // The API copies the original name onto both halves, which would leave two rows of one name.
427
+ // Naming a segment is a client concern here, as the `Segment #N` auto-name is, so the halves
428
+ // are named on this side and sent along, against the names the chain's other rows carry: a half
429
+ // cut again takes no name a sibling holds.
430
+ const names = splitSegmentNames(
431
+ segment.name,
432
+ chain.filter((entry) => entry.id !== segment.id).map((entry) => entry.name),
433
+ );
434
+
435
+ return await applyChainMutation(
436
+ ctx,
437
+ input.itineraryId,
438
+ (api) =>
439
+ api.persistence.splitSegment(input.itineraryId, input.segmentId, {
440
+ first_name: names[0],
441
+ fraction: input.fraction,
442
+ second_name: names[1],
443
+ }),
444
+ () =>
445
+ `Split segment ${input.segmentId} at ${Math.round(convertProportion(input.fraction, "ratio", "percent"))}% of its length.`,
446
+ );
447
+ },
448
+ precondition: splitRefusal,
449
+ requiresConfirmation: true,
450
+ };
451
+
452
+ /**
453
+ * splitPickBegin arms the map to pick where a segment is cut: it records which segment the next
454
+ * click is measured against, so the pointer becomes a cross and the click handler knows what line
455
+ * to project onto. It persists nothing: the split itself is {@link splitSegment}, which the pick
456
+ * resolves into.
457
+ *
458
+ * It obeys the one-gesture-at-a-time invariant every other begin verb obeys, and it has to: the
459
+ * pick mounts the same cursor lock, base-map block, and pointer tooltip an authoring edit does, and
460
+ * none of those three is reference-counted, so a pick armed over an open edit would paint a second
461
+ * tooltip and, on teardown, drop the edit's cursor lock. The map leaf cannot defend itself against
462
+ * that (it just captures clicks), so the refusal belongs here, exactly as it does for the segment,
463
+ * waypoint, and zone begins.
464
+ *
465
+ * It arms a gesture that resolves into {@link splitSegment}, so it carries that verb's contracts
466
+ * too rather than locking the cursor for a cut that would be refused on the click: with a draft
467
+ * open it refuses as `draft-open`, and for an itinerary that is not the one open or a segment the
468
+ * open chain does not hold as `not-found`. It refuses as `draft-open` as well behind an import or a suggest surface that shows with no draft
469
+ * staged, where the itinerary behind takes no begin. While a create's request is out it refuses as
470
+ * `edit-in-progress: create`, since the itinerary that create makes takes the editor as it lands.
471
+ *
472
+ * Hidden from the LLM manifest: picking a point on the map is a human gesture. The agent expresses
473
+ * the same intent directly as a fraction, which needs no pointer. Editing. ctx is the first
474
+ * positional parameter.
475
+ */
476
+ export const splitPickBegin: StudioToolDefinition<"studio.itinerary.segment.splitPickBegin"> = {
477
+ agentHidden: true,
478
+ handler: (ctx, input) => {
479
+ const drafting = guardNoActiveDraft(ctx, "begin split pick");
480
+ if (drafting) {
481
+ return drafting;
482
+ }
483
+
484
+ // A split writes the open itinerary, so one the reader may not edit refuses the pick.
485
+ const readOnly = refuseReadOnlyItinerary(ctx);
486
+ if (readOnly) {
487
+ return readOnly;
488
+ }
489
+
490
+ const behindSurface = guardSplitPickBehindSurface(ctx.ui.getState());
491
+ if (behindSurface) {
492
+ return behindSurface;
493
+ }
494
+
495
+ // A create whose request is out holds the editor: the itinerary it creates takes the
496
+ // editor as it lands, and a pick armed meanwhile would stand on an itinerary that leaves.
497
+ const state = ctx.ui.getState();
498
+ if (state.editorReservation !== null) {
499
+ return editInProgressError(state.editorReservation.kind);
500
+ }
501
+
502
+ const engine = selectActiveEditEngine(state);
503
+ if (engine) {
504
+ return editInProgressError(engine.kind);
505
+ }
506
+
507
+ // The pick is judged against the open chain, so a pick of another itinerary or of a
508
+ // segment the chain does not hold could only end in a refusal on its first click.
509
+ const chain = activeChain(ctx, input.itineraryId);
510
+ if (!chain) {
511
+ return notOpenFailure("begin split pick", input.itineraryId);
512
+ }
513
+
514
+ if (!chain.some((segment) => segment.id === input.segmentId)) {
515
+ return notHeldFailure("begin split pick", input.segmentId);
516
+ }
517
+
518
+ const blocked = guardCollabLock(ctx, "segment", input.segmentId);
519
+ if (blocked) {
520
+ return blocked;
521
+ }
522
+
523
+ ctx.ui.getState().setSegmentSplitPick({
524
+ itineraryId: input.itineraryId,
525
+ segmentId: input.segmentId,
526
+ });
527
+
528
+ return { ok: true, summary: `Picking a split point on segment ${input.segmentId}.` };
529
+ },
530
+ };
531
+
532
+ /**
533
+ * splitPickToleranceMeters converts the split pick's screen-pixel reach into the
534
+ * ground distance it covers where the click landed, `groundMetersPerPixel` at the
535
+ * map's zoom and the click's latitude, so "near enough to the line" means the same
536
+ * thing to the eye at every zoom. Unbounded when no map is mounted: without a
537
+ * viewport there is no scale to convert against, and a coordinate that arrived
538
+ * without a pointer (an agent call, a render-free test) was never an aim that could
539
+ * miss.
540
+ */
541
+ const splitPickToleranceMeters = (ctx: StudioToolContext, latitude: number): number => {
542
+ const viewport = ctx.map?.getViewport();
543
+
544
+ return viewport
545
+ ? SPLIT_PICK_TOLERANCE_PX * groundMetersPerPixel(viewport.zoom, latitude)
546
+ : Number.POSITIVE_INFINITY;
547
+ };
548
+
549
+ /**
550
+ * splitPickSet resolves a picked map coordinate into the split it stands for: it judges the click
551
+ * against the armed segment with {@link splitPickVerdict}, disarms the pick, and chains into
552
+ * {@link splitSegment}, which raises the confirm prompt and performs the write at the fraction the
553
+ * click projects to. The click therefore never has to land exactly on the line, and no coordinate
554
+ * ever reaches the API.
555
+ *
556
+ * A pick the verdict refuses is answered with the verdict's own code and leaves the pick ARMED, so
557
+ * the user simply clicks again instead of re-opening the menu:
558
+ * - `split-too-far`, a click further from the line than {@link SPLIT_PICK_TOLERANCE_PX} allows.
559
+ * The tolerance is a SCREEN distance converted to meters at the click's own latitude and the
560
+ * map's zoom, so the reach stays constant to the eye as the user zooms. With no map mounted (the
561
+ * agent path, a render-free test) there is no scale to convert against and no reach is judged: an
562
+ * explicitly-supplied coordinate was never a pointing gesture.
563
+ * - `split-on-end`, a cut at an endpoint or within {@link SPLIT_MIN_END_DISTANCE_METERS} of one,
564
+ * which cuts nothing or a piece the API refuses.
565
+ * - `invalid-input`, a segment with no line to split.
566
+ *
567
+ * Hidden from the LLM manifest for the same reason its begin is: it is the second half of a pointer
568
+ * gesture. ctx is the first positional parameter.
569
+ */
570
+ export const splitPickSet: StudioToolDefinition<"studio.itinerary.segment.splitPickSet"> = {
571
+ agentHidden: true,
572
+ handler: async (ctx, input) => {
573
+ const pick = ctx.ui.getState().segmentSplitPick;
574
+ if (!pick) {
575
+ return { code: "no-session", error: "set split point: no split pick is armed", ok: false };
576
+ }
577
+
578
+ const segment = (activeChain(ctx, pick.itineraryId) ?? []).find(
579
+ (entry) => entry.id === pick.segmentId,
580
+ );
581
+ if (!segment) {
582
+ ctx.ui.getState().setSegmentSplitPick(null);
583
+
584
+ return {
585
+ code: "not-found",
586
+ error: `set split point: segment ${pick.segmentId} is no longer in the open itinerary`,
587
+ ok: false,
588
+ };
589
+ }
590
+
591
+ const verdict = splitPickVerdict(
592
+ segment.geojson,
593
+ input.lngLat,
594
+ splitPickToleranceMeters(ctx, input.lngLat[1]),
595
+ );
596
+
597
+ // Every refusal returns above the disarm below, leaving the pick live so the next click just
598
+ // works. The end floor in particular is refused BEFORE chaining into the split, which is what
599
+ // raises the confirmation: the API enforces the same floor, but only after the user has
600
+ // confirmed and the write has gone out, and by then the pick has been disarmed, so recovering
601
+ // would mean reopening the row menu.
602
+ if (verdict.ok === false && verdict.code === "invalid-input") {
603
+ return {
604
+ code: "invalid-input",
605
+ error: `set split point: segment ${pick.segmentId} carries no line to split`,
606
+ ok: false,
607
+ };
608
+ }
609
+
610
+ if (verdict.ok === false && verdict.code === "split-too-far") {
611
+ return {
612
+ code: "split-too-far",
613
+ error: `set split point: the picked point is ${Math.round(verdict.projection.distanceMeters)}m from the segment`,
614
+ ok: false,
615
+ };
616
+ }
617
+
618
+ if (verdict.ok === false) {
619
+ return {
620
+ code: "split-on-end",
621
+ error: `set split point: the picked point is within ${SPLIT_MIN_END_DISTANCE_METERS}m of an end of the segment`,
622
+ ok: false,
623
+ };
624
+ }
625
+
626
+ const { fraction } = verdict;
627
+
628
+ if (!ctx.bus) {
629
+ return { code: "internal", error: "set split point: no tool bus available", ok: false };
630
+ }
631
+
632
+ // Disarm before chaining: the split raises a confirm prompt, and leaving the
633
+ // pick armed underneath it would let a second click land while the user reads
634
+ // the prompt.
635
+ ctx.ui.getState().setSegmentSplitPick(null);
636
+
637
+ return await ctx.bus.dispatch(ctx, "studio.itinerary.segment.split", {
638
+ fraction,
639
+ itineraryId: pick.itineraryId,
640
+ segmentId: pick.segmentId,
641
+ });
642
+ },
643
+ };
644
+
645
+ /**
646
+ * splitPickCancel disarms the split-point pick without splitting anything: the Escape path out of
647
+ * the gesture. A no-op when no pick is armed, so any teardown site can call it defensively.
648
+ *
649
+ * Hidden from the LLM manifest alongside its begin/set siblings. ctx is the first positional
650
+ * parameter.
651
+ */
652
+ export const splitPickCancel: StudioToolDefinition<"studio.itinerary.segment.splitPickCancel"> = {
653
+ agentHidden: true,
654
+ handler: (ctx) => {
655
+ ctx.ui.getState().setSegmentSplitPick(null);
656
+
657
+ return { ok: true, summary: "Cancelled the split-point pick." };
658
+ },
659
+ };
660
+
661
+ /**
662
+ * resolveInsertBefore turns the human-shaped anchor ("after this segment", or null for the head)
663
+ * into the wire's "before that segment". The two spellings describe the same gap, but the anchor
664
+ * the UI has in hand is the row ABOVE the gutter, while the endpoint names the row below it.
665
+ * Answers `tail` when the anchor names the tail of the chain: there is no row below it, and
666
+ * appending is the create path's job, not the insert path's. Answers `unknown` for an anchor the
667
+ * chain does not hold, which is no gap at all and never the tail. Answers `empty` for the head of a
668
+ * chain that holds no segment: there is no row to land before, so the segment is the chain's first.
669
+ */
670
+ const resolveInsertBefore = (
671
+ chain: readonly ItinerarySegment[],
672
+ afterSegmentId: string | null,
673
+ ): { beforeSegmentId: string } | "empty" | "tail" | "unknown" => {
674
+ if (afterSegmentId === null) {
675
+ const head = chain[0];
676
+
677
+ return head ? { beforeSegmentId: head.id } : "empty";
678
+ }
679
+
680
+ const index = chain.findIndex((segment) => segment.id === afterSegmentId);
681
+ if (index === -1) {
682
+ return "unknown";
683
+ }
684
+
685
+ const successor = chain[index + 1];
686
+
687
+ return successor ? { beforeSegmentId: successor.id } : "tail";
688
+ };
689
+
690
+ /** InsertSegmentInput is the parsed input of `studio.itinerary.segment.insert`. */
691
+ type InsertSegmentInput = z.infer<
692
+ (typeof studioToolContracts)["studio.itinerary.segment.insert"]["input"]
693
+ >;
694
+
695
+ /**
696
+ * readInsert answers where an insert lands in the open chain, from what the studio holds, or why it
697
+ * cannot be made.
698
+ *
699
+ * A refusal is every one the verb gives without a request, in the order a merge reads its own: a
700
+ * draft that shows, a freehand line asked by the agent, an itinerary that is not the one open, a
701
+ * reader who holds no write grant on it (`forbidden`), an anchor the chain does not hold or that
702
+ * has no row after it, then a
703
+ * segment's geometry edit the reader has armed ({@link guardNoArmedSegmentEdit}) and a
704
+ * collaborator's lock on either side of the gap. Both neighbours are read: the API re-seats the
705
+ * anchor's tail and the successor's head onto the new segment.
706
+ */
707
+ const readInsert = (
708
+ ctx: StudioToolContext,
709
+ input: InsertSegmentInput,
710
+ ):
711
+ | {
712
+ readonly anchor: { readonly beforeSegmentId: string } | "empty";
713
+ readonly chain: readonly ItinerarySegment[];
714
+ }
715
+ | ToolFailure => {
716
+ const drafting = guardNoActiveDraft(ctx, "insert segment");
717
+ if (drafting) {
718
+ return drafting;
719
+ }
720
+
721
+ // Refuse a freehand insert on the agent path, mirroring the append verb: the
722
+ // user draws linestrings on the map, the agent proposes routed geometry only.
723
+ if (input.mode === "linestring" && ctx.origin === "agent") {
724
+ return {
725
+ code: "invalid-input",
726
+ error:
727
+ "freehand (linestring) segments are drawn by the user in the studio, not created by the agent; propose a directions segment through routed vias instead",
728
+ ok: false,
729
+ };
730
+ }
731
+
732
+ const chain = activeChain(ctx, input.itineraryId);
733
+ if (!chain) {
734
+ return notOpenFailure("insert segment", input.itineraryId);
735
+ }
736
+
737
+ // A reader who holds no write grant on the open itinerary is refused before any request.
738
+ const ungranted = refuseUngrantedItinerary(ctx, input.itineraryId);
739
+ if (ungranted) {
740
+ return ungranted;
741
+ }
742
+
743
+ const anchor = resolveInsertBefore(chain, input.afterSegmentId);
744
+ if (anchor === "unknown") {
745
+ return notHeldFailure("insert segment", input.afterSegmentId ?? "");
746
+ }
747
+
748
+ if (anchor === "tail") {
749
+ return {
750
+ code: "invalid-input",
751
+ error:
752
+ "insert segment: no segment follows the given anchor, so there is no gap to insert into; append with studio.itinerary.segment.create instead",
753
+ ok: false,
754
+ };
755
+ }
756
+
757
+ const editing = guardNoArmedSegmentEdit(ctx);
758
+ if (editing) {
759
+ return editing;
760
+ }
761
+
762
+ const blocked =
763
+ (input.afterSegmentId === null
764
+ ? null
765
+ : guardCollabLock(ctx, "segment", input.afterSegmentId)) ??
766
+ (anchor === "empty" ? null : guardCollabLock(ctx, "segment", anchor.beforeSegmentId));
767
+ if (blocked) {
768
+ return blocked;
769
+ }
770
+
771
+ return { anchor, chain };
772
+ };
773
+
774
+ /**
775
+ * insertRefusal answers why an insert cannot be made, or null for one that can be sent: the
776
+ * refusal half of {@link readInsert}, in the shape a verb's `precondition` takes.
777
+ */
778
+ const insertRefusal = (ctx: StudioToolContext, input: InsertSegmentInput): ToolFailure | null => {
779
+ const read = readInsert(ctx, input);
780
+
781
+ return "chain" in read ? null : read;
782
+ };
783
+
784
+ /**
785
+ * insertSegment places a new segment INSIDE the chain rather than at its tail, and renumbers
786
+ * everything after it: a create that names the segment it lands before. The API recomputes both
787
+ * adjoining boundaries so the chain stays geometrically continuous, so the write reads the
788
+ * itinerary again rather than mirroring the one created segment it answers.
789
+ *
790
+ * The freehand `linestring` branch is a HUMAN path, exactly as it is on the append verb: the user
791
+ * draws the line on the map. The agent has no drawing surface, so an agent-origin dispatch is
792
+ * refused before any write and `directions` is its only insert.
793
+ *
794
+ * Inserting after the LAST segment is refused: that gap is an append, which the create verb owns.
795
+ * Keeping the two apart leaves exactly one way to express each. Over an itinerary that holds no
796
+ * segment a null anchor names no gap either, and that insert appends: the segment is created as the
797
+ * chain's first, through the create path the contract names as the append. It re-seats both
798
+ * neighbours, so it refuses as `edit-in-progress`
799
+ * while a segment's geometry edit is armed and as `collab-locked` while a collaborator holds either
800
+ * neighbour, as a merge does. Persisted-itinerary-only (see {@link applyChainMutation}): an open
801
+ * draft refuses as `draft-open`. It persists, so it needs the api seam. ctx is the first positional
802
+ * parameter.
803
+ *
804
+ * Every refusal it can give without a request ({@link readInsert}) is its `precondition`, and the
805
+ * handler reads them again before it writes.
806
+ */
807
+ export const insertSegment: StudioToolDefinition<"studio.itinerary.segment.insert"> = {
808
+ handler: async (ctx, input) => {
809
+ const read = readInsert(ctx, input);
810
+ if (!("chain" in read)) {
811
+ return read;
812
+ }
813
+
814
+ const { anchor, chain } = read;
815
+
816
+ // A fresh segment gets a vivid colour distinct from the one it now follows, the
817
+ // same courtesy the append path extends: an omitted colour renders as the
818
+ // uniform activity grey, which makes a chain unreadable on the map.
819
+ const previous = input.afterSegmentId
820
+ ? (chain.find((segment) => segment.id === input.afterSegmentId)?.color ?? null)
821
+ : null;
822
+ const drawn = {
823
+ color: pickLivelyColor(previous),
824
+ geojson: buildSegmentGeometry(
825
+ input.mode,
826
+ input.vias.map((via) => [...via]),
827
+ ),
828
+ mode: input.mode,
829
+ name: input.name,
830
+ };
831
+
832
+ // The create answers the one segment it made and not the chain, so it goes through the write
833
+ // that reads the itinerary again: ahead of the anchor's segment, the chain renumbers behind
834
+ // it and both adjoining boundaries move server-side, which only the read shows. With no row
835
+ // to land before, the segment is the chain's first and is appended.
836
+ const inserting = anchor !== "empty";
837
+ const result = await writeThrough(ctx, {
838
+ itineraryId: input.itineraryId,
839
+ optimistic: () => {},
840
+ persist: (api) =>
841
+ api.persistence.createSegment(
842
+ input.itineraryId,
843
+ inserting ? { ...drawn, before_segment_id: anchor.beforeSegmentId } : drawn,
844
+ ),
845
+ // An insert re-shapes the chain, so its tiles are busted on a settled frame, as every chain
846
+ // reshape's are ({@link applyChainMutation}); an append's are busted with the write, as a
847
+ // create's are.
848
+ skipTileRefresh: inserting,
849
+ summary: () => `Inserted segment “${input.name}”.`,
850
+ });
851
+
852
+ if (inserting && result.ok) {
853
+ ctx.map?.refreshItineraryTilesWhenSettled();
854
+ }
855
+
856
+ return result;
857
+ },
858
+ precondition: insertRefusal,
859
+ };
860
+
861
+ /**
862
+ * insertBegin opens a geometry draw for a segment that will land INSIDE the chain. It is the
863
+ * gutter's Plus: it resolves everything the draw needs from the segments the new one lands between
864
+ * (the boundary it grows out of, the next default `Segment #N` label, and a colour distinct from
865
+ * the segment it follows), then arms the ordinary segment edit through the same editBegin every
866
+ * other draw goes through. The insert anchor rides along on the session, so the commit writes an
867
+ * insert rather than an append.
868
+ *
869
+ * EXACTLY ONE end is pinned, and it is always the one the chain already fixes:
870
+ * - with a predecessor, the start is pinned to its tail and the END IS FREE. Two adjacent
871
+ * segments share their boundary, so pinning both ends would collapse the draw onto a single point
872
+ * with no length to draw and nothing to aim at. Leaving the end free is what makes an insert a
873
+ * real leg the user places, the mirror of drawing before the first segment;
874
+ * - with no predecessor (a head insert) the end is pinned to the successor's head and the START
875
+ * is free: the same gesture read from the other side;
876
+ * - past the tail neither neighbour exists on the far side, so the start is pinned and the end is
877
+ * free, which is the append it effectively is;
878
+ * - on a chain that holds no segment there is nothing to pin: both ends are free, nothing is
879
+ * seeded, and the draw is the itinerary's first segment.
880
+ *
881
+ * So an append opens here as well as an insert: anchored on the tail, or on null over an empty
882
+ * chain. Its commit goes through the create path, which is the contract's append, since no row
883
+ * follows the gap when the save is asked.
884
+ *
885
+ * The free end is what the following segment is then re-seated onto: the create recomputes
886
+ * the adjoining boundaries, snapping the successor's first point to wherever this draw ended and
887
+ * re-routing it. That is the point of the gesture rather than a side effect of it: the new segment
888
+ * takes over the head of the gap it was inserted into.
889
+ *
890
+ * While a staged draft shows, the one draw it opens is an append onto the draft's own chain
891
+ * ({@link beginDraftAppend}), and any other anchor refuses as `draft-open`: a draft's chain is
892
+ * reshaped by its own controls.
893
+ *
894
+ * Hidden from the LLM manifest: it opens an edit session, which the agent never drives; it proposes
895
+ * routed geometry through the insert verb instead. Editing. ctx is the first positional parameter.
896
+ */
897
+ export const insertBegin: StudioToolDefinition<"studio.itinerary.segment.insertBegin"> = {
898
+ agentHidden: true,
899
+ handler: async (ctx, input) => {
900
+ const draft = showingDraft(ctx.ui.getState());
901
+ if (draft) {
902
+ return await beginDraftAppend(ctx, draft, input);
903
+ }
904
+
905
+ if (!ctx.bus) {
906
+ return { code: "internal", error: "begin segment insert: no tool bus available", ok: false };
907
+ }
908
+
909
+ // A draft is what a null id names, and none shows.
910
+ if (input.itineraryId === null) {
911
+ return {
912
+ code: "not-found",
913
+ error:
914
+ "begin segment insert: itineraryId names no itinerary and no staged draft is showing; pass the id of the itinerary open in the editor",
915
+ ok: false,
916
+ };
917
+ }
918
+
919
+ const chain = activeChain(ctx, input.itineraryId);
920
+ if (!chain) {
921
+ return notOpenFailure("begin segment insert", input.itineraryId);
922
+ }
923
+
924
+ const anchorIndex = input.afterSegmentId
925
+ ? chain.findIndex((segment) => segment.id === input.afterSegmentId)
926
+ : -1;
927
+ if (input.afterSegmentId !== null && anchorIndex === -1) {
928
+ return notHeldFailure("begin segment insert", input.afterSegmentId);
929
+ }
930
+
931
+ // The predecessor the new segment grows out of, if any. A head insert
932
+ // (anchorIndex -1) has none and takes chain[0] as its successor instead.
933
+ const anchor = anchorIndex === -1 ? null : chain[anchorIndex];
934
+ const successor = anchor === null ? (chain[0] ?? null) : null;
935
+
936
+ // The one fixed boundary: the predecessor's tail when there is a predecessor, otherwise the
937
+ // successor's head. The opposite end stays free for the user to place, and the API re-seats the
938
+ // neighbour on that side onto it.
939
+ const pinnedStart = anchor ? segmentTail(anchor) : null;
940
+ const pinnedEnd = successor ? segmentHead(successor) : null;
941
+
942
+ // The seed is that single pin, which the engines expand into a degenerate line so
943
+ // the fixed handle is on the map from the first paint and the draw plainly starts
944
+ // (or ends) where the chain says it must.
945
+ const seedVias = [pinnedStart, pinnedEnd].filter((pin) => pin !== null);
946
+
947
+ return await ctx.bus.dispatch(ctx, "studio.itinerary.segment.editBegin", {
948
+ activitySlug: input.activitySlug,
949
+ color: pickLivelyColor(anchor?.color ?? null),
950
+ insertAnchor: { afterSegmentId: input.afterSegmentId },
951
+ mode: input.mode,
952
+ name: defaultSegmentName(chain.length),
953
+ pinnedEnd: pinnedEnd ?? undefined,
954
+ pinnedStart: pinnedStart ?? undefined,
955
+ seedVias,
956
+ segmentId: (ctx.ids ?? studioSeamAbsences.ids).next(),
957
+ });
958
+ },
959
+ };
960
+
961
+ /** InsertBeginInput is the parsed input of `studio.itinerary.segment.insertBegin`. */
962
+ type InsertBeginInput = z.infer<
963
+ (typeof studioToolContracts)["studio.itinerary.segment.insertBegin"]["input"]
964
+ >;
965
+
966
+ /**
967
+ * beginDraftAppend opens the draw of a segment appended to the chain of `draft`, the staged draft
968
+ * that shows, and answers what the begin answered.
969
+ *
970
+ * It derives from the draft's chain what {@link insertBegin} derives from an itinerary's: the
971
+ * next default `Segment #N` label, a colour distinct from the last segment's, that segment's end
972
+ * as the pinned start and the one seed, and an id from the ids seam. Over a draft that holds no
973
+ * segment nothing is pinned and nothing is seeded. The session it arms commits through the draft
974
+ * sink, which appends the drawn segment to the draft.
975
+ *
976
+ * The anchor names the draft's last segment, or is null over a draft that holds none. Any other
977
+ * is refused with `draft-open`: a gap inside a draft's chain is no place a draw lands, and a
978
+ * segment of the itinerary behind the draft is not the draft's.
979
+ */
980
+ const beginDraftAppend = async (
981
+ ctx: StudioToolContext,
982
+ draft: ItineraryDraft,
983
+ input: InsertBeginInput,
984
+ ): Promise<ToolResult<undefined>> => {
985
+ const chain = draftToView(draft).segments;
986
+ const tail = chain.at(-1) ?? null;
987
+ if (input.afterSegmentId !== (tail?.id ?? null)) {
988
+ return {
989
+ code: "draft-open",
990
+ error:
991
+ "begin segment insert: a staged draft is showing, and the one draw it takes is an append after its last segment",
992
+ ok: false,
993
+ };
994
+ }
995
+
996
+ if (!ctx.bus) {
997
+ return { code: "internal", error: "begin segment insert: no tool bus available", ok: false };
998
+ }
999
+
1000
+ const pinnedStart = tail ? segmentTail(tail) : null;
1001
+
1002
+ return await ctx.bus.dispatch(ctx, "studio.itinerary.segment.editBegin", {
1003
+ activitySlug: input.activitySlug,
1004
+ // A draft segment with no colour of its own holds the empty string.
1005
+ color: pickLivelyColor(tail?.color || null),
1006
+ insertAnchor: { afterSegmentId: input.afterSegmentId },
1007
+ mode: input.mode,
1008
+ name: defaultSegmentName(chain.length),
1009
+ pinnedStart: pinnedStart ?? undefined,
1010
+ seedVias: pinnedStart ? [pinnedStart] : [],
1011
+ segmentId: (ctx.ids ?? studioSeamAbsences.ids).next(),
1012
+ });
1013
+ };
1014
+
1015
+ /** SetSegmentModeInput is the parsed input of `studio.itinerary.segment.setMode`. */
1016
+ type SetSegmentModeInput = z.infer<
1017
+ (typeof studioToolContracts)["studio.itinerary.segment.setMode"]["input"]
1018
+ >;
1019
+
1020
+ /**
1021
+ * setModeRefusal answers why a segment's engine cannot be changed, from what the studio holds, or
1022
+ * null for a change that can be sent: a draft that shows, an itinerary that is not the one open,
1023
+ * a reader who holds no write grant on it (`forbidden`), a segment the open chain does not hold
1024
+ * ({@link notHeldFailure}), the engine the segment already
1025
+ * uses (`invalid-input`, so the reader is never asked to approve a change that changes nothing), a
1026
+ * segment's geometry edit the reader has armed ({@link guardNoArmedSegmentEdit}), then a
1027
+ * collaborator's lock on the segment.
1028
+ *
1029
+ * The refusals ahead of the armed edit are the merge's and the split's, with their codes: the
1030
+ * answer is mirrored into the open editor, so a change of another itinerary's segment would
1031
+ * replace what the reader sees.
1032
+ *
1033
+ * It reads state and writes nothing, so it is both the verb's precondition, which the bus runs
1034
+ * before the reader is asked, and the first thing the handler does once they have answered.
1035
+ */
1036
+ const setModeRefusal = (ctx: StudioToolContext, input: SetSegmentModeInput): ToolFailure | null => {
1037
+ const drafting = guardNoActiveDraft(ctx, "set segment mode");
1038
+ if (drafting) {
1039
+ return drafting;
1040
+ }
1041
+
1042
+ const chain = activeChain(ctx, input.itineraryId);
1043
+ if (!chain) {
1044
+ return notOpenFailure("set segment mode", input.itineraryId);
1045
+ }
1046
+
1047
+ // A reader who holds no write grant on the open itinerary is refused before any request.
1048
+ const ungranted = refuseUngrantedItinerary(ctx, input.itineraryId);
1049
+ if (ungranted) {
1050
+ return ungranted;
1051
+ }
1052
+
1053
+ const segment = chain.find((held) => held.id === input.segmentId);
1054
+ if (!segment) {
1055
+ return notHeldFailure("set segment mode", input.segmentId);
1056
+ }
1057
+
1058
+ if (segment.mode === input.mode) {
1059
+ return {
1060
+ code: "invalid-input",
1061
+ error: `set segment mode: segment ${input.segmentId} already uses the ${input.mode} engine`,
1062
+ ok: false,
1063
+ };
1064
+ }
1065
+
1066
+ return guardNoArmedSegmentEdit(ctx) ?? guardCollabLock(ctx, "segment", input.segmentId);
1067
+ };
1068
+
1069
+ /**
1070
+ * setSegmentMode switches which engine defines one segment's geometry and re-derives it. Routed →
1071
+ * freehand keeps the routed line as the drawn line, simplified and resampled as a line drawn on
1072
+ * creation is, and drops the turn-by-turn steps, which no longer describe anything visible. A
1073
+ * routed line of more positions than the 10,000 a segment write takes (`MAX_SEGMENT_POSITIONS`) is
1074
+ * simplified further until it fits, keeping its ends. The API does that fitting, so the studio
1075
+ * refuses no routed segment for its line's length and sends the mode alone. Freehand → routed
1076
+ * derives the vias to route through and can FAIL routing, which is exactly why this is its own
1077
+ * verb rather than a field on the metadata update. Both directions keep the segment's endpoints,
1078
+ * so neither neighbour changes; the answer is the whole itinerary, for the totals the API
1079
+ * recomputed.
1080
+ *
1081
+ * Nothing is deleted but the segment's shape may visibly change, so it confirms in the cautionary
1082
+ * tone. Persisted-itinerary-only (see {@link applyChainMutation}): an open draft refuses as
1083
+ * `draft-open`, since a draft segment's engine is chosen on the import staging rows, not re-derived
1084
+ * by the API. Persisting + editing, so it needs the api seam and the "editor" capability. ctx is
1085
+ * the first positional parameter.
1086
+ *
1087
+ * What it refuses from the studio's own state ({@link setModeRefusal}) is its `precondition`, so
1088
+ * the reader is never asked to approve a change the studio can already tell it refuses, and each is
1089
+ * read again once they have answered.
1090
+ */
1091
+ export const setSegmentMode: StudioToolDefinition<"studio.itinerary.segment.setMode"> = {
1092
+ confirmation: {
1093
+ confirmLabel: "confirm.setSegmentMode.confirm",
1094
+ descriptionLabel: "confirm.setSegmentMode.body",
1095
+ titleLabel: "confirm.setSegmentMode.title",
1096
+ tone: "cautionary",
1097
+ },
1098
+ handler: async (ctx, input) => {
1099
+ // Read again after the prompt: what the precondition read may have changed meanwhile.
1100
+ const refused = setModeRefusal(ctx, input);
1101
+ if (refused) {
1102
+ return refused;
1103
+ }
1104
+
1105
+ return await applyChainMutation(
1106
+ ctx,
1107
+ input.itineraryId,
1108
+ (api) =>
1109
+ api.persistence.convertSegment(input.itineraryId, input.segmentId, {
1110
+ mode: input.mode,
1111
+ }),
1112
+ () => `Set segment ${input.segmentId} to the ${input.mode} engine.`,
1113
+ );
1114
+ },
1115
+ precondition: setModeRefusal,
1116
+ requiresConfirmation: true,
1117
+ };
1118
+
1119
+ /**
1120
+ * segmentTail is the last coordinate of a segment's line: the point a following segment's start is
1121
+ * pinned to so the chain stays continuous. Null when the segment carries no line to read a tail
1122
+ * from.
1123
+ *
1124
+ * Clamped through {@link clampSeedPoint} because the coordinate is handed to the engines BOTH as a
1125
+ * pin and as a seed via: the freehand guard compares the two exactly, and the engine clamps the
1126
+ * pin, so an unclamped seed via would not match the clamped pin and the draw would reject every
1127
+ * update.
1128
+ */
1129
+ const segmentTail = (segment: ItinerarySegment): [number, number] | null => {
1130
+ const tail = extractLines(segment.geojson).at(-1)?.coordinates.at(-1);
1131
+
1132
+ return tail ? clampSeedPoint(tail) : null;
1133
+ };
1134
+
1135
+ /**
1136
+ * segmentHead is the first coordinate of a segment's line: the point a preceding segment's end is
1137
+ * pinned to, the mirror of {@link segmentTail}. Null when the segment carries no line to read a
1138
+ * head from. Clamped for the same reason.
1139
+ */
1140
+ const segmentHead = (segment: ItinerarySegment): [number, number] | null => {
1141
+ const head = extractLines(segment.geojson).at(0)?.coordinates.at(0);
1142
+
1143
+ return head ? clampSeedPoint(head) : null;
1144
+ };