@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,1186 @@
1
+ import type { Geometry, LineString, Position } from "geojson";
2
+
3
+ import { DIRECTIONS_VIA_MAX, extractLines, segmentLineCoordinates } from "@mountaya/elements/geo";
4
+
5
+ import type { StudioToolInputs, StudioToolOutputs } from "../../bus/contracts/studioTools.js";
6
+ import { failureFromThrown } from "../../bus/rules/handlerErrors.js";
7
+ import type { ToolFailure, ToolResult } from "../../bus/rules/types.js";
8
+ import { selectSuggestionSession } from "../../chrome/rules/agentSelectors.js";
9
+ import type { UiState } from "../../chrome/stores/uiStore.js";
10
+ import { requireData } from "../../data/handlers/graphql.js";
11
+ import { teardownActiveEditSession } from "../../edit/handlers/editLock.js";
12
+ import {
13
+ activityForId,
14
+ defaultSpeedForActivity,
15
+ seedFromCoordinates,
16
+ } from "../../segments/rules/engine.js";
17
+ import { simplifyToVias } from "../../segments/rules/viaSimplify.js";
18
+ import type { StudioToolContext, StudioToolDefinition } from "../../viewer/rules/context.js";
19
+ import { toDataActivity } from "../rules/activity.js";
20
+ import {
21
+ draftSessionIdentity,
22
+ holdDuringDraftCommit,
23
+ holdsDraftSession,
24
+ } from "../rules/draftSurface.js";
25
+ import { type ItineraryDraft, routedSegmentToDraft } from "../rules/import.js";
26
+ import {
27
+ graphqlRouteToLiveRoute,
28
+ type LiveSegmentRouteAnalysis,
29
+ type LiveSegmentRouteElevation,
30
+ routeLineOf,
31
+ } from "../rules/liveSegment.js";
32
+ import { lngLatOf } from "../rules/lngLat.js";
33
+ import {
34
+ buildSuggestionsInput,
35
+ mergeCandidates,
36
+ pointToPointShortfall,
37
+ SUGGESTION_TARGET_COUNT,
38
+ type SuggestionCandidate,
39
+ type SuggestionSession,
40
+ type SuggestionStatus,
41
+ selectedCandidate,
42
+ } from "../rules/suggest.js";
43
+ import { dropDraftSelection } from "./itinerarySelection.js";
44
+ import {
45
+ askToDropDraft,
46
+ leaveForSurface,
47
+ openItinerarySurface,
48
+ ownsDraftSurface,
49
+ } from "./surfaceOpen.js";
50
+
51
+ /**
52
+ * candidateMissing is the refusal a verb that names a candidate answers when there is none to
53
+ * act on: `no-session` with no suggest session open, `not-found` for a seed the batch does not
54
+ * hold, and null when the candidate exists.
55
+ *
56
+ * The store's writes for an unknown seed are no-ops, or record a selection that names nothing,
57
+ * so a verb that answered `ok` there told its caller a candidate had been previewed or kept.
58
+ *
59
+ * @param verb - The verb's own words for the refusal, as in `keep suggestion`.
60
+ */
61
+ const candidateMissing = (
62
+ ctx: StudioToolContext,
63
+ verb: string,
64
+ seed: number,
65
+ ): ToolFailure | null => {
66
+ const session = selectSuggestionSession(ctx.ui.getState());
67
+ if (!session) {
68
+ return { code: "no-session", error: `${verb}: no open suggest session`, ok: false };
69
+ }
70
+
71
+ return session.candidates.some((candidate) => candidate.seed === seed)
72
+ ? null
73
+ : { code: "not-found", error: `${verb}: seed ${seed} is not in the batch`, ok: false };
74
+ };
75
+
76
+ /**
77
+ * select sets which generated candidate the map preview draws, by its seed. It only writes the
78
+ * selection: the suggestion preview-sync hook reads the selected candidate and paints its route
79
+ * (plus the start/end pins) reactively through setItineraryPreview, so the handler never
80
+ * touches ctx.map. It is the click-to-preview a result row drives.
81
+ */
82
+ export const select: StudioToolDefinition<"studio.itinerary.suggest.select"> = {
83
+ handler: (ctx, input) => {
84
+ const missing = candidateMissing(ctx, "select suggestion", input.seed);
85
+ if (missing) {
86
+ return missing;
87
+ }
88
+
89
+ const ui = ctx.ui.getState();
90
+ ui.selectSuggestionCandidate(input.seed);
91
+
92
+ // An agent-origin select is the deliberate pick the delegated "choose for
93
+ // me" flow performs, recorded so startFrom's uninvited-staging gate can
94
+ // tell delegation from a run staging straight off a generate. A human
95
+ // select (a card hover, a panel row) records nothing: human picks stage
96
+ // through their own click chain.
97
+ if (ctx.origin === "agent") {
98
+ ui.setSuggestAgentSelected(true);
99
+ }
100
+
101
+ return { ok: true, summary: `Previewing candidate ${input.seed}.` };
102
+ },
103
+ };
104
+
105
+ /**
106
+ * toggleKeep flips the kept flag of one candidate (matched by seed) so a regenerate reproduces
107
+ * it. The store enforces the cap: a flip that would push the kept count past SUGGESTION_MAX_KEPT
108
+ * is a no-op, so a regenerate always leaves fresh slots. The handler therefore reads the session
109
+ * again after the toggle and reports whether the flag flipped: when the candidate stays unkept
110
+ * after a keep attempt the cap was hit, and the summary says so (still an ok result, since the
111
+ * no-op is the intended cap behavior, not a failure). The answer's `kept` is the flag once the
112
+ * call has run, and `capped` is true for the keep the cap refused.
113
+ */
114
+ export const toggleKeep: StudioToolDefinition<"studio.itinerary.suggest.toggleKeep"> = {
115
+ handler: (ctx, input) => {
116
+ const missing = candidateMissing(ctx, "keep suggestion", input.seed);
117
+ if (missing) {
118
+ return missing;
119
+ }
120
+
121
+ const before = selectSuggestionSession(ctx.ui.getState())?.candidates.find(
122
+ (candidate) => candidate.seed === input.seed,
123
+ );
124
+ ctx.ui.getState().toggleSuggestionKeep(input.seed);
125
+ const after = selectSuggestionSession(ctx.ui.getState())?.candidates.find(
126
+ (candidate) => candidate.seed === input.seed,
127
+ );
128
+
129
+ // A keep attempt that left the flag unchanged means the store refused the
130
+ // flip at the keep cap: report it so the caller learns the pin did not take
131
+ // rather than reading a misleading "kept" summary.
132
+ if (before && after && before.kept === false && after.kept === false) {
133
+ return {
134
+ data: { capped: true, kept: false },
135
+ ok: true,
136
+ summary: `Candidate ${input.seed} not kept: the keep cap was reached.`,
137
+ };
138
+ }
139
+
140
+ const kept = after?.kept === true;
141
+
142
+ return {
143
+ data: { capped: false, kept },
144
+ ok: true,
145
+ summary: kept
146
+ ? `Keeping candidate ${input.seed} across regenerate.`
147
+ : `Stopped keeping candidate ${input.seed}.`,
148
+ };
149
+ },
150
+ };
151
+
152
+ /**
153
+ * SuggestRequest is one request of the open suggest session, and what tells it from the next.
154
+ */
155
+ interface SuggestRequest {
156
+ /** Whether this request is still the one the session waits on. */
157
+ isLatest: () => boolean;
158
+ /** The refusal a request answers once another thing replaced it. */
159
+ superseded: ToolFailure;
160
+ }
161
+
162
+ /**
163
+ * openSuggestRequest marks the open suggest session as waiting on a request and answers the
164
+ * means to tell, once it settles, whether the session still waits on it.
165
+ *
166
+ * The mark is the `generating` status itself: the store keeps the object it is handed until
167
+ * something else writes the status, so the object is the request's identity. Every parameter
168
+ * setter writes `idle`, a later request writes its own mark and a discard closes the session,
169
+ * so each of them replaces this one. A request that was replaced writes nothing and answers
170
+ * `no-session`, as the import preview's does.
171
+ *
172
+ * @param verb - The verb's own words for the refusal, as in `generate suggestions`.
173
+ */
174
+ const openSuggestRequest = (ctx: StudioToolContext, verb: string): SuggestRequest => {
175
+ const generating: SuggestionStatus = { kind: "generating" };
176
+
177
+ ctx.ui.getState().setSuggestionStatus(generating);
178
+
179
+ return {
180
+ isLatest: () => selectSuggestionSession(ctx.ui.getState())?.status === generating,
181
+ superseded: {
182
+ code: "no-session",
183
+ error: `${verb}: a changed parameter, a later request or a discard replaced this one before it answered`,
184
+ ok: false,
185
+ },
186
+ };
187
+ };
188
+
189
+ /**
190
+ * generatedAnswer is what `studio.itinerary.suggest.generate` answers for the batch it landed:
191
+ * the count in the summary a reader sees, and each candidate's figures in `data`, which only
192
+ * the model reads.
193
+ */
194
+ const generatedAnswer = (
195
+ candidates: readonly SuggestionCandidate[],
196
+ ): ToolResult<StudioToolOutputs["studio.itinerary.suggest.generate"]> => {
197
+ const count = candidates.length;
198
+
199
+ // The per-candidate metrics ride `data`, never the summary. The card
200
+ // already shows them to the user, and a summary that recites them is a
201
+ // summary a weaker model pastes into its reply, which lists the batch
202
+ // twice, once as the interactive card and once as prose beneath it. In
203
+ // `data` they stay available for a DELEGATED pick ("choose the flattest")
204
+ // without sitting in the sentence the model is composing from. Bounded:
205
+ // the batch is at most SUGGESTION_TARGET_COUNT plus the kept seeds it
206
+ // reproduces.
207
+ const candidateFacts = candidates.map((candidate) => ({
208
+ ascentMeters: Math.round(candidate.ascentMeters),
209
+ color: candidate.color,
210
+ distanceMeters: Math.round(candidate.distanceMeters),
211
+ durationSeconds: Math.round(candidate.durationSeconds),
212
+ seed: candidate.seed,
213
+ }));
214
+
215
+ return {
216
+ // `data` is the model's channel: the transcript never renders it. The
217
+ // directive rides here rather than in the summary because the summary is
218
+ // ALSO the activity row's label in the user's transcript, and a user who
219
+ // expands that row should not be reading instructions addressed to the
220
+ // model.
221
+ data: {
222
+ candidates: candidateFacts,
223
+ count,
224
+ next:
225
+ count === 0
226
+ ? "Nothing was generated: widen the distance or ascent, or move the start."
227
+ : "These routes are ALREADY displayed to the user as an interactive card in this conversation, with each route's distance, ascent and duration. Do NOT list, describe, or number them in your reply. END your turn now with ONE short sentence inviting the user to hover a route and pick one. Do NOT call select or startFrom unless the user explicitly asked you to choose for them.",
228
+ },
229
+ ok: true,
230
+ // User-facing: this is the activity row's label.
231
+ summary:
232
+ count === 0
233
+ ? "Generated 0 route suggestions."
234
+ : `Generated ${count} route suggestion${count === 1 ? "" : "s"}.`,
235
+ };
236
+ };
237
+
238
+ /**
239
+ * generate is the Data API call behind both the first generate and a regenerate: the
240
+ * include/exclude seed directives buildSuggestionsInput derives make the two identical.
241
+ *
242
+ * It refuses with a structured failure and no request when the Data API seam is absent
243
+ * (requireData), no session is open, a commit of the session's draft is out
244
+ * ({@link holdDuringDraftCommit}), the activity, the start or (for a point-to-point route) the
245
+ * end is not set, the distance is not positive, or a point-to-point target is shorter than the
246
+ * straight line between its ends ({@link pointToPointShortfall}). It resolves the activity the
247
+ * way the segment-edit propose does: it reads the catalog from the cache seam
248
+ * (`{ kind: "activities" }`), resolves the activity by id (activityForId), then maps its REST
249
+ * slug to the Data API enum (toDataActivity); a missing catalog or an unknown activity is a
250
+ * failure.
251
+ *
252
+ * It marks the session `generating`, builds the input, awaits the suggestions query, folds the
253
+ * returned routes into the session through mergeCandidates (keeping the kept flags and
254
+ * accumulating the seen-seed pool), and marks the session `ready`. The session is read again
255
+ * after the await so a concurrent input change is not overwritten by a stale snapshot, and a
256
+ * request that a parameter, a later generate or a discard replaced writes nothing
257
+ * ({@link openSuggestRequest}). On a throw, it marks the session `error` and returns a failure.
258
+ */
259
+ export const generate: StudioToolDefinition<"studio.itinerary.suggest.generate"> = {
260
+ handler: async (ctx, input) => {
261
+ const resolved = requireData(ctx);
262
+ if ("ok" in resolved) {
263
+ return resolved;
264
+ }
265
+
266
+ const session = selectSuggestionSession(ctx.ui.getState());
267
+ if (!session) {
268
+ return {
269
+ code: "no-session",
270
+ error: "generate suggestions: no open suggest session",
271
+ ok: false,
272
+ };
273
+ }
274
+
275
+ // The routes a generate folds in land in a session its commit closes as it lands.
276
+ const held = holdDuringDraftCommit(ctx, "suggest", "generate suggestions");
277
+ if (held) {
278
+ return held;
279
+ }
280
+
281
+ if (session.activityId === null) {
282
+ return {
283
+ code: "invalid-input",
284
+ error: "generate suggestions: no activity selected",
285
+ ok: false,
286
+ };
287
+ }
288
+
289
+ if (session.distanceMeters <= 0) {
290
+ return {
291
+ code: "invalid-input",
292
+ error: "generate suggestions: a positive target distance is required",
293
+ ok: false,
294
+ };
295
+ }
296
+
297
+ if (session.start === null) {
298
+ return {
299
+ code: "invalid-input",
300
+ error: "generate suggestions: a start point is required",
301
+ ok: false,
302
+ };
303
+ }
304
+
305
+ if (session.routeType === "point_to_point" && session.end === null) {
306
+ return {
307
+ code: "invalid-input",
308
+ error: "generate suggestions: an end point is required for a point-to-point route",
309
+ ok: false,
310
+ };
311
+ }
312
+
313
+ // A route is never shorter than the straight line between its ends, which the API refuses:
314
+ // said here, with the figure to reach, rather than as a round trip.
315
+ const straightLine = pointToPointShortfall(session);
316
+ if (straightLine !== null) {
317
+ return {
318
+ code: "invalid-input",
319
+ error: `generate suggestions: the target distance is shorter than the straight line from the start to the end (${straightLine} m)`,
320
+ ok: false,
321
+ };
322
+ }
323
+
324
+ // Resolve the activity from the catalog the useActivities cache holds (the
325
+ // session carries only the activity UUID), then map its REST slug to the
326
+ // Data-API enum the query expects: the same UUID → slug → toDataActivity path
327
+ // the segment-edit propose and the directions call take. A missing catalog or
328
+ // an unknown activity cannot route, so it is a failure rather than a request.
329
+ const categories = ctx.api?.cache.get({ kind: "activities" });
330
+ const activity = categories ? activityForId(categories, session.activityId) : null;
331
+ if (!activity) {
332
+ return {
333
+ code: "not-found",
334
+ error: "generate suggestions: the selected activity is not in the catalog",
335
+ ok: false,
336
+ };
337
+ }
338
+
339
+ const dataSlug = toDataActivity(activity.slug);
340
+
341
+ // The activity's default travel speed (km/h) backs the duration estimate when
342
+ // the user left the speed override unset: without it the server computes a
343
+ // near-zero duration and every candidate row reads "0 min". The session's own
344
+ // speed still wins when set.
345
+ const defaultSpeedKmh = defaultSpeedForActivity(activity.capabilities);
346
+
347
+ const request = openSuggestRequest(ctx, "generate suggestions");
348
+
349
+ try {
350
+ const query = buildSuggestionsInput(session, dataSlug, defaultSpeedKmh);
351
+ const result = await resolved.client.data.suggestions(query);
352
+
353
+ // The batch is for the inputs this request read. A parameter changed since, a later
354
+ // generation or a discard replaced it, and it lands nowhere: written, it would put
355
+ // routes for another start or distance over the cleared list and call the session ready.
356
+ if (!request.isLatest()) {
357
+ return request.superseded;
358
+ }
359
+
360
+ // Re-read the session AFTER the await so the fold runs against the live state (a kept
361
+ // flag toggled while the request was out), not the pre-request snapshot.
362
+ const after = selectSuggestionSession(ctx.ui.getState());
363
+ const merged = mergeCandidates(
364
+ after?.candidates ?? [],
365
+ after?.seenSeeds ?? [],
366
+ result.routes,
367
+ );
368
+
369
+ // The server returned fewer routes than asked for: there are no more
370
+ // distinct routes for the current constraints, so the form nudges the user
371
+ // to widen the distance/ascent and gates a futile regenerate. Measured on the
372
+ // raw response, not the merged list (merge reproduces kept seeds on top).
373
+ const exhausted = result.routes.length < SUGGESTION_TARGET_COUNT;
374
+
375
+ const ui = ctx.ui.getState();
376
+ ui.setSuggestionCandidates(merged.candidates, merged.seenSeeds, exhausted);
377
+ // Preview the first candidate so a fresh batch lands with a route already drawn
378
+ // on the map and its elevation profile shown: a DISPLAY selection, not a keep,
379
+ // so the pin checkbox stays unchecked. A zero-candidate batch previews nothing.
380
+ ui.selectSuggestionCandidate(merged.candidates[0]?.seed ?? null);
381
+ // A fresh batch stales any delegated pick: the run must deliberately
382
+ // re-select before it may stage, so a leftover delegation cannot grab a
383
+ // candidate the user never saw.
384
+ ui.setSuggestAgentSelected(false);
385
+ // Record what this batch is for, so a pick applies the run's own reading of
386
+ // the ask rather than the picking surface inferring one. Re-stated on every
387
+ // generate (including a regenerate) so a batch never inherits the previous
388
+ // one's purpose.
389
+ ui.setSuggestTargetSegment(input.targetSegmentId ?? null);
390
+ ui.setSuggestionStatus({ kind: "ready" });
391
+
392
+ return generatedAnswer(merged.candidates);
393
+ } catch (error) {
394
+ if (!request.isLatest()) {
395
+ return request.superseded;
396
+ }
397
+
398
+ const failure = failureFromThrown(error);
399
+
400
+ // The session message is what the form's banner renders, so it carries the API's own
401
+ // sentence when the throw brought one, and the technical line stays on the result.
402
+ ctx.ui
403
+ .getState()
404
+ .setSuggestionStatus({ kind: "error", message: failure.detail ?? failure.error });
405
+
406
+ return failure;
407
+ }
408
+ },
409
+ };
410
+
411
+ /**
412
+ * PickSubject is what `applyCandidate` applies once its checks pass: the session and the candidate
413
+ * the pick names, the open itinerary it changes, and the bus it changes it through.
414
+ */
415
+ interface PickSubject {
416
+ readonly bus: NonNullable<StudioToolContext["bus"]>;
417
+ readonly candidate: SuggestionCandidate;
418
+ readonly itinerary: NonNullable<UiState["activeItinerary"]>;
419
+ readonly session: SuggestionSession;
420
+ }
421
+
422
+ /**
423
+ * pickSubject runs the checks `applyCandidate` makes before it asks or sends anything, and
424
+ * answers what the pick applies, or the refusal: `no-session` with no suggest session,
425
+ * `not-found` for a seed the batch does not hold, `conflict` with no itinerary open, and
426
+ * `internal` with no bus to apply the route through.
427
+ */
428
+ const pickSubject = (ctx: StudioToolContext, seed: number): PickSubject | ToolFailure => {
429
+ const state = ctx.ui.getState();
430
+ const session = selectSuggestionSession(state);
431
+ if (!session) {
432
+ return { code: "no-session", error: "apply candidate: no open suggest session", ok: false };
433
+ }
434
+
435
+ const candidate = session.candidates.find((entry) => entry.seed === seed);
436
+ if (!candidate) {
437
+ return {
438
+ code: "not-found",
439
+ error: `apply candidate: seed ${seed} is not in the batch`,
440
+ ok: false,
441
+ };
442
+ }
443
+
444
+ const itinerary = state.activeItinerary;
445
+ if (!itinerary) {
446
+ return {
447
+ code: "conflict",
448
+ error: "apply candidate: no itinerary is open to apply the route to",
449
+ ok: false,
450
+ };
451
+ }
452
+
453
+ if (!ctx.bus) {
454
+ return {
455
+ code: "internal",
456
+ error: "apply candidate: no bus to apply the route through",
457
+ ok: false,
458
+ };
459
+ }
460
+
461
+ return { bus: ctx.bus, candidate, itinerary, session };
462
+ };
463
+
464
+ /**
465
+ * releaseStagedDraft asks before a pick drops the draft its session stages, and answers the
466
+ * refusal when the reader keeps it, or null when the pick may go on.
467
+ *
468
+ * A pick that lands closes the suggest session, and a draft the session stages goes with it: the
469
+ * name, the route and the choices the reader made in the draft editor. So it asks with the shared
470
+ * unsaved-changes prompt ({@link askToDropDraft}), the one `studio.itinerary.suggest.clearDraft`
471
+ * and the discard raise, and a decline answers `confirmation-denied` as theirs does, with nothing
472
+ * sent and the session as it stood. A commit of the draft sent while the prompt stood answers
473
+ * `conflict` once it is answered. A session that stages no draft drops nothing and is asked
474
+ * nothing.
475
+ */
476
+ const releaseStagedDraft = async (
477
+ ctx: StudioToolContext,
478
+ session: SuggestionSession,
479
+ input: StudioToolInputs["studio.itinerary.suggest.applyCandidate"],
480
+ ): Promise<ToolFailure | null> => {
481
+ if (session.draft === null) {
482
+ return null;
483
+ }
484
+
485
+ return askToDropDraft(
486
+ ctx,
487
+ "suggest",
488
+ "apply candidate",
489
+ "studio.itinerary.suggest.applyCandidate",
490
+ input,
491
+ "apply candidate declined: kept the staged draft and the batch",
492
+ );
493
+ };
494
+
495
+ /**
496
+ * applyCandidate applies a generated route to the OPEN itinerary, as a segment.
497
+ *
498
+ * This is the co-pilot conversation's pick, and it is deliberately NOT startFrom.
499
+ * startFrom serves the suggest PANEL, where a candidate becomes a whole new
500
+ * itinerary: it stages a draft with no persisted id and drives the panel to a
501
+ * naming/visibility/Create step. Reused for a chat pick, it would take a user editing
502
+ * their route, who asked the co-pilot for options and clicked one, onto that id-less
503
+ * draft: the segment and waypoint lists would vanish (they render nothing for a null
504
+ * source id), the header would relabel itself with the picked route's distance, and a
505
+ * "Create itinerary" footer would appear for an itinerary they never asked to create.
506
+ * A chat pick means something smaller and exact: change this route.
507
+ *
508
+ * Which change is the batch's own, recorded by the run at generate time and read
509
+ * back here. A targeted batch reshapes that segment through the ordinary propose
510
+ * path (a live, draggable edit the user saves), and an untargeted one appends a
511
+ * new routed segment. Absent a recorded target the current selection stands in,
512
+ * so a human who selected a segment and asked for options still gets a reshape.
513
+ *
514
+ * While the chain is out the session reports a request in flight, so the surface
515
+ * that offered the pick can show that row landing rather than looking unresponsive
516
+ * for the length of a routed create; a failure lowers it again and leaves the batch
517
+ * pickable. It is a display signal only: nothing here relies on it to serialize
518
+ * picks, which is the calling surface's own job.
519
+ *
520
+ * The suggest session closes on success: the candidates have served their purpose, and
521
+ * leaving them live would keep painting alternatives over the route the user just
522
+ * committed to. A suggest surface that was showing that session closes with it, so the slot
523
+ * names no surface with nothing behind it.
524
+ *
525
+ * A reshape arms an edit of the open itinerary, and the itinerary behind a showing import or
526
+ * suggest surface takes no edit. So a suggest surface that shows this session steps aside before
527
+ * the reshape, which is where a pick that lands leaves the slot, and a reshape that is refused
528
+ * puts it back over the batch, which stays pickable. An append arms nothing: the surface stays
529
+ * until the segment has landed. A refusal that lands once the session is discarded puts nothing
530
+ * back. One that lands on a session that stands and waits on another request, a parameter
531
+ * changed meanwhile, puts the surface back and leaves the marker, which is that request's.
532
+ * A reshape that lands on such a session leaves its surface aside for the edit it armed, and
533
+ * ends the session, since a session ends as its surface leaves the screen; a session whose
534
+ * surface shows again meanwhile stands.
535
+ *
536
+ * A session that stages a draft loses it to a pick that lands, so the pick asks first
537
+ * ({@link releaseStagedDraft}). On a yes, or with nobody to ask, an edit armed on that draft
538
+ * while the suggest surface shows ends before anything is sent. The yes is for the working copy
539
+ * the session staged as it was asked: a session that stages another while the question is open
540
+ * keeps it, and the pick answers `conflict` with nothing sent.
541
+ */
542
+ export const applyCandidate: StudioToolDefinition<"studio.itinerary.suggest.applyCandidate"> = {
543
+ handler: async (ctx, input) => {
544
+ // A pick drops the session's draft, which waits while that draft's commit is out.
545
+ const held = holdDuringDraftCommit(ctx, "suggest", "apply candidate");
546
+ if (held) {
547
+ return held;
548
+ }
549
+
550
+ const asked = pickSubject(ctx, input.seed);
551
+ if ("ok" in asked) {
552
+ return asked;
553
+ }
554
+
555
+ const questioned = draftSessionIdentity(ctx.ui.getState(), "suggest");
556
+ const declined = await releaseStagedDraft(ctx, asked.session, input);
557
+ if (declined) {
558
+ return declined;
559
+ }
560
+
561
+ // The question is a round trip: what the pick applies is read again once it is answered,
562
+ // the session it was asked on first.
563
+ if (selectSuggestionSession(ctx.ui.getState())?.sessionId !== asked.session.sessionId) {
564
+ return {
565
+ code: "no-session",
566
+ error: "apply candidate: the suggest session closed while the question was open",
567
+ ok: false,
568
+ };
569
+ }
570
+
571
+ // The answer is about the working copy the session staged as it was asked. Another one
572
+ // staged since is a draft nobody was asked about, so it stands and the pick is refused.
573
+ if (!holdsDraftSession(ctx.ui.getState(), "suggest", questioned)) {
574
+ return {
575
+ code: "conflict",
576
+ error:
577
+ "apply candidate: the suggest session staged another draft while the question was open",
578
+ ok: false,
579
+ };
580
+ }
581
+
582
+ const subject = pickSubject(ctx, input.seed);
583
+ if ("ok" in subject) {
584
+ return subject;
585
+ }
586
+
587
+ const { bus, candidate, itinerary, session } = subject;
588
+
589
+ // The reader's word, or a studio with nobody to ask, ends the edit of the draft the pick
590
+ // drops: left armed it would refuse the reshape, or stand on a draft that is closed.
591
+ if (session.draft !== null && ownsDraftSurface(ctx, "suggest")) {
592
+ teardownActiveEditSession(ctx);
593
+ }
594
+
595
+ // The candidate's route is a LineString (possibly collection-wrapped);
596
+ // simplify it to the 2–45 vias a directions segment accepts, exactly as the
597
+ // panel's startFrom does, so both paths hand the router the same shape.
598
+ // simplifyToVias speaks GeoJSON Positions (open-ended arrays); the segment
599
+ // tools speak fixed lng/lat pairs, so the ordinates are narrowed here, and a position that
600
+ // states no finite pair is dropped before the simplification rather than routed through 0, 0.
601
+ const pairs = segmentLineCoordinates(candidate.geometry).flatMap((position) => {
602
+ const pair = lngLatOf(position);
603
+
604
+ return pair === null ? [] : [pair];
605
+ });
606
+ const vias = simplifyToVias(pairs, DIRECTIONS_VIA_MAX).flatMap((position) => {
607
+ const pair = lngLatOf(position);
608
+
609
+ return pair === null ? [] : [pair];
610
+ });
611
+
612
+ // The batch's recorded target leads; the live selection stands in when it
613
+ // recorded none. Either way the id must still name a segment of the OPEN
614
+ // itinerary: a stale target (its segment deleted since the generate) falls
615
+ // back to appending rather than failing the pick.
616
+ const selection = ctx.ui.getState().selection;
617
+ const selected = selection?.kind === "segment" ? selection.id : null;
618
+ const wanted = session.targetSegmentId ?? selected;
619
+ const targetSegmentId =
620
+ wanted !== null && itinerary.segments.some((segment) => segment.id === wanted)
621
+ ? wanted
622
+ : null;
623
+
624
+ // Mark the session as having a request out BEFORE the chain starts, so the surface
625
+ // that offered the pick can show it landing: the chat card's picked row keys its
626
+ // loader on this and its other rows go inert, which is the only feedback between
627
+ // the tap and the settle (a routed create posts). `generating` is the session's
628
+ // "a request of mine is in flight" marker (the panel's commit raises the same one
629
+ // while it persists), not a claim that candidates are being produced.
630
+ const request = openSuggestRequest(ctx, "apply candidate");
631
+
632
+ // The session's own surface steps aside for a reshape, so the begin it dispatches is not
633
+ // one behind a showing surface.
634
+ const steppedAside = targetSegmentId !== null && ownsDraftSurface(ctx, "suggest");
635
+ if (steppedAside) {
636
+ ctx.ui.getState().setOpenContent(null);
637
+ }
638
+
639
+ const applied = targetSegmentId
640
+ ? await bus.dispatch(ctx, "studio.itinerary.segment.editPropose", {
641
+ segmentId: targetSegmentId,
642
+ vias,
643
+ })
644
+ : await bus.dispatch(ctx, "studio.itinerary.segment.create", {
645
+ color: candidate.color,
646
+ itineraryId: itinerary.id,
647
+ mode: "directions",
648
+ name: input.segmentName,
649
+ vias,
650
+ });
651
+
652
+ if (!applied.ok) {
653
+ // The chain is a round trip, and the reader may have discarded the session or asked
654
+ // something else of it meanwhile.
655
+
656
+ // The surface comes back over the session the pick stepped it aside for, while that
657
+ // session stands and nothing took the slot. It is the pick that emptied the slot, so it
658
+ // is the pick's to fill whatever the session waits on by now: a parameter changed
659
+ // meanwhile leaves the session standing, and its surface would stay aside for good.
660
+ const stands = selectSuggestionSession(ctx.ui.getState())?.sessionId === session.sessionId;
661
+ if (steppedAside && stands && ctx.ui.getState().openContent === null) {
662
+ ctx.ui.getState().setOpenContent("suggest");
663
+ }
664
+
665
+ // The marker is this pick's to lower only while the session still waits on it.
666
+ if (!request.isLatest()) {
667
+ return applied;
668
+ }
669
+
670
+ // The batch is untouched and still pickable, so lower the marker: left raised,
671
+ // the card would stay inert forever on a pick that never landed and the user
672
+ // could neither retry it nor choose another candidate.
673
+ ctx.ui.getState().setSuggestionStatus({ kind: "ready" });
674
+
675
+ return applied;
676
+ }
677
+
678
+ // Done with the batch: stop painting the alternatives over the route the user
679
+ // just chose, and drop the preview the selection was driving. The session, its surface and
680
+ // the preview are the pick's to close only while the session still waits on it: one the
681
+ // reader discarded, opened again or changed a parameter of meanwhile is theirs, unless the
682
+ // pick stepped its surface aside and nothing showed it again.
683
+ if (request.isLatest()) {
684
+ const owned = ownsDraftSurface(ctx, "suggest");
685
+ if (owned) {
686
+ dropDraftSelection(ctx, session.draft);
687
+ }
688
+
689
+ ctx.map?.setItineraryPreview(null);
690
+ ctx.ui.getState().closeSuggest();
691
+ if (owned) {
692
+ ctx.ui.getState().setOpenContent(null);
693
+ }
694
+ } else if (
695
+ steppedAside &&
696
+ selectSuggestionSession(ctx.ui.getState())?.sessionId === session.sessionId &&
697
+ ctx.ui.getState().openContent !== "suggest"
698
+ ) {
699
+ // The surface stays aside for the edit the reshape armed, and a session ends as its surface
700
+ // leaves the screen, whatever it waits on: the request it waits on lands on nothing.
701
+ ctx.map?.setItineraryPreview(null);
702
+ ctx.ui.getState().closeSuggest();
703
+ }
704
+
705
+ return {
706
+ ok: true,
707
+ summary: targetSegmentId
708
+ ? "Reshaped the segment from the chosen route: adjust the points and save."
709
+ : `Added the chosen route as segment “${input.segmentName}”.`,
710
+ };
711
+ },
712
+ };
713
+
714
+ /**
715
+ * RoutedBase is the routed 3D base a started-from draft seeds on: the routed line
716
+ * + its metrics, plus the elevation summary and surface/way-type/slope analysis
717
+ * (each null when the route carried none) the draft's first segment shows its
718
+ * full profile from. The analysis/elevation ride in the persisted snake_case +
719
+ * REST shape the panel reads, so routedSegmentToDraft sets them straight onto the
720
+ * draft candidate.
721
+ */
722
+ interface RoutedBase {
723
+ analysis: LiveSegmentRouteAnalysis | null;
724
+ distanceMeters: number;
725
+ durationSeconds: number;
726
+ elevation: LiveSegmentRouteElevation | null;
727
+ routedGeometry: LineString;
728
+ }
729
+
730
+ /**
731
+ * routedBaseFor resolves the routed 3D base a started-from draft seeds on, from the selected
732
+ * candidate. The draft's first segment needs a 3D geometry it can show the profile from at once
733
+ * and route again from on edit, plus the elevation and the analysis the profile's
734
+ * characteristics and bars read.
735
+ *
736
+ * When the candidate's own geometry already carries elevation (a 3rd ordinate on its first
737
+ * vertex), that geometry IS the routed base, the candidate's distance and duration are the
738
+ * metrics, and the candidate's already-converted analysis and elevation ride through, with no
739
+ * server call. Otherwise the simplified vias are routed once through the SAME non-persisting
740
+ * directions seam the segment editor's directions mode uses (never the persisting
741
+ * createSegment), and the routed line, its metrics and the route's analysis and elevation
742
+ * (converted to the persisted shape through graphqlRouteToLiveRoute) come back from that. A
743
+ * no-route response is null, which the caller surfaces as a failure leaving the candidates
744
+ * intact.
745
+ */
746
+ const routedBaseFor = async (
747
+ ctx: StudioToolContext,
748
+ candidateGeometry: Geometry,
749
+ vias: Position[],
750
+ candidateDistanceMeters: number,
751
+ candidateDurationSeconds: number,
752
+ candidateAnalysis: LiveSegmentRouteAnalysis,
753
+ candidateElevation: LiveSegmentRouteElevation,
754
+ activitySlug: string,
755
+ ): Promise<RoutedBase | { failure: ToolFailure } | null> => {
756
+ // Every line the candidate holds, laid end to end. A candidate is one LineString on the
757
+ // wire, and that leaf is kept as it is, so the draft's routed line is the object the preview
758
+ // painted. Several lines (a MultiLineString, a collection of tracks) become one over all of
759
+ // their coordinates, as every reader of a segment's geometry walks them.
760
+ const candidateLine: LineString | null =
761
+ extractLines(candidateGeometry).length === 0 ? null : routeLineOf(candidateGeometry);
762
+
763
+ // A 3D candidate already carries the elevation + analysis the profile needs, so
764
+ // it is the routed base directly with the candidate's own metrics, and no routing
765
+ // round-trip.
766
+ const firstVertex = candidateLine?.coordinates[0];
767
+ if (candidateLine && firstVertex !== undefined && firstVertex[2] !== undefined) {
768
+ return {
769
+ analysis: candidateAnalysis,
770
+ distanceMeters: candidateDistanceMeters,
771
+ durationSeconds: candidateDurationSeconds,
772
+ elevation: candidateElevation,
773
+ routedGeometry: candidateLine,
774
+ };
775
+ }
776
+
777
+ // A 2D candidate must be routed once to obtain a 3D line + metrics + analysis.
778
+ // Use the non-persisting directions query (the same seam the directions-mode
779
+ // segment editor routes through), never createSegment, so nothing is persisted.
780
+ // A missing seam is the seam's own failure, never a route that could not be found.
781
+ const resolved = requireData(ctx);
782
+ if ("ok" in resolved) {
783
+ return { failure: resolved };
784
+ }
785
+
786
+ const result = await resolved.client.data.directions({
787
+ activity: toDataActivity(activitySlug),
788
+ waypoints: vias.map((via) => [...via]),
789
+ });
790
+ const route = result.routes[0];
791
+ if (!route) {
792
+ return null;
793
+ }
794
+
795
+ // The geometry scalar is a GeoJSON geometry and a routed result is a line, read as one by
796
+ // routeLineOf, as buildRouteFn reads it. The shared graphqlRouteToLiveRoute converts the
797
+ // route's analysis and elevation to the persisted snake_case and REST shape the draft
798
+ // candidate carries.
799
+ const routedGeometry = routeLineOf(route.geometry);
800
+ const live = graphqlRouteToLiveRoute({
801
+ analysis: route.analysis,
802
+ distance: route.distance,
803
+ duration: route.duration,
804
+ elevation: route.elevation,
805
+ geometry: routedGeometry,
806
+ });
807
+
808
+ return {
809
+ analysis: live.analysis ?? null,
810
+ distanceMeters: route.distance,
811
+ durationSeconds: route.duration,
812
+ elevation: live.elevation ?? null,
813
+ routedGeometry,
814
+ };
815
+ };
816
+
817
+ /**
818
+ * agentStagingAnswer is what `studio.itinerary.suggest.startFrom` answers a run before it
819
+ * stages anything: the truth when a draft is already staged, a refusal when the reader has not
820
+ * picked and did not delegate the pick, and null when the run may go on or the caller is a
821
+ * person. The truth over a staged draft answers `staged` false: this call staged nothing.
822
+ */
823
+ const agentStagingAnswer = (
824
+ ctx: StudioToolContext,
825
+ session: SuggestionSession,
826
+ ): ToolResult<StudioToolOutputs["studio.itinerary.suggest.startFrom"]> | null => {
827
+ // A draft is already staged: the user picked from the conversation's card
828
+ // (the app stages that pick client-side) or started from a candidate in the
829
+ // panel, and they may already be dragging its vias. A run that stages again
830
+ // (which a weaker model does on reading the pick message, however plainly
831
+ // the prompt says not to) would re-route the same route, re-arm the edit
832
+ // under the user's hands, and overwrite the draft's name with whatever the
833
+ // model passed. Report the truth and change nothing.
834
+ if (ctx.origin === "agent" && session.draft !== null) {
835
+ return {
836
+ data: { staged: false },
837
+ ok: true,
838
+ summary: "That route is already staged in the editor for the user to adjust: nothing to do.",
839
+ };
840
+ }
841
+
842
+ // The pick belongs to the USER unless they explicitly delegated it. A run
843
+ // staging straight off a generate would always find a candidate (the batch
844
+ // auto-previews its first), and the staged draft flips the sidenav to the
845
+ // staging panel over whatever the user was editing. So an agent-origin
846
+ // startFrom requires the deliberate agent-origin select the delegated flow
847
+ // performs and the uninvited one skips. Human dispatches (the suggestions
848
+ // card's pick chain, the panel row) are untouched. Prompt guidance alone
849
+ // does not hold here: a weaker model reads "end your turn" and stages
850
+ // anyway, so the contract is enforced where it cannot be ignored.
851
+ if (ctx.origin === "agent" && !session.agentSelected) {
852
+ return {
853
+ code: "conflict",
854
+ error:
855
+ "start from suggestion: the user has not picked a candidate, and the suggestions card in the conversation is awaiting their choice. End your turn; call studio.itinerary.suggest.select first only when the user explicitly asked you to choose for them.",
856
+ ok: false,
857
+ };
858
+ }
859
+
860
+ return null;
861
+ };
862
+
863
+ /**
864
+ * armStagedSegment opens the first segment of a draft `startFrom` staged for a directions
865
+ * edit, seeded from the vias the draft was built on. A draft with no segment, or a context
866
+ * with no bus, arms nothing.
867
+ */
868
+ const armStagedSegment = async (
869
+ ctx: StudioToolContext,
870
+ draft: ItineraryDraft,
871
+ vias: Position[],
872
+ activitySlug: string,
873
+ ): Promise<void> => {
874
+ // Arm the seeded segment's geometry edit at once so "Start from this itinerary"
875
+ // opens the route draggable, in edit mode. The draft is a
876
+ // single directions segment and the editable [lng, lat] seed the draft row's "Edit
877
+ // geometry" derives is the simplified `vias` seedFromCoordinates narrows here, so the
878
+ // auto-arm seeds the directions engine identically to the manual edit. The edit
879
+ // commits back into the draft via the DraftSink, exactly the pre-persist edit the
880
+ // import draft exercises. Chaining through ctx.bus keeps the bus the single mutation
881
+ // surface: the handler never arms the map engine itself. The created itinerary opens
882
+ // in VIEW mode (the suggest commit arms nothing on activate), so the armed edit
883
+ // lives only during this pre-create staging step.
884
+ const segment = draft.segments[0];
885
+ if (segment && ctx.bus) {
886
+ const seed = seedFromCoordinates(vias);
887
+ await ctx.bus.dispatch(ctx, "studio.itinerary.segment.editBegin", {
888
+ activitySlug,
889
+ color: segment.color,
890
+ mode: "directions",
891
+ seedVias: seed.seedVias,
892
+ segmentId: segment.id,
893
+ });
894
+ }
895
+ };
896
+
897
+ /**
898
+ * StartFromAnswer is what `studio.itinerary.suggest.startFrom` answers.
899
+ */
900
+ type StartFromAnswer = ToolResult<StudioToolOutputs["studio.itinerary.suggest.startFrom"]>;
901
+
902
+ /**
903
+ * StagingSubject is what `startFrom` stages from once its checks pass: the selected candidate,
904
+ * the session's activity and that activity's slug in the catalog.
905
+ */
906
+ interface StagingSubject {
907
+ readonly activityId: string;
908
+ readonly activitySlug: string;
909
+ readonly candidate: SuggestionCandidate;
910
+ }
911
+
912
+ /**
913
+ * stagingSubject runs the checks `startFrom` makes before it routes anything, and answers what
914
+ * it stages from, or the verb's own answer where nothing is staged: `no-session` with no suggest
915
+ * session, `invalid-input` with no activity, `not-found` with no selected candidate or an
916
+ * activity the catalog does not hold, and what {@link agentStagingAnswer} says to a run.
917
+ */
918
+ const stagingSubject = (ctx: StudioToolContext): StagingSubject | StartFromAnswer => {
919
+ const session = selectSuggestionSession(ctx.ui.getState());
920
+ if (!session) {
921
+ return {
922
+ code: "no-session",
923
+ error: "start from suggestion: no open suggest session",
924
+ ok: false,
925
+ };
926
+ }
927
+
928
+ if (session.activityId === null) {
929
+ return {
930
+ code: "invalid-input",
931
+ error: "start from suggestion: no activity selected",
932
+ ok: false,
933
+ };
934
+ }
935
+
936
+ const candidate = selectedCandidate(session);
937
+ if (candidate === null) {
938
+ return {
939
+ code: "not-found",
940
+ error:
941
+ "start from suggestion: no candidate selected; select one with studio.itinerary.suggest.select",
942
+ ok: false,
943
+ };
944
+ }
945
+
946
+ const agentAnswer = agentStagingAnswer(ctx, session);
947
+ if (agentAnswer) {
948
+ return agentAnswer;
949
+ }
950
+
951
+ // Resolve the activity from the catalog the useActivities cache holds (the
952
+ // session carries only the activity UUID) the same way generate does. A
953
+ // missing catalog or unknown activity cannot route or seed the draft, so it
954
+ // is a structured failure rather than a partial seed.
955
+ const categories = ctx.api?.cache.get({ kind: "activities" });
956
+ const activity = categories ? activityForId(categories, session.activityId) : null;
957
+ if (!activity) {
958
+ return {
959
+ code: "not-found",
960
+ error: "start from suggestion: the selected activity is not in the catalog",
961
+ ok: false,
962
+ };
963
+ }
964
+
965
+ return { activityId: session.activityId, activitySlug: activity.slug, candidate };
966
+ };
967
+
968
+ /**
969
+ * stagingBase reads the routed base `startFrom` builds its draft on, or the failure it answers
970
+ * where there is none.
971
+ *
972
+ * The routing read is wrapped in a try so a throw never escapes the bus (which re-throws into
973
+ * the fire-and-forget dispatch and would surface nothing): a failure lands on the session status
974
+ * (the suggest error shape) and the candidates stay intact. A request the session stopped
975
+ * waiting on writes nothing and answers `request.superseded`.
976
+ */
977
+ const stagingBase = async (
978
+ ctx: StudioToolContext,
979
+ request: SuggestRequest,
980
+ subject: StagingSubject,
981
+ vias: Position[],
982
+ ): Promise<RoutedBase | ToolFailure> => {
983
+ const { candidate } = subject;
984
+
985
+ let base: Awaited<ReturnType<typeof routedBaseFor>>;
986
+ try {
987
+ base = await routedBaseFor(
988
+ ctx,
989
+ candidate.geometry,
990
+ vias,
991
+ candidate.distanceMeters,
992
+ candidate.durationSeconds,
993
+ candidate.analysis,
994
+ candidate.elevation,
995
+ subject.activitySlug,
996
+ );
997
+ } catch (error) {
998
+ if (!request.isLatest()) {
999
+ return request.superseded;
1000
+ }
1001
+
1002
+ const failure = failureFromThrown(error);
1003
+
1004
+ // As generate's catch: the API's own sentence on the session, the technical line on
1005
+ // the result.
1006
+ ctx.ui
1007
+ .getState()
1008
+ .setSuggestionStatus({ kind: "error", message: failure.detail ?? failure.error });
1009
+
1010
+ return failure;
1011
+ }
1012
+
1013
+ // The session this verb read was discarded, replaced or given other inputs while the
1014
+ // route was out. Nothing is staged and no edit is armed over what stands there now.
1015
+ if (!request.isLatest()) {
1016
+ return request.superseded;
1017
+ }
1018
+
1019
+ if (base !== null && "failure" in base) {
1020
+ ctx.ui.getState().setSuggestionStatus({ kind: "idle" });
1021
+
1022
+ return base.failure;
1023
+ }
1024
+
1025
+ if (!base) {
1026
+ const message = "start from suggestion: the selected route could not be routed";
1027
+ ctx.ui.getState().setSuggestionStatus({ kind: "error", message });
1028
+
1029
+ return { code: "not-found", error: message, ok: false };
1030
+ }
1031
+
1032
+ return base;
1033
+ };
1034
+
1035
+ /**
1036
+ * StagedNames are the two names `startFrom` is handed: the itinerary's and its first segment's.
1037
+ */
1038
+ interface StagedNames {
1039
+ readonly itineraryName: string;
1040
+ readonly segmentName: string;
1041
+ }
1042
+
1043
+ /**
1044
+ * stageRoutedDraft stages the draft `startFrom` built its routed base for: it asks about an edit
1045
+ * the suggest surface would take the slot from, puts that surface on screen where the session
1046
+ * took none, writes the draft and the itinerary's name onto the session, and arms the draft's
1047
+ * first segment.
1048
+ *
1049
+ * @param input - The verb's own input, which the confirmation request carries and the draft is
1050
+ * named from.
1051
+ */
1052
+ const stageRoutedDraft = async (
1053
+ ctx: StudioToolContext,
1054
+ request: SuggestRequest,
1055
+ subject: StagingSubject,
1056
+ staged: { readonly base: RoutedBase; readonly vias: Position[] },
1057
+ input: StagedNames,
1058
+ ): Promise<StartFromAnswer> => {
1059
+ // The staging below takes the suggest surface where it is not showing, so an edit armed on
1060
+ // what shows now is asked about first, as an open of the surface asks. Asked here, in the
1061
+ // turn that stages, so nothing armed during the routing read is staged over.
1062
+ const kept = await leaveForSurface(ctx, "studio.itinerary.suggest.startFrom", "suggest", input);
1063
+ if (kept) {
1064
+ if (request.isLatest()) {
1065
+ ctx.ui.getState().setSuggestionStatus({ kind: "ready" });
1066
+ }
1067
+
1068
+ return kept;
1069
+ }
1070
+
1071
+ // The reader may have discarded the session or changed an input while they were asked.
1072
+ if (!request.isLatest()) {
1073
+ return request.superseded;
1074
+ }
1075
+
1076
+ // Build the editable draft: a single directions segment carrying the vias (for
1077
+ // re-edit), the routed 3D line + metrics + elevation/analysis (for rendering +
1078
+ // the elevation panel's full profile), the selected candidate's own color, and
1079
+ // the supplied segment name. The draft reuses the hue the results row swatch and
1080
+ // the map preview line have shown all along, so the route the user audited is the
1081
+ // color the created itinerary opens in, with no jarring recolor on "start from".
1082
+ // The draft is shaped exactly like an imported directions
1083
+ // draft so it edits + commits through the identical code paths. Writing the draft
1084
+ // flips the suggest surface to its draft-editing mode and the preview-sync hook
1085
+ // paints the routed line reactively.
1086
+ const draft = routedSegmentToDraft({
1087
+ activityId: subject.activityId,
1088
+ analysis: staged.base.analysis,
1089
+ color: subject.candidate.color,
1090
+ distanceMeters: staged.base.distanceMeters,
1091
+ durationSeconds: staged.base.durationSeconds,
1092
+ elevation: staged.base.elevation,
1093
+ name: input.segmentName,
1094
+ routedGeometry: staged.base.routedGeometry,
1095
+ vias: staged.vias,
1096
+ });
1097
+
1098
+ // The surface first, where the session took none: the draft staged next answers for the
1099
+ // editor from its first write, and the edit armed below is the draft's.
1100
+ if (!ownsDraftSurface(ctx, "suggest")) {
1101
+ openItinerarySurface(ctx, "suggest");
1102
+ }
1103
+
1104
+ const ui = ctx.ui.getState();
1105
+ // Staged, never set: a draft built from another candidate is another working copy.
1106
+ ui.stageSuggestDraft(draft);
1107
+ ui.setSuggestName(input.itineraryName);
1108
+
1109
+ await armStagedSegment(ctx, draft, staged.vias, subject.activitySlug);
1110
+
1111
+ // Mark ready last so the surface settles on the staging step after the edit arms.
1112
+ ui.setSuggestionStatus({ kind: "ready" });
1113
+
1114
+ return {
1115
+ data: { staged: true },
1116
+ ok: true,
1117
+ summary: "Shaped the suggested route into an editable draft for review.",
1118
+ };
1119
+ };
1120
+
1121
+ /**
1122
+ * startFrom seeds the suggest session's editable draft from the selected suggested route,
1123
+ * driving the unified create/edit panel into its staging step, where the user names it, sets
1124
+ * visibility/owner/collections, and tweaks the route before Create.
1125
+ *
1126
+ * It persists nothing and never navigates: it resolves the activity the same way generate does,
1127
+ * simplifies the candidate's first line to the 2–45 vias a directions segment accepts, obtains a
1128
+ * routed 3D base (the candidate's own geometry when it already carries elevation, otherwise the
1129
+ * simplified vias routed once through the non-persisting directions seam), and builds a
1130
+ * single-directions-segment draft from it through routedSegmentToDraft (carrying the vias for
1131
+ * the next edit, the routed line and its metrics, the selected candidate's own color, and the
1132
+ * supplied segment name). It writes that draft and the supplied itinerary name onto the session.
1133
+ * The organization and privacy defaults are seeded by the staging form's effect (privacy already
1134
+ * seeds true in openSuggest), so they are not set here. It then ARMS the seeded segment's
1135
+ * geometry edit (chaining studio.itinerary.segment.editBegin through ctx.bus) so "Start from
1136
+ * this itinerary" opens the route draggable in edit mode, the same pre-persist edit the import
1137
+ * draft exercises. The created itinerary opens in view mode: the suggest commit arms nothing on
1138
+ * activate.
1139
+ *
1140
+ * It requires an open session, a selected candidate and a resolvable activity: any missing is a
1141
+ * structured failure with nothing seeded. While a 2D candidate routes it marks the session
1142
+ * in-progress (`generating`); a routing failure lands on the session status (the suggest error
1143
+ * shape) and returns a failure, leaving the candidates intact so the user can pick another. It
1144
+ * does at most a routing read, but it is the gate into the commit path.
1145
+ *
1146
+ * A draft answers for the editor only while its surface shows, so the staging puts the suggest
1147
+ * surface on screen where the session took none (the co-pilot's own, whose delegated pick
1148
+ * stages here). That is an open of the surface, and it asks as one does: an edit armed on what
1149
+ * the slot was showing is put to the reader through {@link leaveForSurface} once the route is
1150
+ * in hand, and a decline answers `confirmation-denied`, stages nothing and leaves the batch
1151
+ * pickable.
1152
+ */
1153
+ export const startFrom: StudioToolDefinition<"studio.itinerary.suggest.startFrom"> = {
1154
+ handler: async (ctx, input) => {
1155
+ // Another draft staged over one whose commit is out waits until the commit settles.
1156
+ const held = holdDuringDraftCommit(ctx, "suggest", "start from");
1157
+ if (held) {
1158
+ return held;
1159
+ }
1160
+
1161
+ const subject = stagingSubject(ctx);
1162
+ if ("ok" in subject) {
1163
+ return subject;
1164
+ }
1165
+
1166
+ // The chosen candidate's route is a LineString (possibly collection-wrapped);
1167
+ // walk every line it holds and simplify the path to the 2–45 vias a directions segment
1168
+ // accepts so the draft seeds on the pre-shaped route, and so a re-edit seeds the
1169
+ // SDK's draggable waypoints from them. simplifyToVias returns GeoJSON Positions.
1170
+ const vias = simplifyToVias(
1171
+ segmentLineCoordinates(subject.candidate.geometry),
1172
+ DIRECTIONS_VIA_MAX,
1173
+ );
1174
+
1175
+ // Mark the session in-progress while a 2D candidate routes; a 3D candidate
1176
+ // returns synchronously below and the status flip is harmless.
1177
+ const request = openSuggestRequest(ctx, "start from suggestion");
1178
+
1179
+ const base = await stagingBase(ctx, request, subject, vias);
1180
+ if ("ok" in base) {
1181
+ return base;
1182
+ }
1183
+
1184
+ return stageRoutedDraft(ctx, request, subject, { base, vias }, input);
1185
+ },
1186
+ };