@mountaya/studio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (524) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +917 -2
  5. package/dist/agent/index.cjs +2854 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1257 -0
  8. package/dist/agent/index.d.ts +1257 -0
  9. package/dist/agent/index.js +2818 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/bus-BwiNiXdH.d.ts +514 -0
  12. package/dist/bus-DzmhPwdK.d.cts +514 -0
  13. package/dist/chainModel-B23pEP_1.d.cts +127 -0
  14. package/dist/chainModel-B23pEP_1.d.ts +127 -0
  15. package/dist/chunk-2HFY7ETU.js +5721 -0
  16. package/dist/chunk-2HFY7ETU.js.map +1 -0
  17. package/dist/chunk-355TOXSB.js +72 -0
  18. package/dist/chunk-355TOXSB.js.map +1 -0
  19. package/dist/chunk-4ZCUZVSV.js +10275 -0
  20. package/dist/chunk-4ZCUZVSV.js.map +1 -0
  21. package/dist/chunk-6HEKY3NF.js +95 -0
  22. package/dist/chunk-6HEKY3NF.js.map +1 -0
  23. package/dist/chunk-7GFLGGBX.cjs +8 -0
  24. package/dist/chunk-7GFLGGBX.cjs.map +1 -0
  25. package/dist/chunk-7NBRCENN.cjs +19 -0
  26. package/dist/chunk-7NBRCENN.cjs.map +1 -0
  27. package/dist/chunk-AF5GCXE3.js +8 -0
  28. package/dist/chunk-AF5GCXE3.js.map +1 -0
  29. package/dist/chunk-CJDIFRGZ.cjs +2005 -0
  30. package/dist/chunk-CJDIFRGZ.cjs.map +1 -0
  31. package/dist/chunk-CNPZY7N3.js +349 -0
  32. package/dist/chunk-CNPZY7N3.js.map +1 -0
  33. package/dist/chunk-DZJHTWSF.cjs +45 -0
  34. package/dist/chunk-DZJHTWSF.cjs.map +1 -0
  35. package/dist/chunk-EABIHHWA.js +42 -0
  36. package/dist/chunk-EABIHHWA.js.map +1 -0
  37. package/dist/chunk-EKZWV6RS.cjs +415 -0
  38. package/dist/chunk-EKZWV6RS.cjs.map +1 -0
  39. package/dist/chunk-EOKRXXAC.cjs +24 -0
  40. package/dist/chunk-EOKRXXAC.cjs.map +1 -0
  41. package/dist/chunk-F73W2ZTJ.js +1126 -0
  42. package/dist/chunk-F73W2ZTJ.js.map +1 -0
  43. package/dist/chunk-H4DVOZ5O.js +1897 -0
  44. package/dist/chunk-H4DVOZ5O.js.map +1 -0
  45. package/dist/chunk-HI52PBFT.cjs +10314 -0
  46. package/dist/chunk-HI52PBFT.cjs.map +1 -0
  47. package/dist/chunk-IDBXFBLG.cjs +1225 -0
  48. package/dist/chunk-IDBXFBLG.cjs.map +1 -0
  49. package/dist/chunk-LBWTJZUJ.js +297 -0
  50. package/dist/chunk-LBWTJZUJ.js.map +1 -0
  51. package/dist/chunk-NCLA6DKD.cjs +310 -0
  52. package/dist/chunk-NCLA6DKD.cjs.map +1 -0
  53. package/dist/chunk-O4MC5DPD.js +19 -0
  54. package/dist/chunk-O4MC5DPD.js.map +1 -0
  55. package/dist/chunk-OP37FKW6.cjs +98 -0
  56. package/dist/chunk-OP37FKW6.cjs.map +1 -0
  57. package/dist/chunk-OQSYFH3Z.cjs +5945 -0
  58. package/dist/chunk-OQSYFH3Z.cjs.map +1 -0
  59. package/dist/chunk-PACIO4NS.cjs +26 -0
  60. package/dist/chunk-PACIO4NS.cjs.map +1 -0
  61. package/dist/chunk-PSZ2R3TC.cjs +75 -0
  62. package/dist/chunk-PSZ2R3TC.cjs.map +1 -0
  63. package/dist/chunk-QFO5CZG2.cjs +136 -0
  64. package/dist/chunk-QFO5CZG2.cjs.map +1 -0
  65. package/dist/chunk-QL63MUEW.cjs +140 -0
  66. package/dist/chunk-QL63MUEW.cjs.map +1 -0
  67. package/dist/chunk-RFUPPVZO.js +17 -0
  68. package/dist/chunk-RFUPPVZO.js.map +1 -0
  69. package/dist/chunk-RPG2LWMP.js +23 -0
  70. package/dist/chunk-RPG2LWMP.js.map +1 -0
  71. package/dist/chunk-TIBXK6B7.cjs +12 -0
  72. package/dist/chunk-TIBXK6B7.cjs.map +1 -0
  73. package/dist/chunk-UU65VNEV.js +381 -0
  74. package/dist/chunk-UU65VNEV.js.map +1 -0
  75. package/dist/chunk-VGX6TR2I.js +209 -0
  76. package/dist/chunk-VGX6TR2I.js.map +1 -0
  77. package/dist/chunk-WUTDDBVP.js +130 -0
  78. package/dist/chunk-WUTDDBVP.js.map +1 -0
  79. package/dist/chunk-WVQQLKCI.cjs +224 -0
  80. package/dist/chunk-WVQQLKCI.cjs.map +1 -0
  81. package/dist/chunk-WZYXG3SE.js +111 -0
  82. package/dist/chunk-WZYXG3SE.js.map +1 -0
  83. package/dist/chunk-XDI2X3KE.js +6 -0
  84. package/dist/chunk-XDI2X3KE.js.map +1 -0
  85. package/dist/chunk-XKHLRIC7.cjs +381 -0
  86. package/dist/chunk-XKHLRIC7.cjs.map +1 -0
  87. package/dist/context-DNtd2WUv.d.cts +11666 -0
  88. package/dist/context-DgB72Bur.d.ts +11666 -0
  89. package/dist/directorThreads-CqmvsV8b.d.cts +80 -0
  90. package/dist/directorThreads-CqmvsV8b.d.ts +80 -0
  91. package/dist/en-Bu4Ti9Ev.d.cts +2315 -0
  92. package/dist/en-Bu4Ti9Ev.d.ts +2315 -0
  93. package/dist/engines/index.cjs +3446 -0
  94. package/dist/engines/index.cjs.map +1 -0
  95. package/dist/engines/index.d.cts +2216 -0
  96. package/dist/engines/index.d.ts +2216 -0
  97. package/dist/engines/index.js +3416 -0
  98. package/dist/engines/index.js.map +1 -0
  99. package/dist/handlers/index.cjs +99 -0
  100. package/dist/handlers/index.cjs.map +1 -0
  101. package/dist/handlers/index.d.cts +445 -0
  102. package/dist/handlers/index.d.ts +445 -0
  103. package/dist/handlers/index.js +42 -0
  104. package/dist/handlers/index.js.map +1 -0
  105. package/dist/index.cjs +4562 -0
  106. package/dist/index.cjs.map +1 -0
  107. package/dist/index.d.cts +7297 -0
  108. package/dist/index.d.ts +7297 -0
  109. package/dist/index.js +3223 -0
  110. package/dist/index.js.map +1 -0
  111. package/dist/plugins/index.cjs +977 -0
  112. package/dist/plugins/index.cjs.map +1 -0
  113. package/dist/plugins/index.d.cts +313 -0
  114. package/dist/plugins/index.d.ts +313 -0
  115. package/dist/plugins/index.js +933 -0
  116. package/dist/plugins/index.js.map +1 -0
  117. package/dist/saveFile-j-1kkApx.d.cts +123 -0
  118. package/dist/saveFile-j-1kkApx.d.ts +123 -0
  119. package/dist/seams/index.cjs +152 -0
  120. package/dist/seams/index.cjs.map +1 -0
  121. package/dist/seams/index.d.cts +485 -0
  122. package/dist/seams/index.d.ts +485 -0
  123. package/dist/seams/index.js +79 -0
  124. package/dist/seams/index.js.map +1 -0
  125. package/dist/shareLink-B6hlt942.d.ts +144 -0
  126. package/dist/shareLink-C7rIMb7x.d.ts +527 -0
  127. package/dist/shareLink-CnTxxXjp.d.cts +144 -0
  128. package/dist/shareLink-DyZVYH2V.d.cts +527 -0
  129. package/dist/strings/fr/index.cjs +2121 -0
  130. package/dist/strings/fr/index.cjs.map +1 -0
  131. package/dist/strings/fr/index.d.cts +19 -0
  132. package/dist/strings/fr/index.d.ts +19 -0
  133. package/dist/strings/fr/index.js +2119 -0
  134. package/dist/strings/fr/index.js.map +1 -0
  135. package/dist/strings/index.cjs +2678 -0
  136. package/dist/strings/index.cjs.map +1 -0
  137. package/dist/strings/index.d.cts +731 -0
  138. package/dist/strings/index.d.ts +731 -0
  139. package/dist/strings/index.js +2644 -0
  140. package/dist/strings/index.js.map +1 -0
  141. package/dist/studioPlugin-C3C7VjMy.d.ts +847 -0
  142. package/dist/studioPlugin-Cf3OBNUv.d.cts +847 -0
  143. package/dist/tabs-B2nRO4p_.d.cts +15 -0
  144. package/dist/tabs-B2nRO4p_.d.ts +15 -0
  145. package/dist/testing/index.cjs +292 -0
  146. package/dist/testing/index.cjs.map +1 -0
  147. package/dist/testing/index.d.cts +306 -0
  148. package/dist/testing/index.d.ts +306 -0
  149. package/dist/testing/index.js +284 -0
  150. package/dist/testing/index.js.map +1 -0
  151. package/dist/time/index.cjs +28 -0
  152. package/dist/time/index.cjs.map +1 -0
  153. package/dist/time/index.d.cts +43 -0
  154. package/dist/time/index.d.ts +43 -0
  155. package/dist/time/index.js +26 -0
  156. package/dist/time/index.js.map +1 -0
  157. package/dist/types-BzJRV6UI.d.cts +845 -0
  158. package/dist/types-BzJRV6UI.d.ts +845 -0
  159. package/dist/zoneForm-CdYNtnnA.d.cts +320 -0
  160. package/dist/zoneForm-mG85yt5e.d.ts +320 -0
  161. package/package.json +225 -4
  162. package/src/agent/engines/agentThreads.ts +1601 -0
  163. package/src/agent/engines/directorChat.ts +500 -0
  164. package/src/agent/index.ts +67 -0
  165. package/src/agent/rules/agentEditLock.ts +115 -0
  166. package/src/agent/rules/agentErrorCopy.ts +44 -0
  167. package/src/agent/rules/copilotOrganization.ts +36 -0
  168. package/src/agent/rules/playbook.gen.ts +444 -0
  169. package/src/agent/rules/router.ts +518 -0
  170. package/src/agent/rules/stateDelta.ts +28 -0
  171. package/src/agent/rules/studioRouter.ts +123 -0
  172. package/src/agent/rules/surfaces.gen.ts +633 -0
  173. package/src/agent/rules/threadsUrl.ts +48 -0
  174. package/src/agent/rules/transcriptObserver.ts +90 -0
  175. package/src/agent/stores/agentThreads.ts +454 -0
  176. package/src/bus/contracts/noData.ts +18 -0
  177. package/src/bus/contracts/shared.ts +172 -0
  178. package/src/bus/contracts/studioTools.ts +224 -0
  179. package/src/bus/rules/bus.ts +858 -0
  180. package/src/bus/rules/confirmation.ts +22 -0
  181. package/src/bus/rules/defineRegistry.ts +26 -0
  182. package/src/bus/rules/errors.ts +401 -0
  183. package/src/bus/rules/handlerErrors.ts +103 -0
  184. package/src/bus/rules/handlerRegistry.ts +627 -0
  185. package/src/bus/rules/inputSchema.ts +232 -0
  186. package/src/bus/rules/invalidInput.ts +441 -0
  187. package/src/bus/rules/lateBoundTools.ts +100 -0
  188. package/src/bus/rules/studioRegistry.ts +324 -0
  189. package/src/bus/rules/studioToolBus.ts +73 -0
  190. package/src/bus/rules/types.ts +805 -0
  191. package/src/chrome/contracts/alert.ts +42 -0
  192. package/src/chrome/contracts/itinerary.ts +26 -0
  193. package/src/chrome/contracts/map.ts +23 -0
  194. package/src/chrome/contracts/overlay.ts +46 -0
  195. package/src/chrome/contracts/panel.ts +29 -0
  196. package/src/chrome/contracts/question.ts +52 -0
  197. package/src/chrome/contracts/selection.ts +26 -0
  198. package/src/chrome/contracts/sidenav.ts +23 -0
  199. package/src/chrome/contracts/snapshot.ts +319 -0
  200. package/src/chrome/contracts/state.ts +22 -0
  201. package/src/chrome/contracts/tabs.ts +56 -0
  202. package/src/chrome/handlers/alert.ts +91 -0
  203. package/src/chrome/handlers/introspection.ts +180 -0
  204. package/src/chrome/handlers/panels.ts +42 -0
  205. package/src/chrome/handlers/question.ts +24 -0
  206. package/src/chrome/handlers/sidenav.ts +116 -0
  207. package/src/chrome/handlers/snapshot.ts +451 -0
  208. package/src/chrome/handlers/stateDelta.ts +125 -0
  209. package/src/chrome/handlers/tabs.ts +143 -0
  210. package/src/chrome/handlers/timestamp.ts +19 -0
  211. package/src/chrome/rules/agentSelectors.ts +210 -0
  212. package/src/chrome/rules/mapAlert.ts +13 -0
  213. package/src/chrome/rules/question.ts +25 -0
  214. package/src/chrome/rules/tabs.ts +13 -0
  215. package/src/chrome/stores/activeDraftSession.ts +134 -0
  216. package/src/chrome/stores/chrome.ts +527 -0
  217. package/src/chrome/stores/uiStore.ts +573 -0
  218. package/src/collab/contracts/collab.ts +261 -0
  219. package/src/collab/handlers/collab.ts +468 -0
  220. package/src/collab/rules/toolNames.ts +33 -0
  221. package/src/collab/stores/collab.ts +899 -0
  222. package/src/collections/contracts/collection.ts +182 -0
  223. package/src/collections/handlers/collectionAttach.ts +141 -0
  224. package/src/collections/handlers/collections.ts +499 -0
  225. package/src/collections/handlers/heldCollection.ts +42 -0
  226. package/src/collections/handlers/restCollections.ts +386 -0
  227. package/src/collections/rules/collections.ts +138 -0
  228. package/src/collections/rules/entityCollections.ts +53 -0
  229. package/src/collections/stores/collections.ts +133 -0
  230. package/src/data/contracts/data.ts +233 -0
  231. package/src/data/contracts/itinerary.ts +71 -0
  232. package/src/data/handlers/activityResolve.ts +76 -0
  233. package/src/data/handlers/data.ts +200 -0
  234. package/src/data/handlers/graphql.ts +26 -0
  235. package/src/data/handlers/mutationSink.ts +1577 -0
  236. package/src/data/handlers/profile.ts +83 -0
  237. package/src/data/handlers/writeThrough.ts +417 -0
  238. package/src/data/rules/cache.ts +181 -0
  239. package/src/data/rules/dataTypes.ts +40 -0
  240. package/src/data/rules/keys.ts +106 -0
  241. package/src/data/rules/persistence.ts +1058 -0
  242. package/src/data/rules/requestBody.ts +43 -0
  243. package/src/data/rules/restErrors.ts +354 -0
  244. package/src/data/rules/sessionSurface.ts +156 -0
  245. package/src/data/rules/toolResultData.ts +73 -0
  246. package/src/data/rules/uuid.ts +24 -0
  247. package/src/edit/contracts/edit.ts +37 -0
  248. package/src/edit/contracts/itinerary.ts +57 -0
  249. package/src/edit/handlers/draftCommit.ts +257 -0
  250. package/src/edit/handlers/editDiscard.ts +34 -0
  251. package/src/edit/handlers/editLock.ts +949 -0
  252. package/src/edit/handlers/editor.ts +203 -0
  253. package/src/edit/handlers/formUnsaved.ts +24 -0
  254. package/src/edit/rules/draftMetadata.ts +117 -0
  255. package/src/edit/rules/editKeyboard.ts +222 -0
  256. package/src/edit/rules/editShortcuts.ts +102 -0
  257. package/src/edit/rules/editTooltip.ts +174 -0
  258. package/src/edit/rules/editorTaken.ts +49 -0
  259. package/src/edit/rules/history.ts +26 -0
  260. package/src/edit/rules/unsavedWork.ts +60 -0
  261. package/src/edit/stores/editorReservation.ts +70 -0
  262. package/src/edit/stores/formsUnsaved.ts +54 -0
  263. package/src/embed/contracts/embed.ts +48 -0
  264. package/src/embed/engines/embedFraming.ts +1329 -0
  265. package/src/embed/engines/embedReady.ts +353 -0
  266. package/src/embed/engines/framingPageSession.ts +169 -0
  267. package/src/embed/handlers/embed.ts +130 -0
  268. package/src/embed/rules/allowedDomains.ts +71 -0
  269. package/src/embed/rules/bridgeMessages.ts +224 -0
  270. package/src/embed/rules/defaults.ts +173 -0
  271. package/src/embed/rules/displaySeed.ts +115 -0
  272. package/src/embed/rules/embedAllowlist.ts +146 -0
  273. package/src/embed/rules/embedConstraints.ts +215 -0
  274. package/src/embed/rules/embedElements.ts +277 -0
  275. package/src/embed/rules/embedSectionFields.ts +126 -0
  276. package/src/embed/rules/embedSecurity.ts +116 -0
  277. package/src/embed/rules/fieldDependencies.ts +87 -0
  278. package/src/embed/rules/fieldOptions.ts +138 -0
  279. package/src/embed/rules/layerOptions.ts +161 -0
  280. package/src/embed/rules/readyProtocol.ts +66 -0
  281. package/src/embed/rules/safetyRules.ts +213 -0
  282. package/src/embed/rules/snippet.ts +531 -0
  283. package/src/embed/rules/tableCode.ts +269 -0
  284. package/src/embed/stores/embed.ts +60 -0
  285. package/src/embed/stores/embedContent.ts +77 -0
  286. package/src/engines/index.ts +81 -0
  287. package/src/handlers/index.ts +66 -0
  288. package/src/index.ts +1086 -0
  289. package/src/itinerary/contracts/itinerary.ts +705 -0
  290. package/src/itinerary/engines/itineraryPace.ts +612 -0
  291. package/src/itinerary/engines/profileMarker.ts +238 -0
  292. package/src/itinerary/handlers/importStaging.ts +352 -0
  293. package/src/itinerary/handlers/itinerary.ts +572 -0
  294. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  295. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  296. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  297. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  298. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  299. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  300. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  301. package/src/itinerary/handlers/publicationScope.ts +118 -0
  302. package/src/itinerary/handlers/restItineraries.ts +752 -0
  303. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  304. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  305. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  306. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  307. package/src/itinerary/handlers/suggestParams.ts +379 -0
  308. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  309. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  310. package/src/itinerary/rules/activity.ts +139 -0
  311. package/src/itinerary/rules/analysis.ts +42 -0
  312. package/src/itinerary/rules/ceiling.ts +49 -0
  313. package/src/itinerary/rules/createFlow.ts +107 -0
  314. package/src/itinerary/rules/densify.ts +440 -0
  315. package/src/itinerary/rules/draftSurface.ts +219 -0
  316. package/src/itinerary/rules/editorView.ts +83 -0
  317. package/src/itinerary/rules/export.ts +159 -0
  318. package/src/itinerary/rules/friendlyName.ts +77 -0
  319. package/src/itinerary/rules/import.ts +1052 -0
  320. package/src/itinerary/rules/importFiles.ts +140 -0
  321. package/src/itinerary/rules/importTotals.ts +77 -0
  322. package/src/itinerary/rules/liveSegment.ts +712 -0
  323. package/src/itinerary/rules/lngLat.ts +17 -0
  324. package/src/itinerary/rules/mapSync.ts +100 -0
  325. package/src/itinerary/rules/previewRender.ts +416 -0
  326. package/src/itinerary/rules/profileReadout.ts +216 -0
  327. package/src/itinerary/rules/routing.ts +707 -0
  328. package/src/itinerary/rules/suggest.ts +522 -0
  329. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  330. package/src/itinerary/rules/view.ts +61 -0
  331. package/src/itinerary/stores/importSession.ts +319 -0
  332. package/src/itinerary/stores/itinerary.ts +331 -0
  333. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  334. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  335. package/src/itinerary/stores/suggestSession.ts +418 -0
  336. package/src/layers/contracts/itinerary.ts +46 -0
  337. package/src/layers/contracts/overlay.ts +132 -0
  338. package/src/layers/handlers/enrichment.ts +36 -0
  339. package/src/layers/handlers/overlay.ts +406 -0
  340. package/src/layers/handlers/restLayers.ts +94 -0
  341. package/src/layers/handlers/tiles.ts +25 -0
  342. package/src/layers/rules/layers.ts +212 -0
  343. package/src/layers/rules/overlayInstant.ts +12 -0
  344. package/src/layers/rules/reachabilityIcon.ts +18 -0
  345. package/src/layers/rules/readout.ts +102 -0
  346. package/src/layers/stores/layers.ts +262 -0
  347. package/src/map/contracts/contextmenu.ts +33 -0
  348. package/src/map/contracts/geolocate.ts +37 -0
  349. package/src/map/contracts/map.ts +146 -0
  350. package/src/map/contracts/streetview.ts +53 -0
  351. package/src/map/contracts/terrain.ts +152 -0
  352. package/src/map/handlers/contextMenu.ts +135 -0
  353. package/src/map/handlers/geolocate.ts +52 -0
  354. package/src/map/handlers/map.ts +391 -0
  355. package/src/map/handlers/streetview.ts +94 -0
  356. package/src/map/handlers/terrain.ts +663 -0
  357. package/src/map/rules/baseTerrain.ts +75 -0
  358. package/src/map/rules/clickTargets.ts +464 -0
  359. package/src/map/rules/constraints.ts +32 -0
  360. package/src/map/rules/contextMenuReadout.ts +67 -0
  361. package/src/map/rules/coordinates.ts +71 -0
  362. package/src/map/rules/itineraryFit.ts +8 -0
  363. package/src/map/rules/mapEvents.ts +64 -0
  364. package/src/map/rules/mapProjection.ts +476 -0
  365. package/src/map/rules/terrainReading.ts +62 -0
  366. package/src/plugins/contracts/ids.ts +66 -0
  367. package/src/plugins/contracts/plugin.ts +200 -0
  368. package/src/plugins/contracts/slots.ts +137 -0
  369. package/src/plugins/engines/studioPlugin.ts +1365 -0
  370. package/src/plugins/index.ts +111 -0
  371. package/src/plugins/rules/contributions.ts +152 -0
  372. package/src/plugins/rules/errors.ts +60 -0
  373. package/src/plugins/rules/ids.ts +42 -0
  374. package/src/plugins/rules/validation.ts +249 -0
  375. package/src/rules/listeners.ts +57 -0
  376. package/src/rules/origin.ts +13 -0
  377. package/src/rules/storeWrite.ts +37 -0
  378. package/src/rules/types.ts +136 -0
  379. package/src/seams/index.ts +79 -0
  380. package/src/seams/rules/clock.ts +28 -0
  381. package/src/seams/rules/formatters.ts +209 -0
  382. package/src/seams/rules/ids.ts +102 -0
  383. package/src/seams/rules/links.ts +66 -0
  384. package/src/seams/rules/navigation.ts +222 -0
  385. package/src/seams/rules/notify.ts +49 -0
  386. package/src/seams/rules/persistenceDrawer.ts +220 -0
  387. package/src/seams/rules/saveFile.ts +101 -0
  388. package/src/seams/rules/seams.ts +156 -0
  389. package/src/seams/rules/storage.ts +116 -0
  390. package/src/search/contracts/overlay.ts +74 -0
  391. package/src/search/contracts/search.ts +197 -0
  392. package/src/search/handlers/pois.ts +57 -0
  393. package/src/search/handlers/search.ts +280 -0
  394. package/src/search/rules/params.ts +925 -0
  395. package/src/search/rules/poiGroups.ts +138 -0
  396. package/src/search/rules/searchFetch.ts +139 -0
  397. package/src/search/rules/timeWindow.ts +30 -0
  398. package/src/search/stores/search.ts +51 -0
  399. package/src/segments/contracts/itinerary.ts +433 -0
  400. package/src/segments/contracts/segment.ts +35 -0
  401. package/src/segments/engines/segmentDraft.ts +926 -0
  402. package/src/segments/handlers/chainGuards.ts +67 -0
  403. package/src/segments/handlers/directions.ts +44 -0
  404. package/src/segments/handlers/itineraryEcho.ts +45 -0
  405. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  406. package/src/segments/handlers/segment.ts +111 -0
  407. package/src/segments/handlers/segmentEdit.ts +1341 -0
  408. package/src/segments/handlers/segmentGroups.ts +347 -0
  409. package/src/segments/handlers/segmentStructure.ts +1144 -0
  410. package/src/segments/rules/chain.ts +196 -0
  411. package/src/segments/rules/chainModel.ts +217 -0
  412. package/src/segments/rules/colors.ts +11 -0
  413. package/src/segments/rules/commit.ts +76 -0
  414. package/src/segments/rules/draft.ts +90 -0
  415. package/src/segments/rules/draftDisposition.ts +43 -0
  416. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  417. package/src/segments/rules/engine.ts +222 -0
  418. package/src/segments/rules/groupSave.ts +234 -0
  419. package/src/segments/rules/hazardPrompt.ts +60 -0
  420. package/src/segments/rules/itineraryEcho.ts +40 -0
  421. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  422. package/src/segments/rules/merge.ts +51 -0
  423. package/src/segments/rules/metrics.ts +456 -0
  424. package/src/segments/rules/naming.ts +168 -0
  425. package/src/segments/rules/segmentArming.ts +144 -0
  426. package/src/segments/rules/splitPick.ts +84 -0
  427. package/src/segments/rules/viaSimplify.ts +230 -0
  428. package/src/segments/stores/directions.ts +77 -0
  429. package/src/segments/stores/roadAccessDialog.ts +58 -0
  430. package/src/segments/stores/segmentEdit.ts +922 -0
  431. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  432. package/src/segments/stores/segmentSplit.ts +77 -0
  433. package/src/share/contracts/share.ts +39 -0
  434. package/src/share/contracts/shareLink.ts +63 -0
  435. package/src/share/engines/shareLink.ts +1053 -0
  436. package/src/share/handlers/share.ts +47 -0
  437. package/src/share/handlers/shareLink.ts +231 -0
  438. package/src/share/handlers/shareScope.ts +54 -0
  439. package/src/share/rules/link.ts +89 -0
  440. package/src/share/rules/shareLink.ts +218 -0
  441. package/src/share/rules/targets.ts +92 -0
  442. package/src/share/rules/viewConfig.ts +95 -0
  443. package/src/share/stores/share.ts +58 -0
  444. package/src/strings/fr/index.ts +18 -0
  445. package/src/strings/fr/rules/fr.ts +2368 -0
  446. package/src/strings/index.ts +98 -0
  447. package/src/strings/rules/confirmCopy.ts +156 -0
  448. package/src/strings/rules/draftToolNames.ts +94 -0
  449. package/src/strings/rules/en.ts +2519 -0
  450. package/src/strings/rules/failureAlert.ts +115 -0
  451. package/src/strings/rules/formError.ts +400 -0
  452. package/src/strings/rules/maneuvers.ts +107 -0
  453. package/src/strings/rules/outputOptions.ts +126 -0
  454. package/src/strings/rules/publicationState.ts +100 -0
  455. package/src/strings/rules/routeHazardCopy.ts +62 -0
  456. package/src/strings/rules/searchLabels.ts +50 -0
  457. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  458. package/src/strings/rules/studioCopy.ts +130 -0
  459. package/src/strings/rules/unitOptions.ts +119 -0
  460. package/src/testing/checkedBus.ts +226 -0
  461. package/src/testing/index.ts +34 -0
  462. package/src/testing/plugins.ts +106 -0
  463. package/src/testing/studio.ts +267 -0
  464. package/src/testing/urlSeam.ts +153 -0
  465. package/src/time/index.ts +12 -0
  466. package/src/time/rules/sun.ts +78 -0
  467. package/src/video/contracts/cameraSchemas.ts +266 -0
  468. package/src/video/contracts/profileSchemas.ts +37 -0
  469. package/src/video/contracts/video.ts +601 -0
  470. package/src/video/handlers/video.ts +1638 -0
  471. package/src/video/handlers/videoDirector.ts +114 -0
  472. package/src/video/rules/previewRefresh.ts +76 -0
  473. package/src/video/rules/profileSource.ts +51 -0
  474. package/src/video/rules/routeSpans.ts +79 -0
  475. package/src/video/rules/shotDefaults.ts +28 -0
  476. package/src/video/rules/stepOrder.ts +17 -0
  477. package/src/video/rules/videoSnapshot.ts +136 -0
  478. package/src/video/stores/directorThreads.ts +167 -0
  479. package/src/video/stores/videoExport.ts +290 -0
  480. package/src/viewer/contracts/preferences.ts +40 -0
  481. package/src/viewer/handlers/preferences.ts +91 -0
  482. package/src/viewer/rules/capabilities.ts +42 -0
  483. package/src/viewer/rules/config.ts +266 -0
  484. package/src/viewer/rules/context.ts +375 -0
  485. package/src/viewer/rules/ownership.ts +134 -0
  486. package/src/viewer/rules/platformViewer.ts +198 -0
  487. package/src/viewer/rules/scope.ts +197 -0
  488. package/src/viewer/rules/url.ts +145 -0
  489. package/src/viewer/rules/viewer.ts +307 -0
  490. package/src/viewer/rules/viewerSeam.ts +49 -0
  491. package/src/viewer/rules/viewerUnits.ts +34 -0
  492. package/src/waypoints/contracts/itinerary.ts +417 -0
  493. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  494. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  495. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  496. package/src/waypoints/rules/amenities.ts +30 -0
  497. package/src/waypoints/rules/defaults.ts +31 -0
  498. package/src/waypoints/rules/details.ts +213 -0
  499. package/src/waypoints/rules/detailsDraft.ts +312 -0
  500. package/src/waypoints/rules/detailsPreview.ts +76 -0
  501. package/src/waypoints/rules/detailsSave.ts +356 -0
  502. package/src/waypoints/rules/draftDirty.ts +45 -0
  503. package/src/waypoints/rules/icons.ts +32 -0
  504. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  505. package/src/waypoints/rules/naming.ts +185 -0
  506. package/src/waypoints/rules/sections.ts +77 -0
  507. package/src/waypoints/rules/waypointDraft.ts +62 -0
  508. package/src/waypoints/stores/waypointDetails.ts +62 -0
  509. package/src/waypoints/stores/waypointEdit.ts +566 -0
  510. package/src/zones/contracts/collection.ts +37 -0
  511. package/src/zones/contracts/zone.ts +528 -0
  512. package/src/zones/engines/zoneForm.ts +1773 -0
  513. package/src/zones/handlers/restZones.ts +287 -0
  514. package/src/zones/handlers/zonePublish.ts +206 -0
  515. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  516. package/src/zones/handlers/zones.ts +2254 -0
  517. package/src/zones/rules/geometry.ts +946 -0
  518. package/src/zones/rules/zoneDefaults.ts +34 -0
  519. package/src/zones/rules/zoneDraft.ts +54 -0
  520. package/src/zones/rules/zoneForm.ts +563 -0
  521. package/src/zones/rules/zoneMetadata.ts +29 -0
  522. package/src/zones/rules/zoneSource.ts +87 -0
  523. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  524. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1601 @@
1
+ import type { AgentErrorCode } from "@mountaya/client";
2
+ import type { AgentTransport } from "@mountaya/client/events";
3
+ import {
4
+ AgentEngine,
5
+ type AgentEngineState,
6
+ type AgentErrorCopy,
7
+ type AgentObserver,
8
+ type ConversationFaults,
9
+ type ConversationHost,
10
+ createConversationFaults,
11
+ createConversationHost,
12
+ } from "@mountaya/elements/agent";
13
+ import { boundsOf } from "@mountaya/elements/geo";
14
+
15
+ import type { StudioToolInputs } from "../../bus/contracts/studioTools.js";
16
+ import type { ToolBus } from "../../bus/rules/bus.js";
17
+ import { isConfirmationWithheld } from "../../bus/rules/confirmation.js";
18
+ import { failureFromThrown } from "../../bus/rules/errors.js";
19
+ import type { TabSurface, ToolResult } from "../../bus/rules/types.js";
20
+ import { questionToolContracts } from "../../chrome/contracts/question.js";
21
+ import { buildStudioSnapshot } from "../../chrome/handlers/snapshot.js";
22
+ import { captureStudioState } from "../../chrome/handlers/stateDelta.js";
23
+ import { MAX_OPEN_COPILOT_TABS } from "../../chrome/handlers/tabs.js";
24
+ import { agentHandoffTarget, selectSuggestionSession } from "../../chrome/rules/agentSelectors.js";
25
+ import type { UiStoreApi } from "../../chrome/stores/uiStore.js";
26
+ import { notifyListeners, surfaceFault } from "../../rules/listeners.js";
27
+ import type { StudioIds } from "../../seams/rules/ids.js";
28
+ import { defaultSegmentName } from "../../segments/rules/naming.js";
29
+ import { confirmSentence } from "../../strings/rules/confirmCopy.js";
30
+ import type { StudioStrings } from "../../strings/rules/en.js";
31
+ import { layerToolContext, type StudioToolContext } from "../../viewer/rules/context.js";
32
+ import type { StudioViewer } from "../../viewer/rules/viewer.js";
33
+ import { agentEditLockTarget, agentTakesEntityBack } from "../rules/agentEditLock.js";
34
+ import { copilotOrganizationId } from "../rules/copilotOrganization.js";
35
+ import { routerStateFrom } from "../rules/router.js";
36
+ import { studioStateDelta } from "../rules/stateDelta.js";
37
+ import {
38
+ type RecoveryAddendum,
39
+ selectSurfaces,
40
+ studioRecoveryFor,
41
+ surfaceTools,
42
+ } from "../rules/studioRouter.js";
43
+ import type { AgentThreadMirror, AgentThreadsUrlSeam } from "../rules/threadsUrl.js";
44
+ import { transcriptObserver } from "../rules/transcriptObserver.js";
45
+ import {
46
+ type AgentThreadsState,
47
+ type AgentThreadsStoreApi,
48
+ createAgentThreadsStore,
49
+ SEARCH_TAB_ID,
50
+ selectAgentDriving,
51
+ WITHHELD_TAB_ID,
52
+ } from "../stores/agentThreads.js";
53
+
54
+ /** The tool whose call renders as a question card rather than as an activity row. */
55
+ const QUESTION_TOOL = "studio.question.ask";
56
+
57
+ /** The tool whose settle renders the live suggest session as a suggestions card. */
58
+ const GENERATE_TOOL = "studio.itinerary.suggest.generate";
59
+
60
+ /**
61
+ * The code of a run the gateway stopped because its member may not run it there any more: no
62
+ * write role in its organization, or an agreement that does not include Map Studio.
63
+ */
64
+ const ACCESS_REVOKED: AgentErrorCode = "access-revoked";
65
+
66
+ /**
67
+ * AgentThreadsTabsSeam is where an {@link AgentThreadsEngine} publishes its tab strip, so a
68
+ * studio verb dispatched from outside the co-pilot (`studio.tabs.create` from an editor's
69
+ * "ask the co-pilot" entry) reaches the engine's threads through `ctx.tabs`.
70
+ *
71
+ * The engine registers its surface when the first subscriber resumes it and unregisters it
72
+ * when the last one parks it, so a tab verb dispatched while nothing watches the co-pilot
73
+ * answers the structured failure an absent `ctx.tabs` defines. A host whose tool context reads
74
+ * `tabs` through a late-bound getter answers both members with the slot that getter reads.
75
+ */
76
+ export interface AgentThreadsTabsSeam {
77
+ /** Publishes the engine's tab surface. */
78
+ readonly register: (surface: TabSurface) => void;
79
+ /** Withdraws it, after which a tab verb answers a structured failure. */
80
+ readonly unregister: () => void;
81
+ }
82
+
83
+ /**
84
+ * AgentThreadsConfig is what the co-pilot's conversations run against, all of it replaceable
85
+ * mid-life through {@link AgentThreadsEngine.configure}.
86
+ *
87
+ * Every member is read when it is used rather than when the engine is built: a session built
88
+ * after a change runs on the new transport and bus, and an error or a confirmation card raised
89
+ * after a locale change reads the new words.
90
+ */
91
+ export interface AgentThreadsConfig {
92
+ /**
93
+ * The studio's bus, whole. A run reads the manifest it advertises for the context's
94
+ * capabilities and dispatches with the model as its origin, and the engine dispatches the tab,
95
+ * framing and suggestion verbs through it.
96
+ */
97
+ readonly bus: ToolBus<StudioToolContext, StudioToolInputs>;
98
+ /**
99
+ * The studio's tool context, which every conversation drives. A run's dispatches layer the
100
+ * in-chat confirmation and the agent origin over it with `layerToolContext`, so its late-bound
101
+ * getters (the map, the tabs, the collaboration session) stay live.
102
+ */
103
+ readonly context: StudioToolContext;
104
+ /**
105
+ * The localized copy a terminal run error resolves onto, the same object the video director
106
+ * reads, so the two surfaces phrase a budget ceiling or a rate limit identically.
107
+ */
108
+ readonly errorCopy: AgentErrorCopy;
109
+ /**
110
+ * Marks an organization's AI configuration stale after a start the gateway refused for want
111
+ * of one. Omitted, the refusal still surfaces its words and the configuration is re-read on
112
+ * the next natural fetch, the defined answer for a host with no cache of its own.
113
+ */
114
+ readonly invalidateAiConfig?: ((organizationId: string) => void) | undefined;
115
+ /**
116
+ * Marks the viewer's memberships stale after the gateway refused or ended a run for want of
117
+ * access: a start or its stream answered 402, 403 or 404, a follow-up found its run gone, or a
118
+ * run ended `access-revoked` because its member may not run it there any more (no write role in
119
+ * its organization, or an agreement that does not include Map Studio). The co-pilot's gate reads
120
+ * the memberships, so the notice that follows the refresh says why the co-pilot is withheld.
121
+ * Omitted, the refusal still surfaces its words and the memberships are re-read on the next
122
+ * natural fetch.
123
+ */
124
+ readonly invalidateMemberships?: (() => void) | undefined;
125
+ /**
126
+ * Tells the host the API refused the credential a run rides on: its start, its stream (a
127
+ * restored run's included) or a message into it answered 401. Under the browser's own session
128
+ * that is a sign-in the API no longer accepts, after a sign-out or a revoked session, so the
129
+ * host asks whether the person is still signed in and, when nobody is, sends them to sign in.
130
+ * Called once per refusal, once the fault is written. A 401 says nothing of the viewer's
131
+ * access, so the memberships are not read again for it.
132
+ *
133
+ * Pass it where the runs ride the browser's own session. Under a publishable key a 401 refuses
134
+ * the key or the session token beside it, which is no sign-in a host can ask about. Omitted, a
135
+ * refusal still surfaces its words.
136
+ */
137
+ readonly onSignInRefused?: (() => void) | undefined;
138
+ /**
139
+ * The host's own remedy for a failed call, appended to the playbook's recovery the model reads
140
+ * with it. Omitted, the model reads the playbook's recovery alone.
141
+ */
142
+ readonly recoveryAddendum?: RecoveryAddendum | undefined;
143
+ /**
144
+ * Whether a run names the server tools its model sees, from the tools the conversation's
145
+ * surfaces route to: a run's start and each routing update then carry the routed set.
146
+ *
147
+ * Off by default, and to stay off under a publishable key, the credential a studio embedded in
148
+ * a product runs under: a run under a key calls no server tool, and the API refuses a start or
149
+ * an update that names any. Off, a run names none and keeps every server tool its credential
150
+ * reaches. A host on the browser's own session turns it on to narrow them.
151
+ *
152
+ * @default false
153
+ */
154
+ readonly routesServerTools?: boolean | undefined;
155
+ /** The words the conversations write: fault lines, confirmation cards, the staging error. */
156
+ readonly strings: Pick<
157
+ StudioStrings,
158
+ "confirm" | "copilot" | "editing" | "editor" | "prompt" | "share"
159
+ >;
160
+ /**
161
+ * How the open conversations survive a reload. Its `readOnce` is read by the constructor
162
+ * alone, from the options; replacing the seam later changes where `write` mirrors to.
163
+ * Omitted, nothing is restored and nothing is mirrored.
164
+ */
165
+ readonly threadsUrl?: AgentThreadsUrlSeam | undefined;
166
+ /** The event transport every run is started, sent into and read over. */
167
+ readonly transport: AgentTransport;
168
+ }
169
+
170
+ /**
171
+ * AgentThreadsEngineOptions is the {@link AgentThreadsConfig} an engine starts with, plus the
172
+ * settings fixed for its life.
173
+ */
174
+ export interface AgentThreadsEngineOptions extends AgentThreadsConfig {
175
+ /**
176
+ * Where a new conversation's id comes from. Pass the host's `ids` seam, or
177
+ * `sequentialStudioIds()` where the ids must be a function of the input.
178
+ */
179
+ readonly ids: StudioIds;
180
+ /**
181
+ * The store the conversations are written into, for a host that reads it with narrow
182
+ * selectors of its own. It is seeded by the constructor, so it starts empty.
183
+ *
184
+ * @default a new `createAgentThreadsStore()`
185
+ */
186
+ readonly store?: AgentThreadsStoreApi | undefined;
187
+ /**
188
+ * Where the tab strip is published while the engine runs. Omitted, a tab verb dispatched
189
+ * from outside the co-pilot answers a structured failure, and the engine's own tab commands
190
+ * still work.
191
+ */
192
+ readonly tabs?: AgentThreadsTabsSeam | undefined;
193
+ }
194
+
195
+ /**
196
+ * holdRejection keeps the rejection of a dispatch the engine does not await.
197
+ *
198
+ * A tool bus's dispatch never rejects, and a host's own may. Left unhandled, the rejection would
199
+ * end a Node process and reach a page's error tracker as a fault of the studio's. The call made
200
+ * no answer and the engine reads none of a dispatch it does not await, so nothing follows it.
201
+ *
202
+ * What the dispatch answered is read as a promise whatever it is. A bus that answers none, as a
203
+ * double written over a bare spy does, is held the same way, so no command throws over it.
204
+ */
205
+ const holdRejection = (dispatched: Promise<unknown>): void => {
206
+ Promise.resolve(dispatched).then(undefined, () => undefined);
207
+ };
208
+
209
+ /**
210
+ * isOutcome reports whether a dispatch's answer states how the verb ended, as a tool bus's always
211
+ * does: an object whose `ok` is a boolean.
212
+ */
213
+ const isOutcome = (answered: unknown): answered is ToolResult =>
214
+ typeof answered === "object" &&
215
+ answered !== null &&
216
+ "ok" in answered &&
217
+ typeof answered.ok === "boolean";
218
+
219
+ /**
220
+ * restorableThreads keeps the conversations of a URL the engine restores: at most
221
+ * `MAX_OPEN_COPILOT_TABS` of them, in the order written.
222
+ *
223
+ * A URL is the visitor's to write, and every conversation restored with a run id is a session
224
+ * and a reconnecting event stream, so the list is bounded here, by the limit the create gate
225
+ * holds an open tab to, whatever the host's route let through.
226
+ *
227
+ * The seam types the list, and the value behind it is whatever the URL spelled, so `named` is
228
+ * read as `unknown` and nothing here throws on it: anything but a list restores nothing. An
229
+ * entry is dropped when it is not an object, when its id is not a non-empty string, when it is a
230
+ * pseudo-tab's id (Search's or the withheld tab's: a thread under either could never be closed
231
+ * and would count against the limit for good), or when an earlier entry carries the same id. A
232
+ * run id that is not a non-empty string reads as no run.
233
+ */
234
+ const restorableThreads = (named: unknown): readonly AgentThreadMirror[] => {
235
+ const kept = new Map<string, AgentThreadMirror>();
236
+ const entries: readonly unknown[] = Array.isArray(named) ? named : [];
237
+
238
+ for (const entry of entries) {
239
+ if (kept.size >= MAX_OPEN_COPILOT_TABS) {
240
+ break;
241
+ }
242
+
243
+ if (typeof entry !== "object" || entry === null) {
244
+ continue;
245
+ }
246
+
247
+ const id: unknown = "id" in entry ? entry.id : undefined;
248
+ const runId: unknown = "runId" in entry ? entry.runId : undefined;
249
+ if (
250
+ typeof id !== "string" ||
251
+ id === "" ||
252
+ id === SEARCH_TAB_ID ||
253
+ id === WITHHELD_TAB_ID ||
254
+ kept.has(id)
255
+ ) {
256
+ continue;
257
+ }
258
+
259
+ kept.set(id, { id, runId: typeof runId === "string" && runId !== "" ? runId : null });
260
+ }
261
+
262
+ return [...kept.values()];
263
+ };
264
+
265
+ /** One {@link AgentThreadsEngine.subscribe} call, held by identity so each one parks once. */
266
+ interface Subscription {
267
+ readonly listener: () => void;
268
+ }
269
+
270
+ /**
271
+ * AgentThreadsEngine runs the studio co-pilot's concurrent conversations: one `AgentEngine`
272
+ * session per thread, each driving the same studio through the same bus and tool context, so
273
+ * switching tabs switches the conversation and never the workspace.
274
+ *
275
+ * The snapshot is the threads store's state (`AgentThreadsState`): the tab order, the active
276
+ * tab, and each thread's run id, lifecycle state, transcript and pending confirmation. A
277
+ * surface reads it with narrow selectors over the store rather than re-rendering on every
278
+ * streamed token. No member of {@link AgentThreadsConfig} keys it, so there is no previous
279
+ * question whose answer a configuration change could show.
280
+ *
281
+ * What the conversations do, in the order a run meets it:
282
+ *
283
+ * - **Seeding.** The constructor restores the threads the URL names, with their run ids, and
284
+ * the tab it names when that tab still exists; otherwise it lands on Search, with one fresh
285
+ * thread for a viewer entitled to the co-pilot and none for one who is not. It restores at
286
+ * most `MAX_OPEN_COPILOT_TABS` threads, never one under a pseudo-tab's id, and none at all for a
287
+ * viewer withheld the co-pilot: the URL is the visitor's to write, so the engine bounds it
288
+ * and a host's route need not. What the URL names is kept for a viewer withheld at
289
+ * construction, and restored once that viewer is entitled: when the viewer seam tells the
290
+ * change, at the next resume, or ahead of the next command, whichever comes first, and once,
291
+ * and the URL is written with the conversations that restore holds. The entitlement is read
292
+ * from the viewer seam wherever the engine acts on it, so a reveal or a close made after the
293
+ * change follows the viewer as it stands then.
294
+ * - **Routing.** Every message picks the surfaces its turn offers, keeping the thread's
295
+ * previous pick as the stickiness input, and a tool settle re-picks from live state with the
296
+ * thread's last message, so a surface the run unlocks reaches the manifest before its next
297
+ * turn.
298
+ * - **Turns.** A conversation reads `running` from the moment its message is sent, so the
299
+ * workspace locks before the run's context is captured and its start is made. It returns to
300
+ * `awaiting_input` when the turn settles, which its session reports, and at once when the
301
+ * message opens no run.
302
+ * - **Confirmations.** A destructive tool, server or client, raises an in-chat card instead of a
303
+ * modal. The user's decision, a stop, a tab close or a park settles it, so a run never waits
304
+ * on a decision that can no longer arrive.
305
+ * - **Tool calls.** An editor verb locks the entity it names for the run, a verb that takes an
306
+ * entity back lowers the hand-off, a question renders as a card, and a settled generate
307
+ * renders the live suggest session as a suggestions card, framed once while its thread is on
308
+ * screen. The suggest session is one workspace-wide slot, so only the generate that still
309
+ * owns it may render or discard it.
310
+ * - **Faults.** A start refused for access or configuration, a submit with no organization to
311
+ * scope a run to, and a stream that faults each land as an error turn and re-enable input.
312
+ *
313
+ * Every listener is told of a change, and one that throws stops neither the engine nor the
314
+ * listeners after it: its fault reaches the program as an uncaught error on a microtask, never
315
+ * as the outcome of a command or of a session's callback. A URL seam or a tab seam that throws
316
+ * is answered the same way.
317
+ *
318
+ * The lifecycle is the listeners, the way `SearchEngine`'s is. The first subscriber builds a
319
+ * host per thread, reconnects every thread that has a run id, mirrors the driving flag into
320
+ * `ctx.ui`, subscribes to the viewer seam and publishes the tab strip; the last unsubscribe
321
+ * disposes every host, denies every parked confirmation, resets the driving flag, the edit locks
322
+ * and the hand-off, releases the viewer seam and withdraws the tab strip. A configuration that
323
+ * carries another UI store or another viewer moves the mirror or the subscription to it. A park
324
+ * ends no conversation: each keeps its run id, so the next resume reconnects it, and reads the
325
+ * state it read, except one that read `running`, which settles on `awaiting_input`. React's
326
+ * StrictMode mounts, unmounts and mounts again, which parks and resumes with one live session per
327
+ * thread at the end. A command does nothing while the engine is parked or disposed: a run opened
328
+ * with nobody watching could be neither seen nor stopped. {@link AgentThreadsEngine.dispose} is
329
+ * the latch, for an owner that is not a component.
330
+ *
331
+ * A reconnect is read by a new session, which its thread's host hands the position the parked
332
+ * session had reached in the run's stream. The stream resumes after it, so the transcript the
333
+ * park kept is written to by the frames it has not read and by no frame a second time. A thread
334
+ * restored from the URL has no such position and an empty transcript: its run's history is read
335
+ * from the first event and writes each entry once.
336
+ *
337
+ * No clock and no timer: nothing here waits on product time. Ids come from the `ids` option,
338
+ * so a thread id is as deterministic as the host's seam.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * import type { AgentTransport } from "@mountaya/client/events";
343
+ * import type { StudioToolContext, StudioToolInputs, ToolBus } from "@mountaya/studio";
344
+ * import {
345
+ * AgentThreadsEngine,
346
+ * type AgentThreadsState,
347
+ * agentErrorCopy,
348
+ * } from "@mountaya/studio/agent";
349
+ * import { sequentialStudioIds } from "@mountaya/studio/seams";
350
+ * import { studioStrings } from "@mountaya/studio/strings";
351
+ *
352
+ * declare const bus: ToolBus<StudioToolContext, StudioToolInputs>;
353
+ * declare const context: StudioToolContext;
354
+ * declare const transport: AgentTransport;
355
+ * declare function render(state: AgentThreadsState): void;
356
+ *
357
+ * const threads = new AgentThreadsEngine({
358
+ * bus,
359
+ * context,
360
+ * errorCopy: agentErrorCopy(studioStrings.en),
361
+ * ids: sequentialStudioIds("thread"),
362
+ * strings: studioStrings.en,
363
+ * transport,
364
+ * });
365
+ * const release = threads.subscribe(() => render(threads.getSnapshot()));
366
+ *
367
+ * threads.submit("Plan a loop from here");
368
+ * release();
369
+ * ```
370
+ */
371
+ export class AgentThreadsEngine {
372
+ private config: AgentThreadsConfig;
373
+ private readonly ids: StudioIds;
374
+ private readonly store: AgentThreadsStoreApi;
375
+ private readonly tabs: AgentThreadsTabsSeam | undefined;
376
+
377
+ private readonly subscriptions = new Set<Subscription>();
378
+ /** The store subscription the listeners are notified through, while the engine runs. */
379
+ private releaseStore: (() => void) | null = null;
380
+ /** The UI store the driving flag is mirrored into, while the engine runs. */
381
+ private mirrored: UiStoreApi | null = null;
382
+ /**
383
+ * What the URL named at construction, kept while the viewer the seed read is withheld the
384
+ * co-pilot and restored for that viewer once entitled. Null for a seed that read an entitled
385
+ * viewer, and once restored.
386
+ */
387
+ private unrestored: ReturnType<AgentThreadsUrlSeam["readOnce"]> | null = null;
388
+ /** The viewer seam the engine hears a change of the entitlement from, while it runs. */
389
+ private heard: { readonly release: () => void; readonly viewer: StudioViewer } | null = null;
390
+
391
+ /** One host per thread: its session and its started guard. */
392
+ private readonly hosts = new Map<string, ConversationHost>();
393
+ /** The resolver of each thread's parked confirmation. */
394
+ private readonly confirmations = new Map<string, (approved: boolean) => void>();
395
+ /** The surfaces each thread's run is routed to; a thread with none offers every tool. */
396
+ private readonly surfaces = new Map<string, readonly string[]>();
397
+ /** The last message each thread routed on, replayed by a re-route from state. */
398
+ private readonly lastRouted = new Map<string, string>();
399
+ /** The generate call that owns the workspace's one suggest session, and its thread. */
400
+ private suggestBatchOwner: { threadId: string; toolCallId: string } | null = null;
401
+ /** The suggestions cards whose pick is still applying, by entry id. */
402
+ private readonly stagingPicks = new Set<string>();
403
+ /**
404
+ * The threads whose last message is out and whose turn the session has not picked up. While
405
+ * a thread is here, its session's `awaiting_input` is the run being readied and never the
406
+ * turn settling.
407
+ */
408
+ private readonly awaitingTurn = new Set<string>();
409
+ /**
410
+ * The state each thread's session last reported, and no entry for one that has reported none,
411
+ * which reads `awaiting_input`. It says whether a message is sent into a turn under way, which
412
+ * the session answers with no report of `running`.
413
+ */
414
+ private readonly sessionStates = new Map<string, AgentEngineState>();
415
+
416
+ /** Whether nobody is watching. A parked engine opens nothing and answers no command. */
417
+ private parked = true;
418
+ private disposed = false;
419
+
420
+ /**
421
+ * The tab strip the studio's tab verbs mutate through. Every member but the two reads,
422
+ * `countOpen` and `hasTab`, does nothing while the engine is parked, and an opening member
423
+ * then answers the tab already shown.
424
+ */
425
+ private readonly tabSurface: TabSurface = {
426
+ addCopilotTab: () => (this.live() ? this.openTab() : this.shownTab()),
427
+ closeCopilotTab: (tabId) => {
428
+ if (this.live()) {
429
+ this.closeTab(tabId);
430
+ }
431
+ },
432
+ // The Search and withheld pseudo-tabs are not in `order`, so its length is exactly the
433
+ // number of conversations the create gate compares against the limit.
434
+ countOpen: () => this.store.getState().order.length,
435
+ // The strip holds Search, each open conversation and, for a viewer withheld the co-pilot,
436
+ // the withheld tab, and no other id.
437
+ hasTab: (tabId) =>
438
+ tabId === SEARCH_TAB_ID ||
439
+ (tabId === WITHHELD_TAB_ID && this.withheld()) ||
440
+ this.store.getState().order.includes(tabId),
441
+ openCopilot: () => (this.live() ? this.openOrReveal() : this.shownTab()),
442
+ reset: () => {
443
+ if (this.live()) {
444
+ this.resetThreads();
445
+ }
446
+ },
447
+ setActiveTab: (tabId) => {
448
+ if (this.live()) {
449
+ this.showTab(tabId);
450
+ }
451
+ },
452
+ };
453
+
454
+ /**
455
+ * Constructing one seeds the store and does nothing else: it reads the URL seam once and the
456
+ * viewer's entitlement as it stands, builds no host, opens no run and writes no URL. A React
457
+ * binding constructs during a render React is free to throw away, and a constructor with a side
458
+ * effect outside its own store would leave the discarded copy acting.
459
+ */
460
+ constructor(options: AgentThreadsEngineOptions) {
461
+ const { ids, store, tabs, ...config } = options;
462
+ this.config = config;
463
+ this.ids = ids;
464
+ this.tabs = tabs;
465
+ this.store = store ?? createAgentThreadsStore();
466
+ this.seed(config.threadsUrl?.readOnce() ?? {});
467
+ }
468
+
469
+ /** getSnapshot returns the conversations' state, by reference and stable between changes. */
470
+ getSnapshot(): AgentThreadsState {
471
+ return this.store.getState();
472
+ }
473
+
474
+ /**
475
+ * subscribe registers a listener for every change of the snapshot, and returns its own
476
+ * unsubscribe, which is idempotent.
477
+ *
478
+ * The first listener resumes the engine and the last one leaving parks it, which is the whole
479
+ * lifecycle a component can express correctly: React tears an effect down and sets it up
480
+ * again with the same object under StrictMode, so a latch here would leave a live surface
481
+ * bound to a dead engine. Each call is its own subscription, so two owners subscribing one
482
+ * shared function each hold the engine until they release it.
483
+ */
484
+ subscribe(listener: () => void): () => void {
485
+ if (this.disposed) {
486
+ return () => {};
487
+ }
488
+
489
+ const subscription: Subscription = { listener };
490
+ this.subscriptions.add(subscription);
491
+
492
+ if (this.parked) {
493
+ this.resume();
494
+ }
495
+
496
+ return () => {
497
+ if (!this.subscriptions.delete(subscription) || this.subscriptions.size > 0) {
498
+ return;
499
+ }
500
+
501
+ if (!this.parked) {
502
+ this.park();
503
+ }
504
+ };
505
+ }
506
+
507
+ /**
508
+ * configure replaces the configuration. Nothing is asked and no session is rebuilt: every
509
+ * member is read when it is used, so a binding may call this on every render and an unchanged
510
+ * configuration costs an assignment. Two things move with the context: the driving flag's
511
+ * mirror, when it carries a different UI store (the store it leaves is reset, and the new one is
512
+ * brought in line with the conversations), and the subscription to the viewer, when it carries
513
+ * a different viewer.
514
+ */
515
+ configure(config: AgentThreadsConfig): void {
516
+ this.config = config;
517
+
518
+ if (this.mirrored !== null && this.mirrored !== config.context.ui) {
519
+ this.releaseMirror();
520
+ this.mirrorInto(config.context.ui);
521
+ }
522
+
523
+ if (this.heard !== null && this.heard.viewer !== config.context.viewer) {
524
+ this.hearViewer(config.context.viewer);
525
+ this.restoreForEntitled();
526
+ }
527
+ }
528
+
529
+ /**
530
+ * dispose parks the engine and drops every listener, for good.
531
+ *
532
+ * Idempotent, and every call after it is a no-op rather than an error, a subscription
533
+ * included: an owner torn down mid-run should not have to guard the calls it already queued.
534
+ */
535
+ dispose(): void {
536
+ if (this.disposed) {
537
+ return;
538
+ }
539
+
540
+ if (!this.parked) {
541
+ this.park();
542
+ }
543
+
544
+ this.disposed = true;
545
+ this.subscriptions.clear();
546
+ }
547
+
548
+ /**
549
+ * answerQuestion settles the active conversation's question card with the picked option, then
550
+ * sends its label as the next message. Settling first is what makes the send's sweep of open
551
+ * cards leave the pick marked.
552
+ *
553
+ * It does nothing unless `entryId` names a question card of the conversation that is still
554
+ * open: a second answer to one card, and an answer to a card a typed reply already settled,
555
+ * send no message, since the run is waiting on neither.
556
+ */
557
+ answerQuestion(entryId: string, label: string): void {
558
+ const threadId = this.activeThread();
559
+ if (threadId === null || !this.hasOpenQuestion(threadId, entryId)) {
560
+ return;
561
+ }
562
+
563
+ this.store.getState().answerQuestion(threadId, entryId, label);
564
+ this.send(threadId, label);
565
+ }
566
+
567
+ /**
568
+ * chooseSuggestion applies one suggested route from a suggestions card, settles the card, and
569
+ * sends the pick's label as the next message.
570
+ *
571
+ * The pick is applied client-side through `studio.itinerary.suggest.applyCandidate`, which
572
+ * reshapes the segment the batch was generated for or appends the route as a new one, so the
573
+ * route is on the map before the model reads the reply. It applies to the open itinerary and
574
+ * never creates one. A second pick on a card whose apply is still out does nothing, since two
575
+ * appends would put the route in the itinerary twice. A failed apply leaves the card open and
576
+ * writes the staging error, so the user can pick again; an apply a host's bus rejects, or
577
+ * answers with no result, is a failed one. A pick whose confirmation was withheld (the user
578
+ * kept a staged draft the apply would drop, or left the prompt to expire) leaves the card open
579
+ * and writes nothing. A pick whose apply lands after the engine parked, or after its
580
+ * conversation closed, writes nothing and opens no run.
581
+ */
582
+ chooseSuggestion(entryId: string, seed: number, label: string): void {
583
+ const threadId = this.activeThread();
584
+ if (threadId === null || this.stagingPicks.has(entryId)) {
585
+ return;
586
+ }
587
+
588
+ this.stagingPicks.add(entryId);
589
+ void this.applyPick(threadId, entryId, seed, label);
590
+ }
591
+
592
+ /** closeAiTab closes one conversation through `studio.tabs.close`. */
593
+ closeAiTab(tabId: string): void {
594
+ if (this.live()) {
595
+ holdRejection(this.config.bus.dispatch(this.tabsContext(), "studio.tabs.close", { tabId }));
596
+ }
597
+ }
598
+
599
+ /** newAiTab opens a conversation through `studio.tabs.create`. */
600
+ newAiTab(): void {
601
+ if (this.live()) {
602
+ holdRejection(
603
+ this.config.bus.dispatch(this.tabsContext(), "studio.tabs.create", {
604
+ kind: "copilot",
605
+ }),
606
+ );
607
+ }
608
+ }
609
+
610
+ /**
611
+ * previewCandidate paints one staged suggestion on the map through
612
+ * `studio.itinerary.suggest.select`, the call the suggestions panel's own rows make, so
613
+ * hovering a card option and hovering a panel row cannot diverge.
614
+ */
615
+ previewCandidate(seed: number): void {
616
+ if (this.live()) {
617
+ holdRejection(
618
+ this.config.bus.dispatch(this.config.context, "studio.itinerary.suggest.select", {
619
+ seed,
620
+ }),
621
+ );
622
+ }
623
+ }
624
+
625
+ /**
626
+ * resolveConfirmation settles the active conversation's confirmation card with the user's
627
+ * decision and clears the card. With nothing pending (a stale click after a stop already
628
+ * settled it) it does nothing.
629
+ */
630
+ resolveConfirmation(approved: boolean): void {
631
+ const threadId = this.activeThread();
632
+ if (threadId === null) {
633
+ return;
634
+ }
635
+
636
+ const resolve = this.confirmations.get(threadId);
637
+ if (resolve === undefined) {
638
+ return;
639
+ }
640
+
641
+ this.confirmations.delete(threadId);
642
+ this.store.getState().clearPendingConfirmation(threadId);
643
+ resolve(approved);
644
+ }
645
+
646
+ /**
647
+ * stopActive ends the active conversation's run: it denies a pending confirmation, asks the
648
+ * gateway to close the run (a run the session gave up reading included), swaps a fresh session
649
+ * in under the same thread so the next message opens a clean run, drops the run id and parks
650
+ * the thread on `awaiting_input`. The close is what stops the run spending model budget: a
651
+ * session torn down without it leaves the run going until the gateway's own timeout. The
652
+ * transcript stays, since a stop is the user's choice rather than a failure.
653
+ */
654
+ stopActive(): void {
655
+ const threadId = this.activeThread();
656
+ if (threadId === null) {
657
+ return;
658
+ }
659
+
660
+ this.denyPendingConfirmation(threadId);
661
+ this.ensureHost(threadId).restart();
662
+ this.store.getState().setRunId(threadId, null);
663
+ this.settle(threadId);
664
+ this.syncUrl();
665
+ }
666
+
667
+ /**
668
+ * submit sends a message into the active conversation: the first one opens a run scoped to
669
+ * the organization of the resource the co-pilot is open on, with the studio snapshot as its
670
+ * context, and a later one is delivered into the open run.
671
+ *
672
+ * The conversation reads `running` from the submit, so the workspace locks and a surface
673
+ * offers its Stop before the run's context is captured and its start is made. It returns to
674
+ * `awaiting_input` when the turn settles, and at once when there is no organization to scope
675
+ * a run to or the gateway refuses the start.
676
+ */
677
+ submit(message: string): void {
678
+ const threadId = this.activeThread();
679
+ if (threadId !== null) {
680
+ this.send(threadId, message);
681
+ }
682
+ }
683
+
684
+ /** switchTab shows another tab, a conversation or a pseudo-tab, through `studio.tabs.switch`. */
685
+ switchTab(tabId: string): void {
686
+ if (this.live()) {
687
+ holdRejection(this.config.bus.dispatch(this.tabsContext(), "studio.tabs.switch", { tabId }));
688
+ }
689
+ }
690
+
691
+ /**
692
+ * live reports whether something watches the engine, which is when it acts. Every command asks
693
+ * it first, so a live engine restores the URL's conversations for a viewer entitled since the
694
+ * seed (see {@link restoreForEntitled}) ahead of the act: a host whose viewer tells no change
695
+ * still meets them there.
696
+ */
697
+ private live(): boolean {
698
+ if (this.parked || this.disposed) {
699
+ return false;
700
+ }
701
+
702
+ this.restoreForEntitled();
703
+
704
+ return true;
705
+ }
706
+
707
+ /**
708
+ * isOpen reports whether an answer for a conversation still has somewhere to land: the engine
709
+ * is live and the conversation has not closed. An answer that arrives after either belongs to
710
+ * nobody.
711
+ */
712
+ private isOpen(threadId: string): boolean {
713
+ return this.live() && this.store.getState().threads[threadId] !== undefined;
714
+ }
715
+
716
+ /** activeThread is the conversation a command acts on, or null while the engine is not live. */
717
+ private activeThread(): string | null {
718
+ return this.live() ? this.store.getState().activeId : null;
719
+ }
720
+
721
+ /** shownTab is the tab the strip shows, what an opening tab verb answers while parked. */
722
+ private shownTab(): string {
723
+ return this.store.getState().activeTabId ?? SEARCH_TAB_ID;
724
+ }
725
+
726
+ /**
727
+ * withheld reads whether the viewer is withheld the co-pilot, from the viewer seam as it
728
+ * answers now. A membership resolves after a host has mounted and an entitlement can lapse
729
+ * mid-session, so the answer is never held: each decision that turns on it asks again.
730
+ */
731
+ private withheld(): boolean {
732
+ return !this.config.context.viewer.hasEntitlement("copilot");
733
+ }
734
+
735
+ /**
736
+ * seed writes the conversations a mount opens with, from the URL and the entitlement.
737
+ *
738
+ * A viewer withheld the co-pilot is restored none, whatever the URL names: their one way into
739
+ * the co-pilot is the withheld tab. What the URL named is kept for them, and
740
+ * {@link restoreForEntitled} restores it once they are entitled.
741
+ */
742
+ private seed(mirrored: ReturnType<AgentThreadsUrlSeam["readOnce"]>): void {
743
+ if (this.withheld()) {
744
+ this.unrestored = mirrored;
745
+ this.store
746
+ .getState()
747
+ .setActiveTab(
748
+ mirrored.activeThreadId === WITHHELD_TAB_ID ? WITHHELD_TAB_ID : SEARCH_TAB_ID,
749
+ );
750
+
751
+ return;
752
+ }
753
+
754
+ this.restore(mirrored);
755
+ }
756
+
757
+ /**
758
+ * restore writes the conversations of an entitled viewer, from what the URL names, and answers
759
+ * the ids it created.
760
+ *
761
+ * The URL's list passes through {@link restorableThreads} first, and a conversation already
762
+ * open keeps its place. With none to restore, a viewer holding no conversation is opened a
763
+ * fresh one, and the panel lands on Search. Otherwise it lands on the tab the URL names when
764
+ * that tab is now open, and on Search when it is not: the withheld tab is never an entitled
765
+ * viewer's.
766
+ */
767
+ private restore(mirrored: ReturnType<AgentThreadsUrlSeam["readOnce"]>): readonly string[] {
768
+ const state = this.store.getState();
769
+ const named = restorableThreads(mirrored.threads).filter(
770
+ ({ id }) => !Object.hasOwn(state.threads, id),
771
+ );
772
+ const initial = mirrored.activeThreadId;
773
+
774
+ if (named.length === 0) {
775
+ const created = state.order.length === 0 ? [this.ids.next()] : [];
776
+ for (const id of created) {
777
+ state.createThread(id);
778
+ }
779
+ state.setActiveTab(SEARCH_TAB_ID);
780
+
781
+ return created;
782
+ }
783
+
784
+ for (const { id, runId } of named) {
785
+ state.createThread(id, runId);
786
+ }
787
+
788
+ const open = this.store.getState().order;
789
+ state.setActiveTab(
790
+ initial !== undefined && (initial === SEARCH_TAB_ID || open.includes(initial))
791
+ ? initial
792
+ : SEARCH_TAB_ID,
793
+ );
794
+
795
+ return named.map(({ id }) => id);
796
+ }
797
+
798
+ /**
799
+ * restoreForEntitled restores what the URL named at construction for a viewer the seed read as
800
+ * withheld and the viewer seam now answers as entitled. It runs once: a viewer who loses the
801
+ * entitlement afterwards and regains it is not restored a second time. A live engine connects
802
+ * each conversation it restores, so one carrying a run id reconnects to its run; a parked one
803
+ * leaves that to the next resume. The URL is written with what the restore holds: a withheld
804
+ * viewer's reveal may have mirrored the withheld tab over the conversations it named.
805
+ */
806
+ private restoreForEntitled(): void {
807
+ const mirrored = this.unrestored;
808
+ if (mirrored === null || this.withheld()) {
809
+ return;
810
+ }
811
+
812
+ this.unrestored = null;
813
+ const created = this.restore(mirrored);
814
+ this.syncUrl();
815
+
816
+ if (!this.parked && !this.disposed) {
817
+ for (const id of created) {
818
+ this.connect(id);
819
+ }
820
+ }
821
+ }
822
+
823
+ /**
824
+ * hearViewer subscribes to a viewer seam's changes, releasing the one heard before, so a
825
+ * viewer entitled while the engine runs is restored the URL's conversations as the seam tells.
826
+ */
827
+ private hearViewer(viewer: StudioViewer): void {
828
+ this.heard?.release();
829
+ this.heard = null;
830
+
831
+ let release: () => void = () => undefined;
832
+ this.tellSeam(() => {
833
+ release = viewer.subscribe(() => this.restoreForEntitled());
834
+ });
835
+ this.heard = { release, viewer };
836
+ }
837
+
838
+ /**
839
+ * connect builds a thread's host and resumes its session, reconnecting to the run the thread
840
+ * carries. A resume that faults drops the stale run id, mirrors the drop and leaves the
841
+ * conversation usable, through the thread's faults, which also tell the host a reconnect
842
+ * refused 401.
843
+ */
844
+ private connect(threadId: string): void {
845
+ this.ensureHost(threadId).resume(
846
+ this.store.getState().threads[threadId]?.runId ?? null,
847
+ (error) => this.faultsFor(threadId).resumeFailed(error),
848
+ );
849
+ }
850
+
851
+ /** resume starts the engine for its first subscriber. */
852
+ private resume(): void {
853
+ // A viewer entitled while the engine was parked is restored first, so the loop below
854
+ // connects what it restores with everything else.
855
+ this.restoreForEntitled();
856
+ this.parked = false;
857
+ this.releaseStore = this.store.subscribe((state) => {
858
+ this.syncDriving(state);
859
+ // The store is written from a session's callbacks and from the commands, so a listener's
860
+ // fault thrown from here would leave through whichever of them made the change.
861
+ notifyListeners(Array.from(this.subscriptions, ({ listener }) => listener));
862
+ });
863
+ this.mirrorInto(this.config.context.ui);
864
+
865
+ // Every thread gets its host now, so its observer is wired before the first message, and a
866
+ // thread that mounted with a run id reconnects to it.
867
+ for (const id of [...this.store.getState().order]) {
868
+ this.connect(id);
869
+ }
870
+
871
+ this.hearViewer(this.config.context.viewer);
872
+ this.tellSeam(() => this.tabs?.register(this.tabSurface));
873
+ }
874
+
875
+ /** park stops the engine when its last subscriber leaves. */
876
+ private park(): void {
877
+ this.parked = true;
878
+ this.releaseStore?.();
879
+ this.releaseStore = null;
880
+
881
+ // A disposed host's session is ended, and an ended session opens no stream. The host itself
882
+ // is kept: it holds the position its session had reached in the run's stream, and the
883
+ // session the next resume has it build is handed that position.
884
+ for (const host of this.hosts.values()) {
885
+ host.dispose();
886
+ }
887
+ this.awaitingTurn.clear();
888
+ this.sessionStates.clear();
889
+ this.settleStreamingThreads();
890
+
891
+ for (const threadId of [...this.confirmations.keys()]) {
892
+ this.denyPendingConfirmation(threadId);
893
+ }
894
+
895
+ this.releaseMirror();
896
+ const heard = this.heard;
897
+ this.heard = null;
898
+ if (heard !== null) {
899
+ this.tellSeam(heard.release);
900
+ }
901
+ this.tellSeam(() => this.tabs?.unregister());
902
+ }
903
+
904
+ /**
905
+ * tellSeam calls one of the host's seams the engine writes to on its own paths: the URL
906
+ * mirror and the tab strip's slot. A seam that throws stops neither the resume, the park nor
907
+ * the command that reached it, and its fault is surfaced apart, as a listener's is.
908
+ */
909
+ private tellSeam(tell: () => void): void {
910
+ try {
911
+ tell();
912
+ } catch (fault) {
913
+ surfaceFault(fault);
914
+ }
915
+ }
916
+
917
+ /**
918
+ * send hands a message to a thread's host, with the conversation on `running` from this
919
+ * moment: the workspace is the model's from the submit, across the capture of the run's
920
+ * context, its start and the opening of its stream.
921
+ *
922
+ * Written before the host is called, so a submit the host answers at once (no organization
923
+ * to scope a run to) returns the conversation to `awaiting_input` through its fault.
924
+ */
925
+ private send(threadId: string, message: string): void {
926
+ // A session that reads `running` takes the message into the turn under way and reports
927
+ // nothing for it, so there is no turn to wait for: its next report is that turn settling.
928
+ if (this.sessionStates.get(threadId) !== "running") {
929
+ this.awaitingTurn.add(threadId);
930
+ }
931
+ this.writeSessionState(threadId, "running");
932
+ this.ensureHost(threadId).submit(message);
933
+ }
934
+
935
+ /**
936
+ * settle returns a conversation to `awaiting_input`: its turn settled, its run faulted or was
937
+ * stopped. It ends the wait for a turn, so the next report of its session is read as it is.
938
+ */
939
+ private settle(threadId: string): void {
940
+ this.awaitingTurn.delete(threadId);
941
+ this.writeSessionState(threadId, "awaiting_input");
942
+ }
943
+
944
+ /**
945
+ * reportSessionState writes the lifecycle state a thread's session reports, while the engine
946
+ * is live.
947
+ *
948
+ * A session reports `ended` as it is disposed, and the park disposes every one of them. The
949
+ * park ends no conversation, so what its teardown reports is not written: a conversation that
950
+ * never ran keeps reading `awaiting_input`, and a host reading the store sees no state the
951
+ * park passed through.
952
+ *
953
+ * While a thread waits on its turn, its session's `awaiting_input` is not written either: a
954
+ * session that read a run before reports it as it readies the next one, which would lower the
955
+ * lock between the submit and the turn. The wait ends when the session reports `running`,
956
+ * which it does from the message it takes, and its reports are the conversation's from
957
+ * there: the turn's settle is one of them, whether or not the turn carried a frame of its own.
958
+ */
959
+ private reportSessionState(threadId: string, state: AgentEngineState): void {
960
+ this.sessionStates.set(threadId, state);
961
+
962
+ if (!this.live() || (state === "awaiting_input" && this.awaitingTurn.has(threadId))) {
963
+ return;
964
+ }
965
+
966
+ this.awaitingTurn.delete(threadId);
967
+ this.writeSessionState(threadId, state);
968
+ }
969
+
970
+ /** writeSessionState writes a thread's state when it differs from the one it reads. */
971
+ private writeSessionState(threadId: string, state: AgentEngineState): void {
972
+ const thread = this.store.getState().threads[threadId];
973
+ if (thread !== undefined && thread.state !== state) {
974
+ this.store.getState().setSessionState(threadId, state);
975
+ }
976
+ }
977
+
978
+ /** hasOpenQuestion reports whether `entryId` is a question card the thread has not settled. */
979
+ private hasOpenQuestion(threadId: string, entryId: string): boolean {
980
+ return (
981
+ this.store
982
+ .getState()
983
+ .threads[threadId]?.transcript.some(
984
+ (entry) => entry.role === "question" && entry.id === entryId && !entry.settled,
985
+ ) ?? false
986
+ );
987
+ }
988
+
989
+ /**
990
+ * settleStreamingThreads returns every conversation that reads `running` to `awaiting_input`
991
+ * once the park has disposed its session.
992
+ *
993
+ * No session streams the turn any more, and the session the next resume builds starts on
994
+ * `awaiting_input` and reports a change only. A conversation left on `running` would raise
995
+ * the driving lock at that resume with nothing to lower it. Its run id stays, so the resume
996
+ * reconnects the run and the turn's frames report `running` again.
997
+ */
998
+ private settleStreamingThreads(): void {
999
+ const { order, threads } = this.store.getState();
1000
+ for (const id of order) {
1001
+ if (threads[id]?.state === "running") {
1002
+ this.store.getState().setSessionState(id, "awaiting_input");
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ /** mirrorInto starts mirroring the driving flag into `ui`, brought in line at once. */
1008
+ private mirrorInto(ui: UiStoreApi): void {
1009
+ this.mirrored = ui;
1010
+ this.syncDriving(this.store.getState());
1011
+ }
1012
+
1013
+ /**
1014
+ * releaseMirror stops mirroring, leaving the UI store with no driving flag, no edit lock and
1015
+ * no hand-off: a studio the co-pilot left is never stranded inert.
1016
+ */
1017
+ private releaseMirror(): void {
1018
+ const ui = this.mirrored;
1019
+ if (ui === null) {
1020
+ return;
1021
+ }
1022
+
1023
+ this.mirrored = null;
1024
+ ui.getState().setAgentDriving(false);
1025
+ ui.getState().agentClearEditLocks();
1026
+ ui.getState().setAgentHandoff(null);
1027
+ }
1028
+
1029
+ /**
1030
+ * syncDriving writes the driving flag through to the UI store on a real flip only, so a token
1031
+ * stream does not churn it.
1032
+ *
1033
+ * When the runs yield the workspace, the entities they locked are released, except the one a
1034
+ * run left in an open edit session for the user to adjust and save: that draft outlives the
1035
+ * run, and so does the co-pilot's authorship of it.
1036
+ */
1037
+ private syncDriving(state: AgentThreadsState): void {
1038
+ const ui = this.mirrored;
1039
+ if (ui === null) {
1040
+ return;
1041
+ }
1042
+
1043
+ const driving = selectAgentDriving(state);
1044
+ if (ui.getState().agentDriving === driving) {
1045
+ return;
1046
+ }
1047
+
1048
+ ui.getState().setAgentDriving(driving);
1049
+ if (!driving) {
1050
+ ui.getState().agentClearEditLocks(agentHandoffTarget(ui.getState()));
1051
+ }
1052
+ }
1053
+
1054
+ /** syncUrl mirrors the thread ids, their run ids and the active tab through the URL seam. */
1055
+ private syncUrl(): void {
1056
+ const state = this.store.getState();
1057
+ const threads = state.order.map((id) => ({ id, runId: state.threads[id]?.runId ?? null }));
1058
+ this.tellSeam(() =>
1059
+ this.config.threadsUrl?.write({ activeThreadId: state.activeTabId ?? null, threads }),
1060
+ );
1061
+ }
1062
+
1063
+ /**
1064
+ * tabsContext is the tool context a tab verb is dispatched with: the studio's own, with this
1065
+ * engine's tab strip layered over it and every other seam left live.
1066
+ */
1067
+ private tabsContext(): StudioToolContext {
1068
+ return layerToolContext(this.config.context, { tabs: this.tabSurface });
1069
+ }
1070
+
1071
+ /** ensureHost returns a thread's host, building it on first use. */
1072
+ private ensureHost(threadId: string): ConversationHost {
1073
+ let host = this.hosts.get(threadId);
1074
+ if (host === undefined) {
1075
+ host = this.hostFor(threadId);
1076
+ this.hosts.set(threadId, host);
1077
+ }
1078
+
1079
+ return host;
1080
+ }
1081
+
1082
+ /**
1083
+ * hostFor builds one thread's host. The run is scoped to the organization of the resource the
1084
+ * co-pilot is open on, read through the rule the panel's gate reads, so a run opens for the
1085
+ * organization whose card the panel shows and a personal resource opens none. A snapshot that
1086
+ * fails to build opens the run without a context rather than blocking the message.
1087
+ */
1088
+ private hostFor(threadId: string): ConversationHost {
1089
+ return createConversationHost({
1090
+ appendUserMessage: (message) => this.store.getState().appendUserMessage(threadId, message),
1091
+ buildContext: () => buildStudioSnapshot(this.config.context).catch(() => undefined),
1092
+ buildSession: () => this.sessionFor(threadId),
1093
+ onMissingOrganization: () => this.faultsFor(threadId).missingOrganization(),
1094
+ onSendFault: (error, runGone) => this.faultsFor(threadId).recover(runGone, error),
1095
+ onStartError: (organizationId, error, runId) =>
1096
+ this.faultsFor(threadId).handleStartError(organizationId, error, runId),
1097
+ resolveOrganizationId: () => copilotOrganizationId(this.config.context.ui.getState()),
1098
+ routeForMessage: (message) => this.routeForMessage(threadId, message),
1099
+ routeForState: () => this.routeForState(threadId),
1100
+ });
1101
+ }
1102
+
1103
+ /**
1104
+ * sessionFor builds one thread's session. Both confirmation gates, the server tool's and the
1105
+ * client tool's the bus raises through `ctx.confirm`, park on that thread's in-chat card, and
1106
+ * a client tool's card reads its localized body with the request's values, so a merge names
1107
+ * the rows it is about to join.
1108
+ */
1109
+ private sessionFor(threadId: string): AgentEngine {
1110
+ // A session starts on `awaiting_input` and reports a change only.
1111
+ this.sessionStates.delete(threadId);
1112
+
1113
+ return new AgentEngine({
1114
+ bus: this.config.bus,
1115
+ confirmServerTool: (confirmation) =>
1116
+ this.requestConfirmation(
1117
+ threadId,
1118
+ confirmation.name,
1119
+ this.config.strings.confirm.serverToolFallback(confirmation.name),
1120
+ ),
1121
+ // Layered rather than spread: a spread would evaluate the context's late-bound getters once,
1122
+ // and a session built before the map mounts would carry no map for its whole life.
1123
+ ctx: layerToolContext(this.config.context, {
1124
+ confirm: (request) =>
1125
+ this.requestConfirmation(
1126
+ threadId,
1127
+ request.name,
1128
+ confirmSentence(this.config.strings, request.descriptionLabel, request.values) ??
1129
+ request.description,
1130
+ ),
1131
+ origin: "agent",
1132
+ }),
1133
+ observer: this.observerFor(threadId),
1134
+ // What a tool moved rides its result, and a failure carries the playbook's recovery: the
1135
+ // playbook tells the model both, so a session without them would answer every call bare.
1136
+ // The host's addendum is read at the failure, so a host that changes it reaches the
1137
+ // sessions it already built.
1138
+ recoveryFor: (tool, code) => studioRecoveryFor(tool, code, this.config.recoveryAddendum),
1139
+ routesServerTools: this.config.routesServerTools,
1140
+ stateDelta: studioStateDelta,
1141
+ toolSurface: () => {
1142
+ const surfaces = this.surfaces.get(threadId);
1143
+
1144
+ return surfaces === undefined ? undefined : surfaceTools(surfaces);
1145
+ },
1146
+ transport: this.config.transport,
1147
+ });
1148
+ }
1149
+
1150
+ /**
1151
+ * observerFor maps one thread's session onto its transcript, then layers the co-pilot's own
1152
+ * side effects over it: the URL mirror of a new run id, the question card, the suggest
1153
+ * session's owner, the edit lock and the hand-off, the suggestions card and the re-route.
1154
+ */
1155
+ private observerFor(threadId: string): AgentObserver {
1156
+ const store = this.store;
1157
+ const transcript = transcriptObserver({
1158
+ draftWarning: () => ({
1159
+ note: this.config.strings.prompt.budgetDraftOpen,
1160
+ // Whether a draft sits unsaved is a fact about the moment the run ends. `editingKind`
1161
+ // counts a create armed with no id yet, which is just as losable.
1162
+ open: captureStudioState(this.config.context).editingKind !== null,
1163
+ }),
1164
+ errorCopy: () => this.config.errorCopy,
1165
+ writer: {
1166
+ appendAssistantDelta: (delta) => store.getState().appendAssistantDelta(threadId, delta),
1167
+ appendChecksUnmet: (unmet) => store.getState().appendChecksUnmet(threadId, unmet),
1168
+ appendError: (message) => store.getState().appendError(threadId, message),
1169
+ appendToolActivity: (activity) => store.getState().appendToolActivity(threadId, activity),
1170
+ setAssistantMessage: (content, messageIndex) =>
1171
+ store.getState().setAssistantMessage(threadId, content, messageIndex),
1172
+ setRunId: (runId) => store.getState().setRunId(threadId, runId),
1173
+ setSessionState: (state) => this.reportSessionState(threadId, state),
1174
+ settleToolActivity: (toolCallId, outcome) =>
1175
+ store.getState().settleToolActivity(threadId, toolCallId, outcome),
1176
+ },
1177
+ });
1178
+
1179
+ return {
1180
+ ...transcript,
1181
+ onError: (message, code) => {
1182
+ transcript.onError?.(message, code);
1183
+ // The gateway stopped the run because its member may not run it there any more (no
1184
+ // write role, or an agreement without Map Studio), so the memberships the panel's gate
1185
+ // reads, which carry both, are stale.
1186
+ if (code === ACCESS_REVOKED) {
1187
+ this.tellSeam(() => this.config.invalidateMemberships?.());
1188
+ }
1189
+ },
1190
+ onRunId: (runId) => {
1191
+ transcript.onRunId?.(runId);
1192
+ this.syncUrl();
1193
+ },
1194
+ onToolCall: (name, input, toolCallId) => {
1195
+ if (this.appendQuestionCard(threadId, name, input, toolCallId)) {
1196
+ return;
1197
+ }
1198
+
1199
+ // The generate claims the suggest session before it runs, so its settle can tell its
1200
+ // own batch from one a concurrent thread staged after it.
1201
+ if (name === GENERATE_TOOL) {
1202
+ this.suggestBatchOwner = { threadId, toolCallId };
1203
+ }
1204
+
1205
+ const ui = this.config.context.ui;
1206
+ const target = agentEditLockTarget(name, input);
1207
+ if (target !== null) {
1208
+ ui.getState().agentLockEntity(target.kind, target.id);
1209
+ }
1210
+
1211
+ // An editor call that is not a hand-off takes the entity back, so the user's Save is inert
1212
+ // again. Lowered before the dispatch, so a hand-off verb's own handler raises it after.
1213
+ if (agentTakesEntityBack(name, input)) {
1214
+ ui.getState().setAgentHandoff(null);
1215
+ }
1216
+
1217
+ transcript.onToolCall?.(name, input, toolCallId);
1218
+ },
1219
+ onToolResult: (toolCallId, outcome) => {
1220
+ const settledGenerate = outcome.status === "ok" && this.isGenerate(threadId, toolCallId);
1221
+ transcript.onToolResult?.(toolCallId, outcome);
1222
+
1223
+ if (settledGenerate) {
1224
+ this.appendSuggestionsCard(threadId, toolCallId);
1225
+ }
1226
+
1227
+ // A tool can move the state the router reads, so the thread re-picks now that it
1228
+ // landed. An unchanged pick sends nothing, which is almost every settle.
1229
+ this.hosts.get(threadId)?.reroute();
1230
+ },
1231
+ };
1232
+ }
1233
+
1234
+ /**
1235
+ * appendQuestionCard renders a question call as its own card, parsed with the tool's own
1236
+ * schema, and reports whether it did. A malformed input falls through to the ordinary
1237
+ * activity row, whose dispatch then settles red, which is the honest rendering of that call.
1238
+ */
1239
+ private appendQuestionCard(
1240
+ threadId: string,
1241
+ name: string,
1242
+ input: unknown,
1243
+ toolCallId: string,
1244
+ ): boolean {
1245
+ if (name !== QUESTION_TOOL) {
1246
+ return false;
1247
+ }
1248
+
1249
+ const parsed = questionToolContracts[QUESTION_TOOL].input.safeParse(input);
1250
+ if (!parsed.success) {
1251
+ return false;
1252
+ }
1253
+
1254
+ this.store.getState().appendQuestion(threadId, {
1255
+ options: parsed.data.options.map((option) => ({
1256
+ description: option.description ?? null,
1257
+ label: option.label,
1258
+ })),
1259
+ question: parsed.data.question,
1260
+ toolCallId,
1261
+ });
1262
+
1263
+ return true;
1264
+ }
1265
+
1266
+ /** isGenerate reports whether a thread recorded `toolCallId` as a generate's activity row. */
1267
+ private isGenerate(threadId: string, toolCallId: string): boolean {
1268
+ return (
1269
+ this.store
1270
+ .getState()
1271
+ .threads[threadId]?.transcript.some(
1272
+ (entry) =>
1273
+ entry.role === "activity" && entry.id === toolCallId && entry.name === GENERATE_TOOL,
1274
+ ) ?? false
1275
+ );
1276
+ }
1277
+
1278
+ /**
1279
+ * appendSuggestionsCard renders the live suggest session's candidates as the thread's
1280
+ * suggestions card, keyed off the generating call so a replayed settle appends no duplicate,
1281
+ * and frames the batch once while the thread is the tab on screen.
1282
+ *
1283
+ * It snapshots the SESSION, never the model's echo, so every candidate shows its true colour
1284
+ * and metrics. A settle whose call no longer owns the session renders nothing: another thread
1285
+ * re-pointed the session, and its candidates belong to that conversation.
1286
+ */
1287
+ private appendSuggestionsCard(threadId: string, toolCallId: string): void {
1288
+ const owner = this.suggestBatchOwner;
1289
+ if (owner?.threadId !== threadId || owner.toolCallId !== toolCallId) {
1290
+ return;
1291
+ }
1292
+
1293
+ const context = this.config.context;
1294
+ const candidates = selectSuggestionSession(context.ui.getState())?.candidates ?? [];
1295
+ if (candidates.length === 0) {
1296
+ return;
1297
+ }
1298
+
1299
+ const entryId = `${toolCallId}:card`;
1300
+ const transcript = this.store.getState().threads[threadId]?.transcript ?? [];
1301
+ if (transcript.some((entry) => entry.id === entryId)) {
1302
+ return;
1303
+ }
1304
+
1305
+ this.store.getState().appendSuggestions(threadId, {
1306
+ candidates: candidates.map((candidate) => ({
1307
+ ascentMeters: candidate.ascentMeters,
1308
+ color: candidate.color,
1309
+ distanceMeters: candidate.distanceMeters,
1310
+ durationSeconds: candidate.durationSeconds,
1311
+ seed: candidate.seed,
1312
+ })),
1313
+ entryId,
1314
+ });
1315
+
1316
+ if (this.store.getState().activeTabId !== threadId) {
1317
+ return;
1318
+ }
1319
+
1320
+ // A camera move, so it goes through the bus like every other one.
1321
+ const bounds = boundsOf(candidates.map((candidate) => candidate.geometry));
1322
+ if (bounds) {
1323
+ holdRejection(this.config.bus.dispatch(context, "studio.map.fitBounds", { bounds }));
1324
+ }
1325
+ }
1326
+
1327
+ /**
1328
+ * stagePick applies one suggested route through the bus, and answers how it ended.
1329
+ *
1330
+ * A tool bus's dispatch never rejects and always answers a result, and a host's own may do
1331
+ * neither: an apply that rejects answers the refusal the bus would have made of the throw, and
1332
+ * one whose answer states no outcome is refused as `internal`.
1333
+ */
1334
+ private async stagePick(seed: number): Promise<ToolResult> {
1335
+ const context = this.config.context;
1336
+
1337
+ try {
1338
+ // The name matters on the append branch only, and names the segment by its place in the
1339
+ // chain; an itinerary still loading carries no segments array.
1340
+ // Read as `unknown` and narrowed at once: a host's bus is held to the result here.
1341
+ const applied: unknown = await this.config.bus.dispatch(
1342
+ context,
1343
+ "studio.itinerary.suggest.applyCandidate",
1344
+ {
1345
+ seed,
1346
+ segmentName: defaultSegmentName(
1347
+ context.ui.getState().activeItinerary?.segments?.length ?? 0,
1348
+ ),
1349
+ },
1350
+ );
1351
+
1352
+ if (isOutcome(applied)) {
1353
+ return applied;
1354
+ }
1355
+
1356
+ return {
1357
+ code: "internal",
1358
+ error: "the apply of a suggested route answered no result",
1359
+ ok: false,
1360
+ };
1361
+ } catch (err) {
1362
+ return failureFromThrown(err);
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * applyPick runs one suggestions-card pick, releasing the card's guard however it ends.
1368
+ *
1369
+ * The apply asks before it drops a staged draft. A reader who keeps theirs (a confirmation
1370
+ * denied or left to expire) refused nothing: the card stays pickable and nothing is written.
1371
+ */
1372
+ private async applyPick(
1373
+ threadId: string,
1374
+ entryId: string,
1375
+ seed: number,
1376
+ label: string,
1377
+ ): Promise<void> {
1378
+ try {
1379
+ const applied = await this.stagePick(seed);
1380
+ // The engine may have parked, or the conversation closed, while the apply was out.
1381
+ if (!this.isOpen(threadId)) {
1382
+ return;
1383
+ }
1384
+
1385
+ if (!applied.ok) {
1386
+ if (isConfirmationWithheld(applied)) {
1387
+ return;
1388
+ }
1389
+
1390
+ this.store
1391
+ .getState()
1392
+ .appendError(threadId, this.config.strings.prompt.suggestionsStageError);
1393
+
1394
+ return;
1395
+ }
1396
+
1397
+ this.store.getState().chooseSuggestion(threadId, entryId, seed);
1398
+ this.send(threadId, label);
1399
+ } finally {
1400
+ this.stagingPicks.delete(entryId);
1401
+ }
1402
+ }
1403
+
1404
+ /**
1405
+ * requestConfirmation parks a thread's decision on its in-chat card. A decision already parked
1406
+ * on the thread is denied first, so no resolver is stranded, and one requested while the
1407
+ * engine is parked, or for a conversation that has closed, is denied at once: no card could
1408
+ * show it.
1409
+ */
1410
+ private requestConfirmation(
1411
+ threadId: string,
1412
+ name: string,
1413
+ summary: string | null,
1414
+ ): Promise<boolean> {
1415
+ if (!this.isOpen(threadId)) {
1416
+ return Promise.resolve(false);
1417
+ }
1418
+
1419
+ return new Promise<boolean>((resolve) => {
1420
+ this.confirmations.get(threadId)?.(false);
1421
+ this.confirmations.set(threadId, resolve);
1422
+ this.store.getState().setPendingConfirmation(threadId, { name, summary });
1423
+ });
1424
+ }
1425
+
1426
+ /** denyPendingConfirmation denies a thread's parked decision, if any, and clears its card. */
1427
+ private denyPendingConfirmation(threadId: string): void {
1428
+ const resolve = this.confirmations.get(threadId);
1429
+ if (resolve !== undefined) {
1430
+ this.confirmations.delete(threadId);
1431
+ resolve(false);
1432
+ }
1433
+
1434
+ this.store.getState().clearPendingConfirmation(threadId);
1435
+ }
1436
+
1437
+ /**
1438
+ * faultsFor binds the shared fault handling to one thread. The missing-organization line
1439
+ * depends on why there is none, read when the fault happens: with nothing open it asks for an
1440
+ * itinerary or a zone, and with a personal one open it says the co-pilot works on an
1441
+ * organization's.
1442
+ */
1443
+ private faultsFor(threadId: string): ConversationFaults {
1444
+ const { context, invalidateAiConfig, invalidateMemberships, onSignInRefused, strings } =
1445
+ this.config;
1446
+ const store = this.store;
1447
+
1448
+ return createConversationFaults({
1449
+ copy: {
1450
+ generic: strings.prompt.errorGeneric,
1451
+ missingOrganization:
1452
+ copilotOrganizationId(context.ui.getState()) === null
1453
+ ? strings.copilot.errorPersonalResource
1454
+ : strings.copilot.errorNoResource,
1455
+ noAccess: strings.copilot.errorNoAccess,
1456
+ notConfigured: strings.copilot.errorNotConfigured,
1457
+ notEntitled: strings.copilot.withheld,
1458
+ rateLimited: strings.prompt.errorRateLimited,
1459
+ tooLarge: strings.prompt.errorTooLarge,
1460
+ },
1461
+ invalidateAiConfig,
1462
+ invalidateMemberships,
1463
+ // A fault that dropped the run id has to reach the URL, or a reload would resume a run
1464
+ // that is gone.
1465
+ onSettled: () => this.syncUrl(),
1466
+ onSignInRefused,
1467
+ writer: {
1468
+ appendError: (message) => store.getState().appendError(threadId, message),
1469
+ setRunId: (runId) => store.getState().setRunId(threadId, runId),
1470
+ // A fault ends the wait for a turn that will not come, so the state it writes (every one
1471
+ // returns the conversation to `awaiting_input`) lands as it is.
1472
+ setSessionState: (state) => {
1473
+ this.awaitingTurn.delete(threadId);
1474
+ this.writeSessionState(threadId, state);
1475
+ },
1476
+ },
1477
+ });
1478
+ }
1479
+
1480
+ /** routeForMessage picks the surfaces a thread's next turn offers, from its message. */
1481
+ private routeForMessage(threadId: string, message: string): void {
1482
+ this.lastRouted.set(threadId, message);
1483
+ this.route(threadId, message);
1484
+ }
1485
+
1486
+ /**
1487
+ * routeForState re-picks from live state, replaying the thread's last message: its words
1488
+ * carry the keyword and skill matches, and dropping them would narrow the manifest at the
1489
+ * moment the run needs it wider.
1490
+ */
1491
+ private routeForState(threadId: string): void {
1492
+ this.route(threadId, this.lastRouted.get(threadId) ?? "");
1493
+ }
1494
+
1495
+ /** route records a thread's pick, with its previous one as the stickiness input. */
1496
+ private route(threadId: string, message: string): void {
1497
+ const decision = selectSurfaces(
1498
+ message,
1499
+ routerStateFrom(this.config.context),
1500
+ this.surfaces.get(threadId) ?? [],
1501
+ );
1502
+ this.surfaces.set(threadId, decision.surfaces);
1503
+ }
1504
+
1505
+ /** openTab opens a conversation, with its host built so the tools and a submit find it. */
1506
+ private openTab(): string {
1507
+ const id = this.ids.next();
1508
+ this.store.getState().addCopilotTab(id);
1509
+ this.ensureHost(id);
1510
+ this.syncUrl();
1511
+
1512
+ return id;
1513
+ }
1514
+
1515
+ /**
1516
+ * closeTab finishes one conversation's run and disposes its session, and the others run on.
1517
+ *
1518
+ * A pending confirmation is denied, and the suggest session is discarded when it is headless
1519
+ * (no draft, no open panel) and this thread staged it or nobody did: a session the human is
1520
+ * using stays, and so does one another conversation owns. Closing the last conversation of an
1521
+ * entitled viewer opens a fresh one, so the strip always carries one.
1522
+ */
1523
+ private closeTab(tabId: string): void {
1524
+ this.hosts.get(tabId)?.finish();
1525
+ this.hosts.delete(tabId);
1526
+ this.surfaces.delete(tabId);
1527
+ this.lastRouted.delete(tabId);
1528
+ this.awaitingTurn.delete(tabId);
1529
+ this.sessionStates.delete(tabId);
1530
+ this.denyPendingConfirmation(tabId);
1531
+
1532
+ const context = this.config.context;
1533
+ const owner = this.suggestBatchOwner;
1534
+ const session = selectSuggestionSession(context.ui.getState());
1535
+ if (
1536
+ session !== null &&
1537
+ !session.draft &&
1538
+ context.ui.getState().openContent !== "suggest" &&
1539
+ (owner === null || owner.threadId === tabId)
1540
+ ) {
1541
+ this.suggestBatchOwner = null;
1542
+ holdRejection(this.config.bus.dispatch(context, "studio.itinerary.suggest.discard", {}));
1543
+ }
1544
+
1545
+ this.store.getState().closeCopilotTab(tabId);
1546
+
1547
+ if (!this.withheld() && this.store.getState().order.length === 0) {
1548
+ this.openTab();
1549
+
1550
+ return;
1551
+ }
1552
+
1553
+ this.syncUrl();
1554
+ }
1555
+
1556
+ /**
1557
+ * showTab points the panel at a tab and mirrors it. The withheld tab is Search for an entitled
1558
+ * viewer, so no caller shows them the host's own content over their conversations.
1559
+ */
1560
+ private showTab(tabId: string): void {
1561
+ this.store
1562
+ .getState()
1563
+ .setActiveTab(tabId === WITHHELD_TAB_ID && !this.withheld() ? SEARCH_TAB_ID : tabId);
1564
+ this.syncUrl();
1565
+ }
1566
+
1567
+ /**
1568
+ * resetThreads clears the co-pilot for a switched-to resource: every conversation closes, so
1569
+ * the one about the resource being left cannot leak into the next, and the panel lands on
1570
+ * Search behind the fresh conversation the last close opens.
1571
+ */
1572
+ private resetThreads(): void {
1573
+ for (const id of [...this.store.getState().order]) {
1574
+ this.closeTab(id);
1575
+ }
1576
+
1577
+ this.showTab(SEARCH_TAB_ID);
1578
+ }
1579
+
1580
+ /**
1581
+ * openOrReveal reveals the co-pilot, focusing a conversation rather than opening a second one:
1582
+ * a withheld viewer lands on the withheld tab, an entitled one on their latest
1583
+ * conversation, and a new one opens only when there is none.
1584
+ */
1585
+ private openOrReveal(): string {
1586
+ if (this.withheld()) {
1587
+ this.showTab(WITHHELD_TAB_ID);
1588
+
1589
+ return WITHHELD_TAB_ID;
1590
+ }
1591
+
1592
+ const existing = this.store.getState().order.at(-1);
1593
+ if (existing !== undefined) {
1594
+ this.showTab(existing);
1595
+
1596
+ return existing;
1597
+ }
1598
+
1599
+ return this.openTab();
1600
+ }
1601
+ }