@sixb/app 0.1.11 → 0.1.13

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 (702) hide show
  1. package/LICENSE +2 -0
  2. package/README.md +27 -26
  3. package/assets/connector-icons/README.md +29 -0
  4. package/assets/connector-icons/ace-iot.ico +0 -0
  5. package/assets/connector-icons/companycam.png +0 -0
  6. package/assets/connector-icons/exa.png +0 -0
  7. package/assets/connector-icons/github.svg +1 -0
  8. package/assets/connector-icons/google.ico +0 -0
  9. package/assets/connector-icons/googleads.svg +29 -0
  10. package/assets/connector-icons/linkedin.svg +1 -0
  11. package/assets/connector-icons/mercury.svg +1 -0
  12. package/assets/connector-icons/meta.svg +1 -0
  13. package/assets/connector-icons/microsoft.ico +0 -0
  14. package/assets/connector-icons/notion.svg +1 -0
  15. package/assets/connector-icons/pandadoc.png +0 -0
  16. package/assets/connector-icons/pennylane.ico +0 -0
  17. package/assets/connector-icons/pipedrive.png +0 -0
  18. package/assets/connector-icons/plaud.png +0 -0
  19. package/assets/connector-icons/quickbooks.svg +1 -0
  20. package/assets/connector-icons/stripe.svg +1 -0
  21. package/assets/connector-icons/teamleader.ico +0 -0
  22. package/assets/connector-icons/tiktok.svg +1 -0
  23. package/assets/connector-icons/unipile.png +0 -0
  24. package/dist/agent/activity-label.d.ts +5 -0
  25. package/dist/agent/activity-label.d.ts.map +1 -0
  26. package/dist/agent/agent-chat.d.ts +25 -0
  27. package/dist/agent/agent-chat.d.ts.map +1 -0
  28. package/dist/agent/agent-context-provider.d.ts +9 -0
  29. package/dist/agent/agent-context-provider.d.ts.map +1 -0
  30. package/dist/agent/agent-execution-trace.d.ts +9 -0
  31. package/dist/agent/agent-execution-trace.d.ts.map +1 -0
  32. package/dist/agent/agent-panel.d.ts +24 -0
  33. package/dist/agent/agent-panel.d.ts.map +1 -0
  34. package/dist/agent/agent-surface-state.d.ts +22 -0
  35. package/dist/agent/agent-surface-state.d.ts.map +1 -0
  36. package/dist/agent/agent-surface.d.ts +46 -0
  37. package/dist/agent/agent-surface.d.ts.map +1 -0
  38. package/dist/agent/agents-page.d.ts +4 -0
  39. package/dist/agent/agents-page.d.ts.map +1 -0
  40. package/dist/agent/artifact-card.d.ts +9 -0
  41. package/dist/agent/artifact-card.d.ts.map +1 -0
  42. package/dist/agent/artifact-panel-state.d.ts +16 -0
  43. package/dist/agent/artifact-panel-state.d.ts.map +1 -0
  44. package/dist/agent/artifact-panel.d.ts +38 -0
  45. package/dist/agent/artifact-panel.d.ts.map +1 -0
  46. package/dist/agent/bash/bash-tool-view.d.ts +17 -0
  47. package/dist/agent/bash/bash-tool-view.d.ts.map +1 -0
  48. package/dist/agent/bash/data.d.ts +35 -0
  49. package/dist/agent/bash/data.d.ts.map +1 -0
  50. package/dist/agent/bash/interpret.d.ts +84 -0
  51. package/dist/agent/bash/interpret.d.ts.map +1 -0
  52. package/dist/agent/bash/renderers.d.ts +31 -0
  53. package/dist/agent/bash/renderers.d.ts.map +1 -0
  54. package/dist/agent/bash/shell.d.ts +16 -0
  55. package/dist/agent/bash/shell.d.ts.map +1 -0
  56. package/dist/agent/components/activity-status.d.ts +13 -0
  57. package/dist/agent/components/activity-status.d.ts.map +1 -0
  58. package/dist/agent/components/agent-thread-switcher.d.ts +16 -0
  59. package/dist/agent/components/agent-thread-switcher.d.ts.map +1 -0
  60. package/dist/agent/components/composer.d.ts +47 -0
  61. package/dist/agent/components/composer.d.ts.map +1 -0
  62. package/dist/agent/components/context-chips.d.ts +7 -0
  63. package/dist/agent/components/context-chips.d.ts.map +1 -0
  64. package/dist/agent/components/context-picker.d.ts +16 -0
  65. package/dist/agent/components/context-picker.d.ts.map +1 -0
  66. package/dist/agent/components/conversation-panel.d.ts +82 -0
  67. package/dist/agent/components/conversation-panel.d.ts.map +1 -0
  68. package/dist/agent/components/file-attachment-card.d.ts +8 -0
  69. package/dist/agent/components/file-attachment-card.d.ts.map +1 -0
  70. package/dist/agent/components/message-parts.d.ts +14 -0
  71. package/dist/agent/components/message-parts.d.ts.map +1 -0
  72. package/dist/agent/components/message-view.d.ts +58 -0
  73. package/dist/agent/components/message-view.d.ts.map +1 -0
  74. package/dist/agent/components/model-controls.d.ts +20 -0
  75. package/dist/agent/components/model-controls.d.ts.map +1 -0
  76. package/dist/agent/components/model-picker-row.d.ts +8 -0
  77. package/dist/agent/components/model-picker-row.d.ts.map +1 -0
  78. package/dist/agent/components/provider-logo.d.ts +6 -0
  79. package/dist/agent/components/provider-logo.d.ts.map +1 -0
  80. package/dist/agent/components/provider-logos.d.ts +3 -0
  81. package/dist/agent/components/provider-logos.d.ts.map +1 -0
  82. package/dist/agent/components/reasoning-effort-slider.d.ts +11 -0
  83. package/dist/agent/components/reasoning-effort-slider.d.ts.map +1 -0
  84. package/dist/agent/components/sandbox-recovery.d.ts +6 -0
  85. package/dist/agent/components/sandbox-recovery.d.ts.map +1 -0
  86. package/dist/agent/components/thread-artifacts-menu.d.ts +8 -0
  87. package/dist/agent/components/thread-artifacts-menu.d.ts.map +1 -0
  88. package/dist/agent/components/transcript.d.ts +36 -0
  89. package/dist/agent/components/transcript.d.ts.map +1 -0
  90. package/dist/agent/components/web-fetch-tool-view.d.ts +5 -0
  91. package/dist/agent/components/web-fetch-tool-view.d.ts.map +1 -0
  92. package/dist/agent/components/web-search-tool-view.d.ts +5 -0
  93. package/dist/agent/components/web-search-tool-view.d.ts.map +1 -0
  94. package/dist/agent/components/web-sources.d.ts +9 -0
  95. package/dist/agent/components/web-sources.d.ts.map +1 -0
  96. package/dist/agent/format.d.ts +12 -0
  97. package/dist/agent/format.d.ts.map +1 -0
  98. package/dist/agent/hooks/use-agent-conversation.d.ts +337 -0
  99. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -0
  100. package/dist/agent/hooks/use-thread-stream.d.ts +22 -0
  101. package/dist/agent/hooks/use-thread-stream.d.ts.map +1 -0
  102. package/dist/agent/i18n/en.d.ts +550 -0
  103. package/dist/agent/i18n/en.d.ts.map +1 -0
  104. package/dist/agent/i18n/fr.d.ts +4 -0
  105. package/dist/agent/i18n/fr.d.ts.map +1 -0
  106. package/dist/agent/i18n/index.d.ts +1079 -0
  107. package/dist/agent/i18n/index.d.ts.map +1 -0
  108. package/dist/agent/live-run.d.ts +48 -0
  109. package/dist/agent/live-run.d.ts.map +1 -0
  110. package/dist/agent/model-selection.d.ts +33 -0
  111. package/dist/agent/model-selection.d.ts.map +1 -0
  112. package/dist/agent/object-context-title.d.ts +22 -0
  113. package/dist/agent/object-context-title.d.ts.map +1 -0
  114. package/dist/agent/parts.d.ts +42 -0
  115. package/dist/agent/parts.d.ts.map +1 -0
  116. package/dist/agent/publish-artifact/interpret.d.ts +32 -0
  117. package/dist/agent/publish-artifact/interpret.d.ts.map +1 -0
  118. package/dist/agent/publish-artifact/publish-artifact-tool-view.d.ts +9 -0
  119. package/dist/agent/publish-artifact/publish-artifact-tool-view.d.ts.map +1 -0
  120. package/dist/agent/publish-artifact/use-live-publishes.d.ts +10 -0
  121. package/dist/agent/publish-artifact/use-live-publishes.d.ts.map +1 -0
  122. package/dist/agent/react-router.d.ts +7 -0
  123. package/dist/agent/react-router.d.ts.map +1 -0
  124. package/dist/agent/read/interpret.d.ts +24 -0
  125. package/dist/agent/read/interpret.d.ts.map +1 -0
  126. package/dist/agent/read/read-tool-view.d.ts +5 -0
  127. package/dist/agent/read/read-tool-view.d.ts.map +1 -0
  128. package/dist/agent/requester-settings.d.ts +15 -0
  129. package/dist/agent/requester-settings.d.ts.map +1 -0
  130. package/dist/agent/run-presentation.d.ts +70 -0
  131. package/dist/agent/run-presentation.d.ts.map +1 -0
  132. package/dist/agent/thread-navigation.d.ts +5 -0
  133. package/dist/agent/thread-navigation.d.ts.map +1 -0
  134. package/dist/agent/types.d.ts +22 -0
  135. package/dist/agent/types.d.ts.map +1 -0
  136. package/dist/agent/utils/context-display.d.ts +5 -0
  137. package/dist/agent/utils/context-display.d.ts.map +1 -0
  138. package/dist/agent/utils/context-mention.d.ts +12 -0
  139. package/dist/agent/utils/context-mention.d.ts.map +1 -0
  140. package/dist/agent/utils/web-fetch.d.ts +4 -0
  141. package/dist/agent/utils/web-fetch.d.ts.map +1 -0
  142. package/dist/agent/utils/web-search.d.ts +20 -0
  143. package/dist/agent/utils/web-search.d.ts.map +1 -0
  144. package/dist/agent/view-file/interpret.d.ts +9 -0
  145. package/dist/agent/view-file/interpret.d.ts.map +1 -0
  146. package/dist/agent/view-file/view-file-tool-view.d.ts +9 -0
  147. package/dist/agent/view-file/view-file-tool-view.d.ts.map +1 -0
  148. package/dist/artifacts/artifact-page.d.ts +7 -0
  149. package/dist/artifacts/artifact-page.d.ts.map +1 -0
  150. package/dist/artifacts/card-details.d.ts +15 -0
  151. package/dist/artifacts/card-details.d.ts.map +1 -0
  152. package/dist/artifacts/card-preview.d.ts +59 -0
  153. package/dist/artifacts/card-preview.d.ts.map +1 -0
  154. package/dist/artifacts/copy-feedback.d.ts +6 -0
  155. package/dist/artifacts/copy-feedback.d.ts.map +1 -0
  156. package/dist/artifacts/file-size.d.ts +11 -0
  157. package/dist/artifacts/file-size.d.ts.map +1 -0
  158. package/dist/artifacts/file-source.d.ts +45 -0
  159. package/dist/artifacts/file-source.d.ts.map +1 -0
  160. package/dist/artifacts/file-view.d.ts +9 -0
  161. package/dist/artifacts/file-view.d.ts.map +1 -0
  162. package/dist/artifacts/frame.d.ts +45 -0
  163. package/dist/artifacts/frame.d.ts.map +1 -0
  164. package/dist/artifacts/gallery.d.ts +6 -0
  165. package/dist/artifacts/gallery.d.ts.map +1 -0
  166. package/dist/artifacts/kind-icon.d.ts +8 -0
  167. package/dist/artifacts/kind-icon.d.ts.map +1 -0
  168. package/dist/artifacts/markdown-tree.d.ts +22 -0
  169. package/dist/artifacts/markdown-tree.d.ts.map +1 -0
  170. package/dist/artifacts/messages.d.ts +301 -0
  171. package/dist/artifacts/messages.d.ts.map +1 -0
  172. package/dist/artifacts/queries.d.ts +21 -0
  173. package/dist/artifacts/queries.d.ts.map +1 -0
  174. package/dist/artifacts/references/embed-tree.d.ts +17 -0
  175. package/dist/artifacts/references/embed-tree.d.ts.map +1 -0
  176. package/dist/artifacts/references/references.d.ts +50 -0
  177. package/dist/artifacts/references/references.d.ts.map +1 -0
  178. package/dist/artifacts/renderers/document-tree.d.ts +11 -0
  179. package/dist/artifacts/renderers/document-tree.d.ts.map +1 -0
  180. package/dist/artifacts/renderers/document.d.ts +17 -0
  181. package/dist/artifacts/renderers/document.d.ts.map +1 -0
  182. package/dist/artifacts/renderers/file.d.ts +10 -0
  183. package/dist/artifacts/renderers/file.d.ts.map +1 -0
  184. package/dist/artifacts/renderers/notice.d.ts +12 -0
  185. package/dist/artifacts/renderers/notice.d.ts.map +1 -0
  186. package/dist/artifacts/renderers/sheet/chart-data.d.ts +33 -0
  187. package/dist/artifacts/renderers/sheet/chart-data.d.ts.map +1 -0
  188. package/dist/artifacts/renderers/sheet/chart.d.ts +15 -0
  189. package/dist/artifacts/renderers/sheet/chart.d.ts.map +1 -0
  190. package/dist/artifacts/renderers/sheet/format.d.ts +35 -0
  191. package/dist/artifacts/renderers/sheet/format.d.ts.map +1 -0
  192. package/dist/artifacts/renderers/sheet/grid.d.ts +25 -0
  193. package/dist/artifacts/renderers/sheet/grid.d.ts.map +1 -0
  194. package/dist/artifacts/renderers/sheet/mini-chart.d.ts +7 -0
  195. package/dist/artifacts/renderers/sheet/mini-chart.d.ts.map +1 -0
  196. package/dist/artifacts/renderers/sheet/model.d.ts +29 -0
  197. package/dist/artifacts/renderers/sheet/model.d.ts.map +1 -0
  198. package/dist/artifacts/renderers/sheet/selection.d.ts +42 -0
  199. package/dist/artifacts/renderers/sheet/selection.d.ts.map +1 -0
  200. package/dist/artifacts/renderers/sheet/sheet.d.ts +17 -0
  201. package/dist/artifacts/renderers/sheet/sheet.d.ts.map +1 -0
  202. package/dist/artifacts/renderers/sheet/virtual.d.ts +13 -0
  203. package/dist/artifacts/renderers/sheet/virtual.d.ts.map +1 -0
  204. package/dist/artifacts/renderers/sheet/workbook.d.ts +24 -0
  205. package/dist/artifacts/renderers/sheet/workbook.d.ts.map +1 -0
  206. package/dist/artifacts/renderers/slides/navigation.d.ts +17 -0
  207. package/dist/artifacts/renderers/slides/navigation.d.ts.map +1 -0
  208. package/dist/artifacts/renderers/slides/slides.d.ts +14 -0
  209. package/dist/artifacts/renderers/slides/slides.d.ts.map +1 -0
  210. package/dist/artifacts/target.d.ts +29 -0
  211. package/dist/artifacts/target.d.ts.map +1 -0
  212. package/dist/artifacts/theme.d.ts +18 -0
  213. package/dist/artifacts/theme.d.ts.map +1 -0
  214. package/dist/artifacts/viewer.d.ts +19 -0
  215. package/dist/artifacts/viewer.d.ts.map +1 -0
  216. package/dist/chunk-3schcf10.js +251 -0
  217. package/dist/chunk-3schcf10.js.map +10 -0
  218. package/dist/chunk-6n5pdqp0.js +115 -0
  219. package/dist/chunk-6n5pdqp0.js.map +11 -0
  220. package/dist/chunk-c7gy61rx.js +276 -0
  221. package/dist/chunk-c7gy61rx.js.map +10 -0
  222. package/dist/chunk-g3f4cm8x.js +20 -0
  223. package/dist/chunk-g3f4cm8x.js.map +10 -0
  224. package/dist/chunk-gn3k23q5.js +149 -0
  225. package/dist/chunk-gn3k23q5.js.map +10 -0
  226. package/dist/chunk-md3p7qdt.js +379 -0
  227. package/dist/chunk-md3p7qdt.js.map +10 -0
  228. package/dist/chunk-ng0hdnrq.js +183 -0
  229. package/dist/chunk-ng0hdnrq.js.map +10 -0
  230. package/dist/chunk-xxpdn63v.js +15018 -0
  231. package/dist/chunk-xxpdn63v.js.map +105 -0
  232. package/dist/chunk-yvhzn4ye.js +98 -0
  233. package/dist/chunk-yvhzn4ye.js.map +10 -0
  234. package/dist/codegen.d.ts +8 -4
  235. package/dist/codegen.d.ts.map +1 -1
  236. package/dist/createCustomApp.d.ts +14 -7
  237. package/dist/createCustomApp.d.ts.map +1 -1
  238. package/dist/index.d.ts +31 -3
  239. package/dist/index.d.ts.map +1 -1
  240. package/dist/index.js +962 -2891
  241. package/dist/index.js.map +14 -13
  242. package/dist/locale-messages.d.ts +74 -6
  243. package/dist/locale-messages.d.ts.map +1 -1
  244. package/dist/locale.d.ts +75 -8
  245. package/dist/locale.d.ts.map +1 -1
  246. package/dist/locale.js +10 -19
  247. package/dist/locale.js.map +3 -4
  248. package/dist/metadata.d.ts.map +1 -1
  249. package/dist/pages/data/connectors.d.ts +5 -0
  250. package/dist/pages/data/connectors.d.ts.map +1 -0
  251. package/dist/pages/data/datasets.d.ts +30 -0
  252. package/dist/pages/data/datasets.d.ts.map +1 -0
  253. package/dist/pages/data/live-updates.d.ts +13 -0
  254. package/dist/pages/data/live-updates.d.ts.map +1 -0
  255. package/dist/pages/data/messages.d.ts +354 -0
  256. package/dist/pages/data/messages.d.ts.map +1 -0
  257. package/dist/pages/data/pipeline-canvas.d.ts +34 -0
  258. package/dist/pages/data/pipeline-canvas.d.ts.map +1 -0
  259. package/dist/pages/data/pipelines.d.ts +9 -0
  260. package/dist/pages/data/pipelines.d.ts.map +1 -0
  261. package/dist/pages/data/projections.d.ts +10 -0
  262. package/dist/pages/data/projections.d.ts.map +1 -0
  263. package/dist/pages/data/schema.d.ts +20 -0
  264. package/dist/pages/data/schema.d.ts.map +1 -0
  265. package/dist/pages/data/shared.d.ts +13 -0
  266. package/dist/pages/data/shared.d.ts.map +1 -0
  267. package/dist/pages/data/sync-button.d.ts +15 -0
  268. package/dist/pages/data/sync-button.d.ts.map +1 -0
  269. package/dist/pages/data/syncs.d.ts +5 -0
  270. package/dist/pages/data/syncs.d.ts.map +1 -0
  271. package/dist/pages/home.d.ts +6 -0
  272. package/dist/pages/home.d.ts.map +1 -0
  273. package/dist/pages/mosaic.d.ts +5 -0
  274. package/dist/pages/mosaic.d.ts.map +1 -0
  275. package/dist/pages/observability/action-run.d.ts +19 -0
  276. package/dist/pages/observability/action-run.d.ts.map +1 -0
  277. package/dist/pages/observability/activity/calendar.d.ts +9 -0
  278. package/dist/pages/observability/activity/calendar.d.ts.map +1 -0
  279. package/dist/pages/observability/activity/connections.d.ts +7 -0
  280. package/dist/pages/observability/activity/connections.d.ts.map +1 -0
  281. package/dist/pages/observability/activity/format.d.ts +11 -0
  282. package/dist/pages/observability/activity/format.d.ts.map +1 -0
  283. package/dist/pages/observability/activity/messages.d.ts +231 -0
  284. package/dist/pages/observability/activity/messages.d.ts.map +1 -0
  285. package/dist/pages/observability/activity/meta-items.d.ts +10 -0
  286. package/dist/pages/observability/activity/meta-items.d.ts.map +1 -0
  287. package/dist/pages/observability/activity/page.d.ts +6 -0
  288. package/dist/pages/observability/activity/page.d.ts.map +1 -0
  289. package/dist/pages/observability/activity/period.d.ts +31 -0
  290. package/dist/pages/observability/activity/period.d.ts.map +1 -0
  291. package/dist/pages/observability/activity/steps.d.ts +44 -0
  292. package/dist/pages/observability/activity/steps.d.ts.map +1 -0
  293. package/dist/pages/observability/activity/timeline.d.ts +36 -0
  294. package/dist/pages/observability/activity/timeline.d.ts.map +1 -0
  295. package/dist/pages/observability/activity/users.d.ts +18 -0
  296. package/dist/pages/observability/activity/users.d.ts.map +1 -0
  297. package/dist/pages/observability/ai-usage/calls.d.ts +27 -0
  298. package/dist/pages/observability/ai-usage/calls.d.ts.map +1 -0
  299. package/dist/pages/observability/ai-usage/charts.d.ts +23 -0
  300. package/dist/pages/observability/ai-usage/charts.d.ts.map +1 -0
  301. package/dist/pages/observability/ai-usage/format.d.ts +101 -0
  302. package/dist/pages/observability/ai-usage/format.d.ts.map +1 -0
  303. package/dist/pages/observability/ai-usage/limits.d.ts +12 -0
  304. package/dist/pages/observability/ai-usage/limits.d.ts.map +1 -0
  305. package/dist/pages/observability/ai-usage/messages.d.ts +431 -0
  306. package/dist/pages/observability/ai-usage/messages.d.ts.map +1 -0
  307. package/dist/pages/observability/ai-usage/page.d.ts +6 -0
  308. package/dist/pages/observability/ai-usage/page.d.ts.map +1 -0
  309. package/dist/pages/observability/live-updates.d.ts +3 -0
  310. package/dist/pages/observability/live-updates.d.ts.map +1 -0
  311. package/dist/pages/observability/logs.d.ts +11 -0
  312. package/dist/pages/observability/logs.d.ts.map +1 -0
  313. package/dist/pages/observability/messages.d.ts +329 -0
  314. package/dist/pages/observability/messages.d.ts.map +1 -0
  315. package/dist/pages/observability/runs.d.ts +7 -0
  316. package/dist/pages/observability/runs.d.ts.map +1 -0
  317. package/dist/pages/observability/workflow-run.d.ts +6 -0
  318. package/dist/pages/observability/workflow-run.d.ts.map +1 -0
  319. package/dist/pages/ontology/actions.d.ts +3 -0
  320. package/dist/pages/ontology/actions.d.ts.map +1 -0
  321. package/dist/pages/ontology/components/action-button.d.ts +12 -0
  322. package/dist/pages/ontology/components/action-button.d.ts.map +1 -0
  323. package/dist/pages/ontology/components/action-param-null-control.d.ts +7 -0
  324. package/dist/pages/ontology/components/action-param-null-control.d.ts.map +1 -0
  325. package/dist/pages/ontology/components/collection-toolbar.d.ts +21 -0
  326. package/dist/pages/ontology/components/collection-toolbar.d.ts.map +1 -0
  327. package/dist/pages/ontology/components/common.d.ts +16 -0
  328. package/dist/pages/ontology/components/common.d.ts.map +1 -0
  329. package/dist/pages/ontology/components/file-ref-upload-field.d.ts +13 -0
  330. package/dist/pages/ontology/components/file-ref-upload-field.d.ts.map +1 -0
  331. package/dist/pages/ontology/components/object-filter-popover.d.ts +9 -0
  332. package/dist/pages/ontology/components/object-filter-popover.d.ts.map +1 -0
  333. package/dist/pages/ontology/components/object-icon.d.ts +7 -0
  334. package/dist/pages/ontology/components/object-icon.d.ts.map +1 -0
  335. package/dist/pages/ontology/components/object-query-bar.d.ts +21 -0
  336. package/dist/pages/ontology/components/object-query-bar.d.ts.map +1 -0
  337. package/dist/pages/ontology/components/telemetry-chart.d.ts +18 -0
  338. package/dist/pages/ontology/components/telemetry-chart.d.ts.map +1 -0
  339. package/dist/pages/ontology/components/telemetry-grid.d.ts +19 -0
  340. package/dist/pages/ontology/components/telemetry-grid.d.ts.map +1 -0
  341. package/dist/pages/ontology/components/telemetry-tile.d.ts +18 -0
  342. package/dist/pages/ontology/components/telemetry-tile.d.ts.map +1 -0
  343. package/dist/pages/ontology/components/telemetry-value.d.ts +10 -0
  344. package/dist/pages/ontology/components/telemetry-value.d.ts.map +1 -0
  345. package/dist/pages/ontology/components/usage-bar.d.ts +12 -0
  346. package/dist/pages/ontology/components/usage-bar.d.ts.map +1 -0
  347. package/dist/pages/ontology/graph.d.ts +6 -0
  348. package/dist/pages/ontology/graph.d.ts.map +1 -0
  349. package/dist/pages/ontology/hooks/object-live-updates.d.ts +5 -0
  350. package/dist/pages/ontology/hooks/object-live-updates.d.ts.map +1 -0
  351. package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts +8 -0
  352. package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts.map +1 -0
  353. package/dist/pages/ontology/hooks/object-type-counts.d.ts +5 -0
  354. package/dist/pages/ontology/hooks/object-type-counts.d.ts.map +1 -0
  355. package/dist/pages/ontology/hooks/rule-live-updates.d.ts +9 -0
  356. package/dist/pages/ontology/hooks/rule-live-updates.d.ts.map +1 -0
  357. package/dist/pages/ontology/hooks/workflow-live-updates.d.ts +6 -0
  358. package/dist/pages/ontology/hooks/workflow-live-updates.d.ts.map +1 -0
  359. package/dist/pages/ontology/lib/action-params.d.ts +55 -0
  360. package/dist/pages/ontology/lib/action-params.d.ts.map +1 -0
  361. package/dist/pages/ontology/lib/format-value.d.ts +3 -0
  362. package/dist/pages/ontology/lib/format-value.d.ts.map +1 -0
  363. package/dist/pages/ontology/lib/labels.d.ts +3 -0
  364. package/dist/pages/ontology/lib/labels.d.ts.map +1 -0
  365. package/dist/pages/ontology/lib/live-update-keys.d.ts +15 -0
  366. package/dist/pages/ontology/lib/live-update-keys.d.ts.map +1 -0
  367. package/dist/pages/ontology/lib/object-query.d.ts +72 -0
  368. package/dist/pages/ontology/lib/object-query.d.ts.map +1 -0
  369. package/dist/pages/ontology/lib/ontology-graph-layout.d.ts +68 -0
  370. package/dist/pages/ontology/lib/ontology-graph-layout.d.ts.map +1 -0
  371. package/dist/pages/ontology/lib/ontology-graph-links.d.ts +4 -0
  372. package/dist/pages/ontology/lib/ontology-graph-links.d.ts.map +1 -0
  373. package/dist/pages/ontology/lib/telemetry-history.d.ts +10 -0
  374. package/dist/pages/ontology/lib/telemetry-history.d.ts.map +1 -0
  375. package/dist/pages/ontology/lib/time.d.ts +3 -0
  376. package/dist/pages/ontology/lib/time.d.ts.map +1 -0
  377. package/dist/pages/ontology/lib/user-preferences.d.ts +8 -0
  378. package/dist/pages/ontology/lib/user-preferences.d.ts.map +1 -0
  379. package/dist/pages/ontology/object-page.d.ts +7 -0
  380. package/dist/pages/ontology/object-page.d.ts.map +1 -0
  381. package/dist/pages/ontology/object-type.d.ts +3 -0
  382. package/dist/pages/ontology/object-type.d.ts.map +1 -0
  383. package/dist/pages/ontology/object-types.d.ts +7 -0
  384. package/dist/pages/ontology/object-types.d.ts.map +1 -0
  385. package/dist/pages/ontology/objects.d.ts +6 -0
  386. package/dist/pages/ontology/objects.d.ts.map +1 -0
  387. package/dist/pages/ontology/rules.d.ts +32 -0
  388. package/dist/pages/ontology/rules.d.ts.map +1 -0
  389. package/dist/pages/ontology/workflow.d.ts +6 -0
  390. package/dist/pages/ontology/workflow.d.ts.map +1 -0
  391. package/dist/pages/ontology/workflows/agent-execution-panel.d.ts +17 -0
  392. package/dist/pages/ontology/workflows/agent-execution-panel.d.ts.map +1 -0
  393. package/dist/pages/ontology/workflows/intervention-panel.d.ts +5 -0
  394. package/dist/pages/ontology/workflows/intervention-panel.d.ts.map +1 -0
  395. package/dist/pages/ontology/workflows/node-execution-panel.d.ts +11 -0
  396. package/dist/pages/ontology/workflows/node-execution-panel.d.ts.map +1 -0
  397. package/dist/pages/ontology/workflows/request-run-dialog.d.ts +5 -0
  398. package/dist/pages/ontology/workflows/request-run-dialog.d.ts.map +1 -0
  399. package/dist/pages/ontology/workflows/run-debug-section.d.ts +11 -0
  400. package/dist/pages/ontology/workflows/run-debug-section.d.ts.map +1 -0
  401. package/dist/pages/ontology/workflows/run-input-form.d.ts +18 -0
  402. package/dist/pages/ontology/workflows/run-input-form.d.ts.map +1 -0
  403. package/dist/pages/ontology/workflows/run-progress.d.ts +15 -0
  404. package/dist/pages/ontology/workflows/run-progress.d.ts.map +1 -0
  405. package/dist/pages/ontology/workflows/schema-shape.d.ts +10 -0
  406. package/dist/pages/ontology/workflows/schema-shape.d.ts.map +1 -0
  407. package/dist/pages/ontology/workflows/status-badge.d.ts +5 -0
  408. package/dist/pages/ontology/workflows/status-badge.d.ts.map +1 -0
  409. package/dist/pages/ontology/workflows/utils.d.ts +29 -0
  410. package/dist/pages/ontology/workflows/utils.d.ts.map +1 -0
  411. package/dist/pages/ontology/workflows/workflow-card.d.ts +5 -0
  412. package/dist/pages/ontology/workflows/workflow-card.d.ts.map +1 -0
  413. package/dist/pages/ontology/workflows.d.ts +3 -0
  414. package/dist/pages/ontology/workflows.d.ts.map +1 -0
  415. package/dist/pages/routes.d.ts +26 -0
  416. package/dist/pages/routes.d.ts.map +1 -0
  417. package/dist/pages/section-page.d.ts +91 -0
  418. package/dist/pages/section-page.d.ts.map +1 -0
  419. package/dist/pages/section-ui.d.ts +212 -0
  420. package/dist/pages/section-ui.d.ts.map +1 -0
  421. package/dist/pages/settings/controls.d.ts +94 -0
  422. package/dist/pages/settings/controls.d.ts.map +1 -0
  423. package/dist/pages/settings/developers.d.ts +3 -0
  424. package/dist/pages/settings/developers.d.ts.map +1 -0
  425. package/dist/pages/settings/members.d.ts +3 -0
  426. package/dist/pages/settings/members.d.ts.map +1 -0
  427. package/dist/pages/settings/messages.d.ts +538 -0
  428. package/dist/pages/settings/messages.d.ts.map +1 -0
  429. package/dist/pages/settings/personal.d.ts +6 -0
  430. package/dist/pages/settings/personal.d.ts.map +1 -0
  431. package/dist/pages/settings/service-accounts.d.ts +3 -0
  432. package/dist/pages/settings/service-accounts.d.ts.map +1 -0
  433. package/dist/pages/settings/sessions.d.ts +3 -0
  434. package/dist/pages/settings/sessions.d.ts.map +1 -0
  435. package/dist/pages/values.d.ts +77 -0
  436. package/dist/pages/values.d.ts.map +1 -0
  437. package/dist/pages.d.ts +45 -0
  438. package/dist/pages.d.ts.map +1 -0
  439. package/dist/pages.js +26029 -0
  440. package/dist/pages.js.map +98 -0
  441. package/dist/runtime.d.ts +0 -2
  442. package/dist/runtime.d.ts.map +1 -1
  443. package/dist/sections/catalog.d.ts +37 -0
  444. package/dist/sections/catalog.d.ts.map +1 -0
  445. package/dist/sections/counts.d.ts +7 -0
  446. package/dist/sections/counts.d.ts.map +1 -0
  447. package/dist/sections/sections.d.ts +67 -0
  448. package/dist/sections/sections.d.ts.map +1 -0
  449. package/dist/server.d.ts +8 -0
  450. package/dist/server.d.ts.map +1 -0
  451. package/dist/server.js +3036 -0
  452. package/dist/server.js.map +19 -0
  453. package/dist/session.d.ts +18 -0
  454. package/dist/session.d.ts.map +1 -0
  455. package/dist/shell/agent-dock.d.ts +7 -0
  456. package/dist/shell/agent-dock.d.ts.map +1 -0
  457. package/dist/shell/app-shell.d.ts +42 -0
  458. package/dist/shell/app-shell.d.ts.map +1 -0
  459. package/dist/shell/brand.d.ts +15 -0
  460. package/dist/shell/brand.d.ts.map +1 -0
  461. package/dist/shell/nav-items.d.ts +34 -0
  462. package/dist/shell/nav-items.d.ts.map +1 -0
  463. package/dist/shell/search-command.d.ts +12 -0
  464. package/dist/shell/search-command.d.ts.map +1 -0
  465. package/dist/shell/section-nav.d.ts +13 -0
  466. package/dist/shell/section-nav.d.ts.map +1 -0
  467. package/dist/shell/user-menu.d.ts +25 -0
  468. package/dist/shell/user-menu.d.ts.map +1 -0
  469. package/dist/tailwind.d.ts +4 -4
  470. package/dist/tailwind.d.ts.map +1 -1
  471. package/package.json +22 -21
  472. package/src/agent/activity-label.ts +70 -0
  473. package/src/agent/agent-chat.tsx +248 -0
  474. package/src/agent/agent-context-provider.tsx +92 -0
  475. package/src/agent/agent-execution-trace.tsx +316 -0
  476. package/src/agent/agent-panel.tsx +74 -0
  477. package/src/agent/agent-surface-state.ts +113 -0
  478. package/src/agent/agent-surface.tsx +363 -0
  479. package/src/agent/agent.css +231 -0
  480. package/src/agent/agents-page.ts +7 -0
  481. package/src/agent/artifact-card.tsx +190 -0
  482. package/src/agent/artifact-panel-state.ts +38 -0
  483. package/src/agent/artifact-panel.tsx +320 -0
  484. package/src/agent/bash/bash-tool-view.tsx +288 -0
  485. package/src/agent/bash/data.ts +137 -0
  486. package/src/agent/bash/interpret.ts +769 -0
  487. package/src/agent/bash/renderers.tsx +503 -0
  488. package/src/agent/bash/shell.ts +195 -0
  489. package/src/agent/components/activity-status.tsx +86 -0
  490. package/src/agent/components/agent-thread-switcher.tsx +346 -0
  491. package/src/agent/components/composer.tsx +870 -0
  492. package/src/agent/components/context-chips.tsx +63 -0
  493. package/src/agent/components/context-picker.tsx +88 -0
  494. package/src/agent/components/conversation-panel.tsx +352 -0
  495. package/src/agent/components/file-attachment-card.tsx +136 -0
  496. package/src/agent/components/message-parts.tsx +305 -0
  497. package/src/agent/components/message-view.tsx +422 -0
  498. package/src/agent/components/model-controls.tsx +204 -0
  499. package/src/agent/components/model-picker-row.tsx +136 -0
  500. package/src/agent/components/provider-logo.tsx +31 -0
  501. package/src/agent/components/provider-logos.ts +24 -0
  502. package/src/agent/components/reasoning-effort-slider.tsx +121 -0
  503. package/src/agent/components/sandbox-recovery.tsx +49 -0
  504. package/src/agent/components/thread-artifacts-menu.tsx +77 -0
  505. package/src/agent/components/transcript.tsx +239 -0
  506. package/src/agent/components/web-fetch-tool-view.tsx +69 -0
  507. package/src/agent/components/web-search-tool-view.tsx +37 -0
  508. package/src/agent/components/web-sources.tsx +159 -0
  509. package/src/agent/format.ts +60 -0
  510. package/src/agent/hooks/use-agent-conversation.ts +536 -0
  511. package/src/agent/hooks/use-thread-stream.ts +121 -0
  512. package/src/agent/i18n/en.ts +500 -0
  513. package/src/agent/i18n/fr.ts +530 -0
  514. package/src/agent/i18n/index.ts +14 -0
  515. package/src/agent/live-run.ts +257 -0
  516. package/src/agent/model-selection.ts +88 -0
  517. package/src/agent/object-context-title.ts +57 -0
  518. package/src/agent/parts.ts +119 -0
  519. package/src/agent/publish-artifact/interpret.ts +110 -0
  520. package/src/agent/publish-artifact/publish-artifact-tool-view.tsx +62 -0
  521. package/src/agent/publish-artifact/use-live-publishes.ts +45 -0
  522. package/src/agent/react-router.tsx +103 -0
  523. package/src/agent/read/interpret.ts +101 -0
  524. package/src/agent/read/read-tool-view.tsx +92 -0
  525. package/src/agent/requester-settings.ts +55 -0
  526. package/src/agent/run-presentation.ts +211 -0
  527. package/src/agent/thread-navigation.ts +11 -0
  528. package/src/agent/types.ts +37 -0
  529. package/src/agent/utils/context-display.ts +72 -0
  530. package/src/agent/utils/context-mention.ts +28 -0
  531. package/src/agent/utils/web-fetch.ts +20 -0
  532. package/src/agent/utils/web-search.ts +106 -0
  533. package/src/agent/view-file/interpret.ts +22 -0
  534. package/src/agent/view-file/view-file-tool-view.tsx +123 -0
  535. package/src/artifacts/artifact-page.tsx +61 -0
  536. package/src/artifacts/artifacts.css +172 -0
  537. package/src/artifacts/card-details.ts +92 -0
  538. package/src/artifacts/card-preview.tsx +612 -0
  539. package/src/artifacts/copy-feedback.ts +25 -0
  540. package/src/artifacts/file-size.ts +24 -0
  541. package/src/artifacts/file-source.ts +109 -0
  542. package/src/artifacts/file-view.ts +57 -0
  543. package/src/artifacts/frame.tsx +288 -0
  544. package/src/artifacts/gallery.tsx +405 -0
  545. package/src/artifacts/kind-icon.tsx +23 -0
  546. package/src/artifacts/markdown-tree.ts +32 -0
  547. package/src/artifacts/messages.ts +317 -0
  548. package/src/artifacts/queries.ts +85 -0
  549. package/src/artifacts/references/embed-tree.ts +86 -0
  550. package/src/artifacts/references/references.tsx +739 -0
  551. package/src/artifacts/renderers/document-tree.ts +157 -0
  552. package/src/artifacts/renderers/document.tsx +334 -0
  553. package/src/artifacts/renderers/file.tsx +160 -0
  554. package/src/artifacts/renderers/notice.tsx +38 -0
  555. package/src/artifacts/renderers/sheet/chart-data.ts +73 -0
  556. package/src/artifacts/renderers/sheet/chart.tsx +288 -0
  557. package/src/artifacts/renderers/sheet/format.ts +142 -0
  558. package/src/artifacts/renderers/sheet/grid.tsx +709 -0
  559. package/src/artifacts/renderers/sheet/mini-chart.tsx +241 -0
  560. package/src/artifacts/renderers/sheet/model.ts +136 -0
  561. package/src/artifacts/renderers/sheet/selection.ts +152 -0
  562. package/src/artifacts/renderers/sheet/sheet.tsx +471 -0
  563. package/src/artifacts/renderers/sheet/virtual.ts +49 -0
  564. package/src/artifacts/renderers/sheet/workbook.ts +57 -0
  565. package/src/artifacts/renderers/slides/navigation.ts +38 -0
  566. package/src/artifacts/renderers/slides/slides.tsx +441 -0
  567. package/src/artifacts/target.ts +76 -0
  568. package/src/artifacts/theme.ts +29 -0
  569. package/src/artifacts/viewer.tsx +476 -0
  570. package/src/build.ts +13 -2
  571. package/src/codegen.ts +98 -80
  572. package/src/createCustomApp.ts +175 -67
  573. package/src/index.ts +47 -16
  574. package/src/locale-messages.ts +128 -12
  575. package/src/locale.ts +1 -2
  576. package/src/metadata.ts +35 -1
  577. package/src/pages/canvas.css +43 -0
  578. package/src/pages/data/connectors.tsx +317 -0
  579. package/src/pages/data/datasets.tsx +731 -0
  580. package/src/pages/data/live-updates.ts +71 -0
  581. package/src/pages/data/messages.ts +349 -0
  582. package/src/pages/data/pipeline-canvas.tsx +288 -0
  583. package/src/pages/data/pipelines.tsx +710 -0
  584. package/src/pages/data/projections.tsx +482 -0
  585. package/src/pages/data/schema.tsx +62 -0
  586. package/src/pages/data/shared.tsx +78 -0
  587. package/src/pages/data/sync-button.tsx +103 -0
  588. package/src/pages/data/syncs.tsx +326 -0
  589. package/src/pages/home.tsx +64 -0
  590. package/src/pages/mosaic.tsx +97 -0
  591. package/src/pages/observability/action-run.tsx +229 -0
  592. package/src/pages/observability/activity/calendar.tsx +239 -0
  593. package/src/pages/observability/activity/connections.tsx +144 -0
  594. package/src/pages/observability/activity/format.ts +49 -0
  595. package/src/pages/observability/activity/messages.ts +255 -0
  596. package/src/pages/observability/activity/meta-items.tsx +23 -0
  597. package/src/pages/observability/activity/page.tsx +605 -0
  598. package/src/pages/observability/activity/period.ts +63 -0
  599. package/src/pages/observability/activity/steps.ts +102 -0
  600. package/src/pages/observability/activity/timeline.tsx +411 -0
  601. package/src/pages/observability/activity/users.tsx +133 -0
  602. package/src/pages/observability/ai-usage/calls.tsx +541 -0
  603. package/src/pages/observability/ai-usage/charts.tsx +126 -0
  604. package/src/pages/observability/ai-usage/format.ts +276 -0
  605. package/src/pages/observability/ai-usage/limits.tsx +629 -0
  606. package/src/pages/observability/ai-usage/messages.ts +446 -0
  607. package/src/pages/observability/ai-usage/page.tsx +814 -0
  608. package/src/pages/observability/live-updates.ts +19 -0
  609. package/src/pages/observability/logs.tsx +617 -0
  610. package/src/pages/observability/messages.ts +336 -0
  611. package/src/pages/observability/runs.tsx +732 -0
  612. package/src/pages/observability/workflow-run.tsx +323 -0
  613. package/src/pages/ontology/actions.tsx +749 -0
  614. package/src/pages/ontology/components/action-button.tsx +355 -0
  615. package/src/pages/ontology/components/action-param-null-control.tsx +35 -0
  616. package/src/pages/ontology/components/collection-toolbar.tsx +61 -0
  617. package/src/pages/ontology/components/common.tsx +60 -0
  618. package/src/pages/ontology/components/file-ref-upload-field.tsx +279 -0
  619. package/src/pages/ontology/components/object-filter-popover.tsx +311 -0
  620. package/src/pages/ontology/components/object-icon.tsx +133 -0
  621. package/src/pages/ontology/components/object-query-bar.tsx +217 -0
  622. package/src/pages/ontology/components/telemetry-chart.tsx +392 -0
  623. package/src/pages/ontology/components/telemetry-grid.tsx +137 -0
  624. package/src/pages/ontology/components/telemetry-tile.tsx +164 -0
  625. package/src/pages/ontology/components/telemetry-value.tsx +91 -0
  626. package/src/pages/ontology/components/usage-bar.tsx +64 -0
  627. package/src/pages/ontology/graph.tsx +1283 -0
  628. package/src/pages/ontology/hooks/object-live-updates.ts +53 -0
  629. package/src/pages/ontology/hooks/object-telemetry-updates.ts +45 -0
  630. package/src/pages/ontology/hooks/object-type-counts.ts +27 -0
  631. package/src/pages/ontology/hooks/rule-live-updates.ts +28 -0
  632. package/src/pages/ontology/hooks/workflow-live-updates.ts +20 -0
  633. package/src/pages/ontology/lib/action-params.ts +231 -0
  634. package/src/pages/ontology/lib/format-value.ts +34 -0
  635. package/src/pages/ontology/lib/labels.ts +50 -0
  636. package/src/pages/ontology/lib/live-update-keys.ts +62 -0
  637. package/src/pages/ontology/lib/object-query.ts +372 -0
  638. package/src/pages/ontology/lib/ontology-graph-layout.ts +1004 -0
  639. package/src/pages/ontology/lib/ontology-graph-links.ts +15 -0
  640. package/src/pages/ontology/lib/telemetry-history.ts +56 -0
  641. package/src/pages/ontology/lib/time.ts +23 -0
  642. package/src/pages/ontology/lib/user-preferences.ts +52 -0
  643. package/src/pages/ontology/object-page.tsx +1029 -0
  644. package/src/pages/ontology/object-type.tsx +910 -0
  645. package/src/pages/ontology/object-types.tsx +240 -0
  646. package/src/pages/ontology/objects.tsx +938 -0
  647. package/src/pages/ontology/rules.tsx +805 -0
  648. package/src/pages/ontology/workflow.tsx +1485 -0
  649. package/src/pages/ontology/workflows/agent-execution-panel.tsx +340 -0
  650. package/src/pages/ontology/workflows/intervention-panel.tsx +261 -0
  651. package/src/pages/ontology/workflows/node-execution-panel.tsx +86 -0
  652. package/src/pages/ontology/workflows/request-run-dialog.tsx +197 -0
  653. package/src/pages/ontology/workflows/run-debug-section.tsx +54 -0
  654. package/src/pages/ontology/workflows/run-input-form.tsx +900 -0
  655. package/src/pages/ontology/workflows/run-progress.tsx +83 -0
  656. package/src/pages/ontology/workflows/schema-shape.tsx +206 -0
  657. package/src/pages/ontology/workflows/status-badge.tsx +15 -0
  658. package/src/pages/ontology/workflows/utils.ts +107 -0
  659. package/src/pages/ontology/workflows/workflow-card.tsx +48 -0
  660. package/src/pages/ontology/workflows.tsx +143 -0
  661. package/src/pages/routes.ts +63 -0
  662. package/src/pages/section-page.tsx +272 -0
  663. package/src/pages/section-ui.tsx +773 -0
  664. package/src/pages/settings/controls.tsx +721 -0
  665. package/src/pages/settings/developers.tsx +163 -0
  666. package/src/pages/settings/members.tsx +1018 -0
  667. package/src/pages/settings/messages.ts +551 -0
  668. package/src/pages/settings/personal.tsx +97 -0
  669. package/src/pages/settings/service-accounts.tsx +623 -0
  670. package/src/pages/settings/sessions.tsx +183 -0
  671. package/src/pages/values.tsx +700 -0
  672. package/src/pages.ts +59 -0
  673. package/src/runtime.ts +0 -3
  674. package/src/sections/catalog.ts +182 -0
  675. package/src/sections/counts.ts +33 -0
  676. package/src/sections/sections.tsx +259 -0
  677. package/src/server.ts +19 -0
  678. package/src/session.ts +29 -0
  679. package/src/shell/agent-dock.tsx +32 -0
  680. package/src/shell/app-shell.tsx +142 -0
  681. package/src/shell/brand.tsx +47 -0
  682. package/src/shell/nav-items.tsx +136 -0
  683. package/src/shell/search-command.tsx +160 -0
  684. package/src/shell/section-nav.tsx +61 -0
  685. package/src/shell/user-menu.tsx +206 -0
  686. package/src/tailwind.ts +4 -4
  687. package/dist/agents.d.ts +0 -11
  688. package/dist/agents.d.ts.map +0 -1
  689. package/dist/agents.js +0 -41
  690. package/dist/agents.js.map +0 -10
  691. package/dist/auth.js +0 -3
  692. package/dist/auth.js.map +0 -9
  693. package/dist/browser.d.ts +0 -3
  694. package/dist/browser.d.ts.map +0 -1
  695. package/dist/browser.js +0 -9
  696. package/dist/browser.js.map +0 -9
  697. package/dist/chunk-cftmy40z.js +0 -70
  698. package/dist/chunk-cftmy40z.js.map +0 -10
  699. package/dist/chunk-e1gj8c1a.js +0 -8
  700. package/dist/chunk-e1gj8c1a.js.map +0 -10
  701. package/src/agents.ts +0 -48
  702. package/src/browser.ts +0 -2
package/dist/index.js CHANGED
@@ -1,2940 +1,1011 @@
1
1
  // @bun
2
2
  import {
3
- publicEnv2
4
- } from "./chunk-e1gj8c1a.js";
3
+ AgentContextProvider2,
4
+ useAgentContext2,
5
+ useRegisteredAgentContext,
6
+ objectHref,
7
+ ARTIFACTS_HREF,
8
+ useAgentMessages,
9
+ Composer2,
10
+ AgentChat,
11
+ AgentChatPage2,
12
+ SyncButton2,
13
+ useCurrentUser2,
14
+ useSignOut2,
15
+ NavItems2,
16
+ isExternal,
17
+ useSectionsEnabled,
18
+ useSections2,
19
+ useCurrentSection2,
20
+ useRegisterSectionNav,
21
+ Brand2
22
+ } from "./chunk-xxpdn63v.js";
5
23
  import {
6
- en,
7
- fr
8
- } from "./chunk-cftmy40z.js";
9
-
10
- // src/createCustomApp.ts
11
- import { randomBytes } from "crypto";
12
- import { watch } from "fs";
13
- import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
14
- import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve3 } from "path";
15
- import { pathToFileURL as pathToFileURL2 } from "url";
16
-
17
- // src/build.ts
18
- import { existsSync } from "fs";
19
- import { copyFile, mkdir, readFile, rm, writeFile } from "fs/promises";
20
- import { basename, dirname, join, resolve } from "path";
21
- import { promisify } from "util";
22
- import {
23
- brotliCompress as brotliCompressCallback,
24
- gzip as gzipCallback,
25
- constants as zlibConstants
26
- } from "zlib";
27
- var STATIC_ASSET_ORIGIN = "https://sixb-static.invalid";
28
- var brotliCompress = promisify(brotliCompressCallback);
29
- var gzip = promisify(gzipCallback);
30
- var PRECOMPRESSION_CONCURRENCY = 4;
31
- var SHARED_APP_SHELL_FILE_NAME = "shared-index.html";
32
- async function buildApp(options) {
33
- const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app");
34
- if (Boolean(options.sharedEntryPath) !== Boolean(options.sharedScriptEntryPath)) {
35
- throw new Error("[SixbCustomApp] sharedEntryPath and sharedScriptEntryPath must be provided together.");
36
- }
37
- await rm(outdir, { recursive: true, force: true });
38
- await mkdir(outdir, { recursive: true });
39
- const result = await buildBrowserEntry(options.scriptEntryPath, outdir, "app");
40
- if (!result.success) {
41
- return {
42
- success: false,
43
- outdir,
44
- logs: result.logs.map(String)
45
- };
46
- }
47
- const normalEntry = resolveBrowserEntry(result.outputs, "browser");
48
- const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"));
49
- const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/;
50
- if (!sourceEntryPattern.test(sourceHtml)) {
51
- throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.");
52
- }
53
- const assetTags = [
54
- ...normalEntry.stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`),
55
- `<script type="module" crossorigin src="/${basename(normalEntry.script.path)}"></script>`
56
- ].join("");
57
- const html = withLoadingShell(sourceHtml).replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
58
- await writeFile(join(outdir, "index.html"), html, "utf-8");
59
- const outputs = [...result.outputs];
60
- if (options.sharedEntryPath && options.sharedScriptEntryPath) {
61
- const sharedResult = await buildBrowserEntry(options.sharedScriptEntryPath, outdir, "shared");
62
- if (!sharedResult.success) {
63
- return {
64
- success: false,
65
- outdir,
66
- logs: sharedResult.logs.map(String)
67
- };
68
- }
69
- const sharedEntry = resolveBrowserEntry(sharedResult.outputs, "shared browser");
70
- const sharedHtml = await renderSharedAppHtml(options.sharedEntryPath, sharedEntry);
71
- await writeFile(join(outdir, SHARED_APP_SHELL_FILE_NAME), sharedHtml, "utf-8");
72
- outputs.push(...sharedResult.outputs);
73
- }
74
- if (options.manifestPath) {
75
- await copyFile(options.manifestPath, join(outdir, "app.webmanifest"));
76
- }
77
- await precompressBuildAssets(outputs);
78
- return { success: true, outdir };
79
- }
80
- async function buildSharedAppDev(options) {
81
- await rm(options.outdir, { recursive: true, force: true });
82
- await mkdir(options.outdir, { recursive: true });
83
- let result;
84
- try {
85
- result = await buildBrowserEntry(options.scriptEntryPath, options.outdir, "shared-dev", true);
86
- } catch (error) {
87
- await rm(options.outdir, { recursive: true, force: true });
88
- throw error;
89
- }
90
- if (!result.success) {
91
- await rm(options.outdir, { recursive: true, force: true });
92
- throw new Error(`[SixbCustomApp] Failed to build the shared development shell: ${result.logs.map(String).join(`
93
- `)}`);
94
- }
95
- const entry = resolveBrowserEntry(result.outputs, "shared development browser");
96
- return {
97
- assetPaths: result.outputs.map((output) => output.path),
98
- html: await renderSharedAppHtml(options.entryPath, entry)
99
- };
100
- }
101
- async function buildBrowserEntry(entrypoint, outdir, entryName, development = false) {
102
- return await Bun.build({
103
- entrypoints: [entrypoint],
104
- outdir,
105
- target: "browser",
106
- conditions: ["bun"],
107
- publicPath: "/",
108
- minify: !development,
109
- splitting: true,
110
- naming: {
111
- entry: `${entryName}-[hash].[ext]`,
112
- chunk: "chunk-[name]-[hash].[ext]",
113
- asset: "asset-[name]-[hash].[ext]"
114
- },
115
- plugins: [extensionlessSourceImportPlugin],
116
- define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
117
- sourcemap: development ? "inline" : "external"
118
- });
119
- }
120
- async function renderSharedAppHtml(entryPath, entry) {
121
- const sourceHtml = restoreAppStaticUrls(await readFile(entryPath, "utf-8"));
122
- const sourceEntryPattern = /const \{ startSharedApp \} = await import\((["'])\.\/shared-main\.tsx\1\)\s+startSharedApp\(bootstrap\)/;
123
- if (!sourceEntryPattern.test(sourceHtml)) {
124
- throw new Error("[SixbCustomApp] Generated shared app shell is missing its ./shared-main.tsx import.");
125
- }
126
- const stylesheetUrls = entry.stylesheets.map((stylesheet) => `/${basename(stylesheet.path)}`);
127
- const bootstrap = [
128
- `const { startSharedApp } = await import(${JSON.stringify(`/${basename(entry.script.path)}`)})`,
129
- ...stylesheetUrls.length > 0 ? [
130
- " startSharedApp(bootstrap, {",
131
- " async loadAppStyles() {",
132
- " await Promise.all(",
133
- ` ${JSON.stringify(stylesheetUrls)}.map((href) => new Promise((resolve) => {`,
134
- ' const link = document.createElement("link")',
135
- ' link.rel = "stylesheet"',
136
- ' link.crossOrigin = "anonymous"',
137
- ' link.addEventListener("load", resolve, { once: true })',
138
- ' link.addEventListener("error", resolve, { once: true })',
139
- " link.href = href",
140
- " document.head.append(link)",
141
- " }))",
142
- " )",
143
- " },",
144
- " })"
145
- ] : [" startSharedApp(bootstrap)"]
146
- ].join(`
147
- `);
148
- return withLoadingShell(sourceHtml).replace(sourceEntryPattern, bootstrap);
149
- }
150
- function resolveBrowserEntry(outputs, label) {
151
- const script = outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
152
- const stylesheets = outputs.filter((output) => output.type.startsWith("text/css"));
153
- if (!script || stylesheets.length > 1) {
154
- throw new Error(`[SixbCustomApp] Expected one ${label} entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
155
- }
156
- return { script, stylesheets };
157
- }
158
- async function buildAuthExperience(options) {
159
- const outdir = resolve(options.outdir);
160
- const assetsDir = join(outdir, "assets");
161
- await rm(outdir, { recursive: true, force: true });
162
- await mkdir(assetsDir, { recursive: true });
163
- const result = await Bun.build({
164
- entrypoints: [options.scriptEntryPath],
165
- outdir: assetsDir,
166
- target: "browser",
167
- conditions: ["bun"],
168
- publicPath: "/auth/assets/",
169
- minify: true,
170
- splitting: true,
171
- naming: {
172
- entry: "auth-[hash].[ext]",
173
- chunk: "chunk-[name]-[hash].[ext]",
174
- asset: "asset-[name]-[hash].[ext]"
175
- },
176
- plugins: [extensionlessSourceImportPlugin],
177
- define: { "process.env.NODE_ENV": '"production"' },
178
- sourcemap: "external"
179
- });
180
- if (!result.success) {
181
- return {
182
- success: false,
183
- outdir,
184
- logs: result.logs.map(String)
185
- };
186
- }
187
- const script = result.outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
188
- const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"));
189
- if (!script || stylesheets.length > 1) {
190
- throw new Error(`[SixbCustomApp] Expected one auth entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
191
- }
192
- const sourceHtml = await readFile(options.entryPath, "utf-8");
193
- const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/auth-main\.tsx["']><\/script>/;
194
- if (!sourceEntryPattern.test(sourceHtml)) {
195
- throw new Error("[SixbCustomApp] Generated auth shell is missing its ./auth-main.tsx entry.");
196
- }
197
- const assetTags = [
198
- ...stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/auth/assets/${basename(stylesheet.path)}">`),
199
- `<script type="module" crossorigin src="/auth/assets/${basename(script.path)}"></script>`
200
- ].join("");
201
- const html = sourceHtml.replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
202
- await writeFile(join(outdir, "index.html"), html, "utf-8");
203
- await precompressBuildAssets(result.outputs);
204
- return { success: true, outdir };
205
- }
206
- async function prepareAppHtmlBundleEntry(entryPath) {
207
- const html = await readFile(entryPath, "utf-8");
208
- const bundleHtml = html.replace(/(<link\s+rel=["'](?:manifest|icon|apple-touch-icon)["']\s+href=["'])(\/[^"']*)(["'][^>]*>)/g, `$1${STATIC_ASSET_ORIGIN}$2$3`);
209
- const entryName = basename(entryPath, ".html");
210
- const bundleEntryPath = join(dirname(entryPath), `${entryName}.sixb-bundle.html`);
211
- await writeFile(bundleEntryPath, bundleHtml, "utf-8");
212
- return bundleEntryPath;
213
- }
214
- function restoreAppStaticUrls(html) {
215
- return html.replaceAll(STATIC_ASSET_ORIGIN, "");
216
- }
217
- function withLoadingShell(html) {
218
- const styles = `<style data-sixb-loading-shell>
219
- .sixb-loading-shell{position:fixed;inset:0;display:grid;place-items:center;background:#fff;color:#71717a}
220
- .sixb-loading-spinner{width:1.25rem;height:1.25rem;border:2px solid currentColor;border-right-color:transparent;border-radius:9999px;animation:sixb-loading-spin .7s linear infinite}
221
- @media(prefers-color-scheme:dark){.sixb-loading-shell{background:#09090b;color:#a1a1aa}}
222
- @media(prefers-reduced-motion:reduce){.sixb-loading-spinner{animation-duration:1.5s}}
223
- @keyframes sixb-loading-spin{to{transform:rotate(360deg)}}
224
- </style>`;
225
- const root = '<div id="root"><div class="sixb-loading-shell" role="status" aria-label="Loading application"><span class="sixb-loading-spinner" aria-hidden="true"></span></div></div>';
226
- if (!html.includes('<div id="root"></div>') || !html.includes("</head>")) {
227
- throw new Error("[SixbCustomApp] Generated app shell is missing its root or head element.");
228
- }
229
- return html.replace("</head>", `${styles}
230
- </head>`).replace('<div id="root"></div>', root);
231
- }
232
- var extensionlessSourceImportPlugin = {
233
- name: "sixb-extensionless-source-imports",
234
- setup(build) {
235
- build.onResolve({ filter: /^\.\.?\/(?:.*\/)?[^/.]+$/ }, (args) => {
236
- const base = resolve(dirname(args.importer), args.path);
237
- for (const candidate of [
238
- `${base}.ts`,
239
- `${base}.tsx`,
240
- `${base}.js`,
241
- `${base}.jsx`,
242
- join(base, "index.ts"),
243
- join(base, "index.tsx"),
244
- join(base, "index.js"),
245
- join(base, "index.jsx")
246
- ]) {
247
- if (existsSync(candidate))
248
- return { path: candidate };
249
- }
250
- return;
251
- });
252
- }
253
- };
254
- async function precompressBuildAssets(outputs) {
255
- const paths = [
256
- ...new Set(outputs.filter((output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")).map((output) => output.path))
257
- ];
258
- let cursor = 0;
259
- const worker = async () => {
260
- while (cursor < paths.length) {
261
- const path = paths[cursor++];
262
- const bytes = await Bun.file(path).arrayBuffer();
263
- const [brotli, gzipped] = await Promise.all([
264
- brotliCompress(bytes, {
265
- params: {
266
- [zlibConstants.BROTLI_PARAM_QUALITY]: 5
267
- }
268
- }),
269
- gzip(bytes, { level: 9 })
270
- ]);
271
- await Promise.all([writeFile(`${path}.br`, brotli), writeFile(`${path}.gz`, gzipped)]);
272
- }
273
- };
274
- await Promise.all(Array.from({ length: Math.min(PRECOMPRESSION_CONCURRENCY, paths.length) }, worker));
275
- }
276
-
277
- // src/codegen.ts
278
- import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
279
- import { join as join4, relative as relative2, resolve as resolve2 } from "path";
280
-
281
- // src/manifest.ts
282
- function renderAppManifest(metadata) {
283
- const manifest = {
284
- id: "/",
285
- name: metadata.title,
286
- ...metadata.description ? { description: metadata.description } : {},
287
- start_url: "/",
288
- scope: "/",
289
- display: "standalone",
290
- theme_color: metadata.themeColor,
291
- background_color: metadata.backgroundColor,
292
- ...metadata.icons.length > 0 ? { icons: metadata.icons } : {}
293
- };
294
- return `${JSON.stringify(manifest, null, 2)}
295
- `;
296
- }
297
-
298
- // src/metadata.ts
299
- import { createHash } from "crypto";
300
- import { readFile as readFile2, stat } from "fs/promises";
301
- import { createRequire } from "module";
302
- import { extname, join as join2 } from "path";
303
- import { pathToFileURL } from "url";
304
- var metadataRequire = createRequire(import.meta.url);
305
- var metadataFields = [
306
- "title",
307
- "description",
308
- "favicon",
309
- "themeColor",
310
- "backgroundColor"
311
- ];
312
- async function resolveAppMetadata(options) {
313
- const configured = await loadConfiguredMetadata(options.layoutPath);
314
- validateMetadata(configured, options.layoutPath);
315
- const conventionalFaviconPath = join2(options.publicDir, "favicon.svg");
316
- const favicon = configured.favicon ?? (await fileExists(conventionalFaviconPath) ? "/favicon.svg" : undefined);
317
- const themeColor = configured.themeColor ?? configured.backgroundColor ?? "#ffffff";
318
- const backgroundColor = configured.backgroundColor ?? themeColor;
319
- const icons = [];
320
- if (await fileExists(join2(options.publicDir, "icon-192.png"))) {
321
- icons.push({
322
- src: "/icon-192.png",
323
- sizes: "192x192",
324
- type: "image/png",
325
- purpose: "any"
326
- });
327
- }
328
- if (await fileExists(join2(options.publicDir, "icon-512.png"))) {
329
- icons.push({
330
- src: "/icon-512.png",
331
- sizes: "512x512",
332
- type: "image/png",
333
- purpose: "any"
334
- });
335
- }
336
- if (await fileExists(join2(options.publicDir, "icon-maskable-512.png"))) {
337
- icons.push({
338
- src: "/icon-maskable-512.png",
339
- sizes: "512x512",
340
- type: "image/png",
341
- purpose: "maskable"
342
- });
343
- }
344
- const hasStandardIcon = icons.some((icon) => icon.purpose === "any");
345
- if (!hasStandardIcon && favicon) {
346
- const type = inferImageMimeType(favicon);
347
- if (type) {
348
- icons.push({
349
- src: favicon,
350
- ...type === "image/svg+xml" ? { sizes: "any" } : {},
351
- type,
352
- purpose: "any"
353
- });
354
- }
355
- }
356
- return {
357
- title: configured.title ?? "Sixb",
358
- ...configured.description ? { description: configured.description } : {},
359
- ...favicon ? { favicon } : {},
360
- themeColor,
361
- backgroundColor,
362
- ...await fileExists(join2(options.publicDir, "apple-touch-icon.png")) ? { appleTouchIcon: "/apple-touch-icon.png" } : {},
363
- icons
364
- };
365
- }
366
- async function loadConfiguredMetadata(layoutPath) {
367
- if (!await fileExists(layoutPath)) {
368
- return {};
369
- }
370
- try {
371
- const sourceHash = createHash("sha256").update(await readFile2(layoutPath)).digest("hex");
372
- const url = pathToFileURL(layoutPath);
373
- delete metadataRequire.cache[metadataRequire.resolve(layoutPath)];
374
- url.searchParams.set("sixb-metadata", sourceHash);
375
- const layoutModule = await import(url.href);
376
- if (layoutModule.metadata === undefined) {
377
- return {};
378
- }
379
- if (typeof layoutModule.metadata !== "object" || layoutModule.metadata === null || Array.isArray(layoutModule.metadata)) {
380
- throw metadataError(layoutPath, "the named metadata export must be an object");
381
- }
382
- return layoutModule.metadata;
383
- } catch (error) {
384
- if (error instanceof Error && error.message.startsWith("[SixbCustomApp]")) {
385
- throw error;
386
- }
387
- const detail = error instanceof Error ? error.message : String(error);
388
- throw new Error(`[SixbCustomApp] Could not load metadata from ${layoutPath}: ${detail}. App metadata is build-time configuration, so app/layout.tsx must be import-safe in Bun and must not access window or document at module scope.`);
389
- }
390
- }
391
- function validateMetadata(metadata, layoutPath) {
392
- for (const field of metadataFields) {
393
- const value = metadata[field];
394
- if (value !== undefined && (typeof value !== "string" || value.trim().length === 0)) {
395
- throw metadataError(layoutPath, `metadata.${field} must be a non-empty string when provided`);
396
- }
397
- }
398
- }
399
- function metadataError(layoutPath, detail) {
400
- return new Error(`[SixbCustomApp] Invalid app metadata in ${layoutPath}: ${detail}`);
401
- }
402
- function inferImageMimeType(url) {
403
- if (url.startsWith("data:")) {
404
- const match = /^data:(image\/[a-z0-9.+-]+)/i.exec(url);
405
- return match?.[1]?.toLowerCase();
406
- }
407
- let pathname = url;
408
- try {
409
- pathname = new URL(url, "https://sixb.invalid").pathname;
410
- } catch {}
411
- switch (extname(pathname).toLowerCase()) {
412
- case ".svg":
413
- return "image/svg+xml";
414
- case ".png":
415
- return "image/png";
416
- case ".ico":
417
- return "image/x-icon";
418
- case ".jpg":
419
- case ".jpeg":
420
- return "image/jpeg";
421
- case ".webp":
422
- return "image/webp";
423
- case ".avif":
424
- return "image/avif";
425
- default:
426
- return;
427
- }
428
- }
429
- async function fileExists(path) {
430
- try {
431
- return (await stat(path)).isFile();
432
- } catch {
433
- return false;
434
- }
435
- }
436
-
437
- // src/runtime.ts
438
- function collectPublicEnv() {
439
- return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[0].startsWith("SIXB_PUBLIC_") && entry[1] !== undefined));
440
- }
441
- function renderCustomAppRuntimeScript(config) {
442
- const safeConfig = JSON.stringify(config).replaceAll("<", "\\u003c");
443
- return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
444
- }
445
-
446
- // src/scanner.ts
447
- import { readdir } from "fs/promises";
448
- import { join as join3, relative } from "path";
449
- var dynamicSegmentPattern = /^\[([\w-]+)\]$/;
450
- var reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb", "/shared"];
451
- var reservedRoutePaths = new Set(["/app.webmanifest"]);
452
- async function scanAppRoutes(appDir) {
453
- const pages = [];
454
- const layouts = [];
455
- await walkDir(appDir, appDir, pages, layouts);
456
- pages.sort(compareRouteModules);
457
- layouts.sort(compareRouteModules);
458
- return { pages, layouts };
459
- }
460
- function routePatternKey(path) {
461
- if (path === "/")
462
- return "/";
463
- const segments = routeSegments(path).map((segment) => segment.startsWith(":") ? ":" : segment.toLowerCase());
464
- return `/${segments.join("/")}`;
465
- }
466
- async function walkDir(dir, appDir, pages, layouts) {
467
- const entries = await readDirectory(dir);
468
- if (!entries)
469
- return;
470
- const visibleEntries = entries.filter((entry) => !String(entry.name).startsWith("_")).sort((a, b) => compareText(String(a.name), String(b.name)));
471
- const relativeDir = normalizeRelativePath(relative(appDir, dir));
472
- validateChildDirectories(visibleEntries, relativeDir);
473
- const pageEntries = visibleEntries.filter((entry) => entry.isFile() && (entry.name === "page.tsx" || entry.name === "page.ts"));
474
- if (pageEntries.length > 1) {
475
- const modules = pageEntries.map((entry) => displayAppPath(join3(relativeDir, entry.name)));
476
- throw new Error(`[SixbCustomApp] Conflicting page modules for route '${directoryRoutePath(relativeDir)}': ${modules.join(" and ")}. Keep exactly one of page.tsx or page.ts.`);
477
- }
478
- const pageEntry = pageEntries[0];
479
- if (pageEntry) {
480
- const relativePath = normalizeRelativePath(join3(relativeDir, pageEntry.name));
481
- const path = directoryRoutePath(relativeDir);
482
- assertRouteIsAvailable(path, relativePath);
483
- pages.push({ path, filePath: join3(dir, pageEntry.name), relativePath });
484
- }
485
- if (relativeDir) {
486
- const layoutEntry = visibleEntries.find((entry) => entry.isFile() && entry.name === "layout.tsx");
487
- if (layoutEntry) {
488
- layouts.push({
489
- path: directoryRoutePath(relativeDir),
490
- filePath: join3(dir, layoutEntry.name),
491
- relativePath: normalizeRelativePath(join3(relativeDir, layoutEntry.name))
492
- });
493
- }
494
- }
495
- for (const entry of visibleEntries) {
496
- if (!entry.isDirectory())
497
- continue;
498
- if (!relativeDir && entry.name === "public")
499
- continue;
500
- await walkDir(join3(dir, entry.name), appDir, pages, layouts);
501
- }
502
- }
503
- async function readDirectory(dir) {
504
- try {
505
- return await readdir(dir, { withFileTypes: true });
506
- } catch (error) {
507
- if (isNotFoundError(error))
508
- return null;
509
- throw error;
510
- }
511
- }
512
- function validateChildDirectories(entries, relativeDir) {
513
- const claimedSegments = new Map;
514
- for (const entry of entries) {
515
- if (!entry.isDirectory())
516
- continue;
517
- if (!relativeDir && entry.name.toLowerCase() === "shared") {
518
- throw new Error("[SixbCustomApp] app/shared is reserved for framework-managed shared links. " + "Move this page to another route.");
519
- }
520
- const segment = routeSegment(entry.name, join3(relativeDir, entry.name));
521
- const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
522
- const existing = claimedSegments.get(key);
523
- if (existing && existing !== entry.name) {
524
- const parent = relativeDir ? displayAppPath(relativeDir) : "app/";
525
- throw new Error(`[SixbCustomApp] Ambiguous route directories '${existing}' and '${entry.name}' under ${parent}. They match the same URL segment.`);
526
- }
527
- claimedSegments.set(key, entry.name);
528
- }
529
- }
530
- function directoryRoutePath(relativeDir) {
531
- if (!relativeDir)
532
- return "/";
533
- return `/${relativeDir.split("/").map((segment) => routeSegment(segment, relativeDir)).join("/")}`;
534
- }
535
- function routeSegment(segment, relativePath) {
536
- const dynamic = dynamicSegmentPattern.exec(segment);
537
- if (dynamic)
538
- return `:${dynamic[1]}`;
539
- if (segment.includes("[") || segment.includes("]")) {
540
- throw new Error(`[SixbCustomApp] Invalid dynamic route directory ${displayAppPath(relativePath)}. Use one name such as '[id]'; catch-all and partial dynamic segments are not supported.`);
541
- }
542
- if (segment.includes("(") || segment.includes(")")) {
543
- throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Route groups are not supported yet; use a normal directory name.`);
544
- }
545
- if (/[:*?]/.test(segment)) {
546
- throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Use '[name]' for a dynamic segment; ':', '*' and '?' are reserved by React Router.`);
547
- }
548
- return segment;
549
- }
550
- function assertRouteIsAvailable(path, relativePath) {
551
- const normalizedPath = path.toLowerCase();
552
- const reserved = reservedRoutePaths.has(normalizedPath) || reservedRoutePrefixes.some((prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`));
553
- if (!reserved)
554
- return;
555
- throw new Error(`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, /shared, and /app.webmanifest.`);
556
- }
557
- function routeSegments(path) {
558
- return path === "/" ? [] : path.replace(/^\/+|\/+$/g, "").split("/");
559
- }
560
- function normalizeRelativePath(path) {
561
- return path.split("\\").join("/").replace(/^\.\/$/, "");
562
- }
563
- function displayAppPath(path) {
564
- const normalized = normalizeRelativePath(path);
565
- return normalized ? `app/${normalized}` : "app/";
566
- }
567
- function compareRouteModules(a, b) {
568
- return compareText(a.path, b.path) || compareText(a.relativePath, b.relativePath);
569
- }
570
- function compareText(a, b) {
571
- return a < b ? -1 : a > b ? 1 : 0;
572
- }
573
- function isNotFoundError(error) {
574
- if (!(error instanceof Error))
575
- return false;
576
- const code = error.code;
577
- return code === "ENOENT" || code === "ENOTDIR";
578
- }
579
-
580
- // src/codegen.ts
581
- function sharedUnavailableTranslations() {
582
- return { en: en.shared.unavailableDetail, fr: fr.shared.unavailableDetail };
583
- }
584
- var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
585
- function assertNoReservedSharedRoutes(routes) {
586
- const reservedRoute = routes.find((route) => route.path === "/shared" || route.path.startsWith("/shared/"));
587
- if (!reservedRoute)
588
- return;
589
- throw new Error(`[SixbCustomApp] ${reservedRoute.relativePath} maps to the reserved ${JSON.stringify(reservedRoute.path)} route. Shared links reuse ordinary app pages; move this page outside app/shared/.`);
590
- }
591
- async function generateRouteManifest(routes, generatedDir, options = {}) {
592
- assertNoReservedSharedRoutes(routes);
593
- await mkdir2(generatedDir, { recursive: true });
594
- const pages = [...routes].sort(compareRouteModules2);
595
- const pageImports = pages.map((route, index) => {
596
- const rel = relativeTo(generatedDir, route.filePath);
597
- return `import Page${index} from ${JSON.stringify(rel)}`;
598
- }).join(`
599
- `);
600
- const projectRoutePatterns = new Set(pages.map((route) => routePatternKey(route.path)));
601
- const builtInRoutes = (options.builtInRoutes ?? []).filter((route) => !projectRoutePatterns.has(routePatternKey(route.path)));
602
- const builtInImports = builtInRoutes.map((route, index) => {
603
- if (route.exportName) {
604
- return `import { ${route.exportName} as BuiltInPage${index} } from ${JSON.stringify(route.moduleSpecifier)}`;
605
- }
606
- return `import BuiltInPage${index} from ${JSON.stringify(route.moduleSpecifier)}`;
607
- }).join(`
608
- `);
609
- const routePatterns = [...pages, ...builtInRoutes].map((route) => routePatternKey(route.path));
610
- const layouts = [...options.layouts ?? []].filter((layout) => {
611
- const layoutPattern = routePatternKey(layout.path);
612
- return routePatterns.some((routePattern) => routePattern === layoutPattern || routePattern.startsWith(`${layoutPattern}/`));
613
- }).sort(compareRouteModules2);
614
- const layoutImports = layouts.map((layout, index) => {
615
- const rel = relativeTo(generatedDir, layout.filePath);
616
- return `import Layout${index} from ${JSON.stringify(rel)}`;
617
- }).join(`
618
- `);
619
- const tree = createRouteTree();
620
- for (const [index, layout] of layouts.entries()) {
621
- insertRouteLayout(tree, layout, `Layout${index}`);
622
- }
623
- for (const [index, route] of pages.entries()) {
624
- insertRoutePage(tree, route.path, `Page${index}`, route.relativePath);
625
- }
626
- for (const [index, route] of builtInRoutes.entries()) {
627
- insertRoutePage(tree, route.path, `BuiltInPage${index}`, `${route.moduleSpecifier} (${route.path})`);
628
- }
629
- const importEntries = [
630
- 'import { createElement } from "react"',
631
- layouts.length > 0 ? 'import { Outlet, type RouteObject } from "react-router-dom"' : 'import type { RouteObject } from "react-router-dom"',
632
- pageImports,
633
- builtInImports,
634
- layoutImports
635
- ].filter(Boolean).join(`
636
- `);
637
- const routePaths = [
638
- ...pages.map((route) => route.path),
639
- ...builtInRoutes.map((route) => route.path)
640
- ];
641
- const content = `${importEntries}
642
-
643
- export const routePaths = ${JSON.stringify(routePaths, null, 2)} as const
644
-
645
- export const routes = [
646
- ${renderRootRouteObjects(tree)}
647
- ] satisfies RouteObject[]
648
- `;
649
- const outPath = join4(generatedDir, "routes.ts");
650
- await writeFileIfChanged(outPath, content);
651
- return outPath;
652
- }
653
- function createRouteTree(segment = "") {
654
- return { segment, children: new Map };
655
- }
656
- function insertRouteLayout(root, layout, componentName) {
657
- if (layout.path === "/") {
658
- throw new Error(`[SixbCustomApp] Root layout ${layout.relativePath} must remain the global app wrapper.`);
659
- }
660
- const node = resolveRouteNode(root, layout.path, layout.relativePath);
661
- if (node.layout) {
662
- throw new Error(`[SixbCustomApp] Conflicting layouts '${node.layout.source}' and '${layout.relativePath}' own route '${layout.path}'.`);
663
- }
664
- node.layout = { componentName, source: layout.relativePath };
665
- }
666
- function insertRoutePage(root, path, componentName, source) {
667
- const node = resolveRouteNode(root, path, source);
668
- if (node.page) {
669
- throw new Error(`[SixbCustomApp] Conflicting pages '${node.page.source}' and '${source}' match route '${path}'.`);
670
- }
671
- node.page = { componentName, source };
672
- }
673
- function resolveRouteNode(root, path, source) {
674
- let node = root;
675
- for (const segment of splitRoutePath(path)) {
676
- const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
677
- const existing = node.children.get(key);
678
- if (existing) {
679
- if (existing.segment.startsWith(":") && segment.startsWith(":") && existing.segment !== segment) {
680
- throw new Error(`[SixbCustomApp] Route '${source}' uses dynamic segment '${segment}', but '${existing.segment}' already owns the same route position. Use one parameter name consistently.`);
681
- }
682
- node = existing;
683
- continue;
684
- }
685
- const child = createRouteTree(segment);
686
- node.children.set(key, child);
687
- node = child;
688
- }
689
- return node;
690
- }
691
- function renderRootRouteObjects(root) {
692
- const lines = [];
693
- if (root.page) {
694
- lines.push(` { path: "/", element: createElement(${root.page.componentName}) },`);
695
- }
696
- for (const child of sortedRenderableChildren(root)) {
697
- lines.push(...renderRouteNode(child, 1));
698
- }
699
- return lines.join(`
700
- `);
701
- }
702
- function renderRouteNode(node, depth) {
703
- const indent = " ".repeat(depth);
704
- const children = sortedRenderableChildren(node);
705
- if (!node.layout && node.page && children.length === 0) {
706
- return [
707
- `${indent}{ path: ${JSON.stringify(node.segment)}, element: createElement(${node.page.componentName}) },`
708
- ];
709
- }
710
- const lines = [`${indent}{`, `${indent} path: ${JSON.stringify(node.segment)},`];
711
- if (node.layout) {
712
- lines.push(`${indent} element: createElement(${node.layout.componentName}, { children: createElement(Outlet) }),`);
713
- }
714
- lines.push(`${indent} children: [`);
715
- if (node.page) {
716
- lines.push(`${indent} { index: true, element: createElement(${node.page.componentName}) },`);
717
- }
718
- for (const child of children) {
719
- lines.push(...renderRouteNode(child, depth + 2));
720
- }
721
- lines.push(`${indent} ],`, `${indent}},`);
722
- return lines;
723
- }
724
- function sortedRenderableChildren(node) {
725
- return [...node.children.values()].filter(hasPageDescendant).sort((a, b) => {
726
- const aDynamic = a.segment.startsWith(":");
727
- const bDynamic = b.segment.startsWith(":");
728
- if (aDynamic !== bDynamic)
729
- return aDynamic ? 1 : -1;
730
- return compareText2(a.segment, b.segment);
731
- });
732
- }
733
- function hasPageDescendant(node) {
734
- if (node.page)
735
- return true;
736
- for (const child of node.children.values()) {
737
- if (hasPageDescendant(child))
738
- return true;
739
- }
740
- return false;
741
- }
742
- function splitRoutePath(path) {
743
- if (path === "/")
744
- return [];
745
- if (!path.startsWith("/")) {
746
- throw new Error(`[SixbCustomApp] Route path '${path}' must start with '/'.`);
747
- }
748
- const segments = path.slice(1).split("/");
749
- if (segments.some((segment) => !segment)) {
750
- throw new Error(`[SixbCustomApp] Route path '${path}' contains an empty segment.`);
751
- }
752
- return segments;
753
- }
754
- function compareRouteModules2(a, b) {
755
- return compareText2(a.path, b.path) || compareText2(a.relativePath, b.relativePath);
756
- }
757
- function compareText2(a, b) {
758
- return a < b ? -1 : a > b ? 1 : 0;
759
- }
760
- async function generateAuthExperienceEntry(projectRoot, generatedDir, options = {}) {
761
- await mkdir2(generatedDir, { recursive: true });
762
- const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
763
- const authPath = join4(appDir, "auth.tsx");
764
- if (!await fileExists2(authPath)) {
765
- return null;
766
- }
767
- const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
768
- const layoutPath = join4(appDir, "layout.tsx");
769
- const globalsCssPath = join4(appDir, "globals.css");
770
- const metadata = await resolveAppMetadata({ layoutPath, publicDir });
771
- const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
772
- const stylesheetImport = stylesheetPath ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}` : "";
773
- const authRel = relativeTo(generatedDir, authPath);
774
- const mainContent = `import React from "react"
775
- import { createRoot } from "react-dom/client"
776
- import type {
777
- AuthExperienceActions,
778
- AuthExperienceState,
779
- } from "@sixb/app/auth"
780
- import AuthExperience from ${JSON.stringify(authRel)}
781
- ${stylesheetImport}
782
-
783
- interface AuthExperienceBootstrap {
784
- readonly state: AuthExperienceState
785
- readonly signInUrl: string
786
- readonly submission?: {
787
- readonly kind: "requestMagicLink" | "confirmSignIn"
788
- readonly action: string
789
- readonly fields: Readonly<Record<string, string>>
790
- }
791
- }
792
-
793
- const root = document.getElementById("root")
794
- if (!root) {
795
- throw new Error("[SixbApp] Could not find the auth experience root element.")
796
- }
797
-
798
- const encodedBootstrap = root.dataset.sixbAuth
799
- if (!encodedBootstrap) {
800
- throw new Error("[SixbApp] Auth experience bootstrap is missing.")
801
- }
802
-
803
- const bootstrap = decodeBootstrap(encodedBootstrap)
804
- const actions: AuthExperienceActions = {
805
- requestMagicLink(email) {
806
- submit("requestMagicLink", { email })
807
- },
808
- confirmSignIn() {
809
- submit("confirmSignIn")
810
- },
811
- restartSignIn() {
812
- window.location.assign(bootstrap.signInUrl)
813
- },
814
- }
815
-
816
- function submit(
817
- kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
818
- additionalFields: Readonly<Record<string, string>> = {}
819
- ): void {
820
- const submission = bootstrap.submission
821
- if (!submission || submission.kind !== kind) {
822
- throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
823
- }
824
-
825
- const form = document.createElement("form")
826
- form.method = "post"
827
- form.action = submission.action
828
- form.hidden = true
829
- for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
830
- const input = document.createElement("input")
831
- input.type = "hidden"
832
- input.name = name
833
- input.value = value
834
- form.append(input)
835
- }
836
- document.body.append(form)
837
- form.submit()
838
- }
839
-
840
- function decodeBootstrap(value: string): AuthExperienceBootstrap {
841
- const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
842
- const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
843
- const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
844
- return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
845
- }
846
-
847
- createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
848
- `;
849
- const mainPath = join4(generatedDir, "auth-main.tsx");
850
- await writeFileIfChanged(mainPath, mainContent);
851
- const htmlContent = `<!DOCTYPE html>
852
- <html lang="en">
853
- <head>
854
- <meta charset="UTF-8" />
855
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
856
- ${renderAuthMetadataHead(metadata)}
857
- <style>
858
- * { box-sizing: border-box; }
859
- html, body, #root { margin: 0; min-height: 100%; }
860
- body, #root { min-height: 100vh; min-height: 100dvh; }
861
- </style>
862
- </head>
863
- <body>
864
- <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
865
- <script type="module" src="./auth-main.tsx"></script>
866
- </body>
867
- </html>
868
- `;
869
- const htmlPath = join4(generatedDir, "auth-index.html");
870
- await writeFileIfChanged(htmlPath, htmlContent);
871
- return { htmlPath, mainPath };
872
- }
873
- async function generateAppEntry(projectRoot, generatedDir, options = {}) {
874
- await mkdir2(generatedDir, { recursive: true });
875
- const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
876
- const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
877
- const globalsCssPath = join4(appDir, "globals.css");
878
- const layoutPath = join4(appDir, "layout.tsx");
879
- const metadata = await resolveAppMetadata({ layoutPath, publicDir });
880
- const manifestPath = join4(generatedDir, "app.webmanifest");
881
- await writeFileIfChanged(manifestPath, renderAppManifest(metadata));
882
- const layoutRel = relativeTo(generatedDir, layoutPath);
883
- const hasLayout = await fileExists2(layoutPath);
884
- const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
885
- const stylesheetPaths = [
886
- ...options.frameworkStylesheetPaths ?? [],
887
- ...stylesheetPath ? [stylesheetPath] : []
888
- ];
889
- const globalsCssImport = stylesheetPaths.map((path) => `import ${JSON.stringify(relativeTo(generatedDir, path))}`).join(`
890
- `);
891
- const layoutImport = hasLayout ? `import RootLayout from ${JSON.stringify(layoutRel)}
892
- ` : "";
893
- const layoutWrapperStart = hasLayout ? "<RootLayout>" : "<>";
894
- const layoutWrapperEnd = hasLayout ? "</RootLayout>" : "</>";
895
- const runtimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
896
- api: { baseUrl: options.apiBaseUrl },
897
- auth: { audience: options.audience ?? "app", enabled: options.authEnabled ?? true }
898
- }) : "";
899
- const runtimeContent = `import React from "react"
900
- import { createRoot, type Root } from "react-dom/client"
901
- import { signOut } from "@sixb/client"
902
- import {
903
- BrowserRouter,
904
- matchPath,
905
- useLocation,
906
- useNavigate,
907
- useRoutes,
908
- } from "react-router-dom"
909
- import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
910
- import { isSixbApiError } from "@sixb/client/browser"
911
- import { getProjectInfoOptions } from "@sixb/client/hooks"
912
- import { LocaleProvider, useAppMessages } from "@sixb/app/locale"
913
- import { routePaths, routes } from "./routes"
914
- ${globalsCssImport}
915
- ${layoutImport}
916
-
917
- interface CustomAppHotData {
918
- root?: Root
919
- queryClient?: QueryClient
920
- }
921
-
922
- export interface StartAppOptions {
923
- readonly basename?: string
924
- }
925
-
926
- if (import.meta.hot) import.meta.hot.accept()
927
-
928
- const queryClient = getQueryClient()
929
-
930
- function getRoot(): Root {
931
- const element = document.getElementById("root")
932
- if (!element) {
933
- throw new Error("[SixbApp] Could not find the root element.")
934
- }
935
-
936
- if (import.meta.hot) {
937
- const data = import.meta.hot.data as CustomAppHotData
938
- data.root ??= createRoot(element)
939
- return data.root
940
- }
941
-
942
- return createRoot(element)
943
- }
944
-
945
- function getQueryClient(): QueryClient {
946
- if (import.meta.hot) {
947
- const data = import.meta.hot.data as CustomAppHotData
948
- data.queryClient ??= createQueryClient()
949
- return data.queryClient
950
- }
951
-
952
- return createQueryClient()
953
- }
954
-
955
- function createQueryClient(): QueryClient {
956
- return new QueryClient({
957
- defaultOptions: {
958
- queries: {
959
- refetchOnWindowFocus: false,
960
- retry: 1,
961
- },
962
- },
963
- })
964
- }
965
-
966
- const RESERVED_PATH_PREFIXES = ["/api", "/auth", "/ws", "/docs", "/shared"]
967
-
968
- function isReservedPath(pathname: string) {
969
- return RESERVED_PATH_PREFIXES.some(
970
- (prefix) => pathname === prefix || pathname.startsWith(prefix + "/")
971
- )
972
- }
973
-
974
- function isSharedTransportPath(pathname: string): boolean {
975
- return pathname === "/shared" || pathname.startsWith("/shared/")
976
- }
977
-
978
- function primaryNavigationAnchor(event: MouseEvent): HTMLAnchorElement | null {
979
- if (event.defaultPrevented) return null
980
- if (event.button !== 0) return null
981
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null
982
-
983
- const target = event.target
984
- if (!(target instanceof Element)) return null
985
- const anchor = target.closest("a")
986
- if (!(anchor instanceof HTMLAnchorElement)) return null
987
- if (anchor.target && anchor.target !== "_self") return null
988
- if (anchor.hasAttribute("download")) return null
989
- if (anchor.relList.contains("external")) return null
990
- if (!anchor.getAttribute("href")) return null
991
- return anchor
992
- }
993
-
994
- // A React Router <Link> mutates the current document before effects can reload it. Capture shared
995
- // transport clicks first so an OIDC document never acquires a bearer fragment.
996
- function SharedDocumentLinkInterceptor({ basename }: { readonly basename?: string }) {
997
- React.useLayoutEffect(() => {
998
- function onClick(event: MouseEvent) {
999
- const anchor = primaryNavigationAnchor(event)
1000
- if (!anchor) return
1001
-
1002
- const url = new URL(anchor.href, window.location.href)
1003
- if (url.origin !== window.location.origin) return
1004
- const appPath = pathInsideApp(url.pathname, basename)
1005
- if (!isSharedTransportPath(appPath)) return
1006
-
1007
- // React Router prefixes an absolute <Link to="/shared/..."> with the current basename.
1008
- // Rebuild the transport URL from the path inside the app so switching grants does not nest
1009
- // the new link beneath /shared/:currentGrantId.
1010
- const documentUrl = new URL(appPath + url.search + url.hash, url.origin)
1011
-
1012
- event.preventDefault()
1013
- event.stopImmediatePropagation()
1014
- window.location.assign(documentUrl.href)
1015
- }
1016
-
1017
- document.addEventListener("click", onClick, true)
1018
- return () => document.removeEventListener("click", onClick, true)
1019
- }, [basename])
1020
-
1021
- return null
1022
- }
1023
-
1024
- // Makes plain same-origin <a href="/..."> clicks navigate client-side, so app
1025
- // authors get SPA navigation without remembering react-router's <Link>.
1026
- // Deliberately conservative: anything unusual falls through to the browser.
1027
- function InternalLinkInterceptor({ basename }: { readonly basename?: string }) {
1028
- const navigate = useNavigate()
1029
-
1030
- React.useEffect(() => {
1031
- function onClick(event: MouseEvent) {
1032
- const anchor = primaryNavigationAnchor(event)
1033
- if (!anchor) return
1034
-
1035
- const url = new URL(anchor.href, window.location.href)
1036
- if (url.origin !== window.location.origin) return
1037
- const appPath = pathInsideApp(url.pathname, basename)
1038
- if (isReservedPath(appPath)) return
1039
- // Only intercept destinations the app actually routes; anything else may
1040
- // be a real server resource and keeps native navigation.
1041
- if (!routePaths.some((path) => matchPath(path, appPath))) return
1042
- // Same-document hash links keep native scroll behavior.
1043
- if (
1044
- url.hash &&
1045
- url.pathname === window.location.pathname &&
1046
- url.search === window.location.search
1047
- ) {
1048
- return
1049
- }
1050
-
1051
- event.preventDefault()
1052
- navigate(appPath + url.search + url.hash)
1053
- }
1054
-
1055
- document.addEventListener("click", onClick)
1056
- return () => document.removeEventListener("click", onClick)
1057
- }, [basename, navigate])
1058
-
1059
- return null
1060
- }
1061
-
1062
- function pathInsideApp(pathname: string, basename: string | undefined): string {
1063
- if (
1064
- basename &&
1065
- (pathname === basename || pathname.startsWith(basename.endsWith("/") ? basename : basename + "/"))
1066
- ) {
1067
- return pathname.slice(basename.length) || "/"
1068
- }
1069
- return pathname
1070
- }
1071
-
1072
- // Programmatic React Router navigation cannot be blocked by BrowserRouter. Gate the ordinary page
1073
- // tree while forcing the new document so no route can run under the previous OIDC authority.
1074
- function SharedDocumentBoundary({ children }: { readonly children: React.ReactNode }) {
1075
- const location = useLocation()
1076
- const crossingBoundary = isSharedTransportPath(location.pathname)
1077
-
1078
- React.useLayoutEffect(() => {
1079
- if (crossingBoundary) window.location.reload()
1080
- }, [crossingBoundary])
1081
-
1082
- return crossingBoundary ? null : children
1083
- }
1084
-
1085
- // Shared presentational fallback used by the not-found view and the error
1086
- // boundary. Styled with @sixb/ui design tokens (var(--token)) so it adopts the
1087
- // app's theme when those tokens are loaded, but every token has a hardcoded
1088
- // fallback so it stays self-contained and readable when they are not. The
1089
- // background/foreground pair is always set together so text stays legible
1090
- // regardless of the surrounding app's background.
1091
- function AppFallback({
1092
- title,
1093
- detail,
1094
- showReload = true,
1095
- action,
1096
- }: {
1097
- title: string
1098
- detail: string
1099
- showReload?: boolean
1100
- action?: React.ReactNode
1101
- }) {
1102
- const messages = useAppMessages()
1103
- return (
1104
- <div
1105
- role="alert"
1106
- style={{
1107
- minHeight: "100dvh",
1108
- display: "flex",
1109
- flexDirection: "column",
1110
- alignItems: "center",
1111
- justifyContent: "center",
1112
- gap: "1rem",
1113
- padding: "2rem",
1114
- textAlign: "center",
1115
- fontFamily:
1116
- "var(--font-sans, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif)",
1117
- background: "var(--background, #ffffff)",
1118
- color: "var(--foreground, #1f2933)",
1119
- }}
1120
- >
1121
- <h1 style={{ margin: 0, fontSize: "1.5rem", fontWeight: 600 }}>{title}</h1>
1122
- <p style={{ margin: 0, maxWidth: "32rem", color: "var(--muted-foreground, #52606d)" }}>
1123
- {detail}
1124
- </p>
1125
- <div style={{ display: "flex", gap: "0.75rem" }}>
1126
- {action ?? (
1127
- <>
1128
- <a
1129
- href="/"
1130
- style={{
1131
- padding: "0.5rem 1rem",
1132
- borderRadius: "var(--radius, 0.5rem)",
1133
- background: "var(--primary, #1f2933)",
1134
- color: "var(--primary-foreground, #ffffff)",
1135
- textDecoration: "none",
1136
- }}
1137
- >
1138
- {messages.goHome}
1139
- </a>
1140
- {showReload ? (
1141
- <button
1142
- type="button"
1143
- onClick={() => window.location.reload()}
1144
- style={{
1145
- padding: "0.5rem 1rem",
1146
- borderRadius: "var(--radius, 0.5rem)",
1147
- border: "1px solid var(--border, #cbd2d9)",
1148
- background: "transparent",
1149
- color: "inherit",
1150
- cursor: "pointer",
1151
- }}
1152
- >
1153
- {messages.reload}
1154
- </button>
1155
- ) : null}
1156
- </>
1157
- )}
1158
- </div>
1159
- </div>
1160
- )
1161
- }
1162
-
1163
- function AccessDeniedView() {
1164
- const messages = useAppMessages().accessDenied
1165
- const [isSigningOut, setIsSigningOut] = React.useState(false)
1166
-
1167
- async function handleSignOut() {
1168
- setIsSigningOut(true)
1169
- try {
1170
- await signOut({ throwOnError: true })
1171
- window.location.reload()
1172
- } catch {
1173
- setIsSigningOut(false)
1174
- }
1175
- }
1176
-
1177
- return (
1178
- <AppFallback
1179
- title={messages.title}
1180
- detail={messages.detail}
1181
- showReload={false}
1182
- action={
1183
- <button
1184
- type="button"
1185
- disabled={isSigningOut}
1186
- onClick={handleSignOut}
1187
- style={{
1188
- padding: "0.5rem 1rem",
1189
- borderRadius: "var(--radius, 0.5rem)",
1190
- border: "1px solid var(--border, #cbd2d9)",
1191
- background: "transparent",
1192
- color: "inherit",
1193
- cursor: isSigningOut ? "default" : "pointer",
1194
- }}
1195
- >
1196
- {isSigningOut ? messages.signingOut : messages.signOut}
1197
- </button>
1198
- }
1199
- />
1200
- )
1201
- }
1202
-
1203
- // The not-found view. Rendered both for unmatched client routes (the catch-all
1204
- // route below) and for an expected 404 surfaced through a query. Apps will be
1205
- // able to override this via app/not-found.tsx.
1206
- function NotFoundView() {
1207
- const messages = useAppMessages().notFound
1208
- return (
1209
- <AppFallback
1210
- title={messages.title}
1211
- detail={messages.detail}
1212
- showReload={false}
1213
- />
1214
- )
1215
- }
1216
-
1217
- // Last-resort safety net so an uncaught render throw (a 404 surfaced through a
1218
- // suspense/throwOnError query, a bug, a failed import) shows a fallback instead
1219
- // of a blank page and a console error. A missing object is an expected state,
1220
- // so a 404 reuses the not-found view rather than the generic crash screen.
1221
- // Apps will be able to override this via app/error.tsx.
1222
- function AppErrorFallback({
1223
- error,
1224
- hideErrorDetails,
1225
- }: {
1226
- error: unknown
1227
- hideErrorDetails: boolean
1228
- }) {
1229
- const messages = useAppMessages().error
1230
- if (isSixbApiError(error) && error.status === 404) {
1231
- return <NotFoundView />
1232
- }
1233
- return (
1234
- <AppFallback
1235
- title={messages.title}
1236
- detail={
1237
- hideErrorDetails
1238
- ? messages.sharedDetail
1239
- : error instanceof Error
1240
- ? error.message
1241
- : String(error)
1242
- }
1243
- />
1244
- )
1245
- }
1246
-
1247
- class AppErrorBoundary extends React.Component<
1248
- { resetKey: string; hideErrorDetails: boolean; children: React.ReactNode },
1249
- { error: unknown }
1250
- > {
1251
- state: { error: unknown } = { error: null }
1252
-
1253
- static getDerivedStateFromError(error: unknown) {
1254
- return { error }
1255
- }
1256
-
1257
- componentDidCatch(error: unknown) {
1258
- if (this.props.hideErrorDetails) {
1259
- console.error("[SixbApp] A shared page failed to render.")
1260
- } else {
1261
- console.error("[SixbApp] Uncaught render error:", error)
1262
- }
1263
- }
1264
-
1265
- // Clear the error when the route changes so navigating away (or an in-app
1266
- // link) recovers without a full reload.
1267
- componentDidUpdate(prevProps: { resetKey: string }) {
1268
- if (this.state.error !== null && prevProps.resetKey !== this.props.resetKey) {
1269
- this.setState({ error: null })
1270
- }
1271
- }
1272
-
1273
- render() {
1274
- if (this.state.error !== null) {
1275
- return (
1276
- <AppErrorFallback
1277
- error={this.state.error}
1278
- hideErrorDetails={this.props.hideErrorDetails}
1279
- />
1280
- )
1281
- }
1282
- return this.props.children
1283
- }
1284
- }
1285
-
1286
- function RoutedErrorBoundary({
1287
- children,
1288
- hideErrorDetails,
1289
- }: {
1290
- children: React.ReactNode
1291
- hideErrorDetails: boolean
1292
- }) {
1293
- const location = useLocation()
1294
- return (
1295
- <AppErrorBoundary
1296
- resetKey={location.pathname + location.search}
1297
- hideErrorDetails={hideErrorDetails}
1298
- >
1299
- {children}
1300
- </AppErrorBoundary>
1301
- )
1302
- }
1303
-
1304
- const appRoutes = [...routes, { path: "*", element: <NotFoundView /> }]
1305
-
1306
- function AppRoutes() {
1307
- return useRoutes(appRoutes)
1308
- }
1309
-
1310
- function RoutedApp({ hideErrorDetails }: { readonly hideErrorDetails: boolean }) {
1311
- return (
1312
- <RoutedErrorBoundary hideErrorDetails={hideErrorDetails}>
1313
- ${layoutWrapperStart}
1314
- <AppRoutes />
1315
- ${layoutWrapperEnd}
1316
- </RoutedErrorBoundary>
1317
- )
1318
- }
1319
-
1320
- // Project settings do not change while the app runs: never refetch or collect them. Built on use:
1321
- // the query key captures the API base URL, which the bootstrap configures after this module loads.
1322
- function projectInfoQuery() {
1323
- return {
1324
- ...getProjectInfoOptions(),
1325
- staleTime: Number.POSITIVE_INFINITY,
1326
- gcTime: Number.POSITIVE_INFINITY,
1327
- retry: false,
1328
- }
1329
- }
1330
-
1331
- // Framework text follows the reader's browser languages and falls back to the project's. A shared
1332
- // link's grant cannot read project settings, so it keeps the browser's languages alone.
1333
- function ProjectLocale({
1334
- shared,
1335
- children,
1336
- }: {
1337
- readonly shared: boolean
1338
- readonly children: React.ReactNode
1339
- }) {
1340
- const { data: project } = useQuery({ ...projectInfoQuery(), enabled: !shared })
1341
- return <LocaleProvider fallbackLocale={project?.locale}>{children}</LocaleProvider>
1342
- }
1343
-
1344
- function App({ basename }: StartAppOptions) {
1345
- return (
1346
- <QueryClientProvider client={queryClient}>
1347
- <ProjectLocale shared={Boolean(basename)}>
1348
- <BrowserRouter basename={basename}>
1349
- <SharedDocumentLinkInterceptor basename={basename} />
1350
- <InternalLinkInterceptor basename={basename} />
1351
- {basename ? (
1352
- <RoutedApp hideErrorDetails />
1353
- ) : (
1354
- <SharedDocumentBoundary>
1355
- <RoutedApp hideErrorDetails={false} />
1356
- </SharedDocumentBoundary>
1357
- )}
1358
- </BrowserRouter>
1359
- </ProjectLocale>
1360
- </QueryClientProvider>
1361
- )
1362
- }
1363
-
1364
- export function startApp(options: StartAppOptions = {}) {
1365
- // The HTML is built without loading the project: declare the project's language on the document
1366
- // as soon as the API answers, without waiting for the page tree to render.
1367
- if (!options.basename) {
1368
- void queryClient.fetchQuery(projectInfoQuery()).then(
1369
- (project) => {
1370
- document.documentElement.lang = project.locale
1371
- },
1372
- () => undefined
1373
- )
1374
- }
1375
- getRoot().render(<App basename={options.basename} />)
1376
- }
1377
-
1378
- // Without a session the project's locale is unknown: these speak the browser's language.
1379
- export function renderAccessDenied() {
1380
- getRoot().render(
1381
- <LocaleProvider>
1382
- <AccessDeniedView />
1383
- </LocaleProvider>
1384
- )
1385
- }
1386
-
1387
- export function renderApiUnavailable(apiBaseUrl: string) {
1388
- getRoot().render(
1389
- <LocaleProvider>
1390
- <ApiUnavailableView apiBaseUrl={apiBaseUrl} />
1391
- </LocaleProvider>
1392
- )
1393
- }
1394
-
1395
- function ApiUnavailableView({ apiBaseUrl }: { readonly apiBaseUrl: string }) {
1396
- const messages = useAppMessages()
1397
- return (
1398
- <AppFallback
1399
- title={messages.apiUnavailable.title}
1400
- detail={messages.apiUnavailable.detail(apiBaseUrl)}
1401
- action={
1402
- <button
1403
- type="button"
1404
- onClick={() => window.location.reload()}
1405
- style={{
1406
- padding: "0.5rem 1rem",
1407
- borderRadius: "var(--radius, 0.5rem)",
1408
- border: "1px solid var(--border, #cbd2d9)",
1409
- background: "transparent",
1410
- color: "inherit",
1411
- cursor: "pointer",
1412
- }}
1413
- >
1414
- {messages.retry}
1415
- </button>
1416
- }
1417
- />
1418
- )
1419
- }
1420
- `;
1421
- const runtimePath = join4(generatedDir, "app-runtime.tsx");
1422
- await writeFileIfChanged(runtimePath, runtimeContent);
1423
- const mainContent = `import {
1424
- configureSixbBrowserClient,
1425
- readSixbBrowserRuntimeConfig,
1426
- requireSixbBrowserAuthSession,
1427
- } from "@sixb/client/browser"
1428
- import { renderAccessDenied, renderApiUnavailable, startApp } from "./app-runtime"
1429
-
1430
- const runtimeConfig = readSixbBrowserRuntimeConfig({ audience: "app" })
1431
- const browserClient = configureSixbBrowserClient(runtimeConfig)
1432
-
1433
- if (import.meta.hot) {
1434
- import.meta.hot.accept()
1435
- import.meta.hot.dispose(() => browserClient.dispose())
1436
- }
1437
-
1438
- // Without the API's answer the app can neither render nor send the user to sign in.
1439
- const authSession = runtimeConfig.auth.enabled
1440
- ? await requireSixbBrowserAuthSession(runtimeConfig, browserClient).catch((error: unknown) => {
1441
- console.error("[SixbCustomApp] Could not load the session from the API:", error)
1442
- return "unavailable" as const
1443
- })
1444
- : null
1445
-
1446
- if (authSession === "unavailable") {
1447
- renderApiUnavailable(runtimeConfig.api.baseUrl)
1448
- } else if (
1449
- !runtimeConfig.auth.enabled ||
1450
- (authSession?.authenticated === false && authSession.authEnabled === false) ||
1451
- (authSession?.authenticated === true && authSession.applicationAccess.allowed)
1452
- ) {
1453
- startApp()
1454
- } else if (authSession?.authenticated === true && !authSession.applicationAccess.allowed) {
1455
- renderAccessDenied()
1456
- }
1457
- `;
1458
- const mainPath = join4(generatedDir, "main.tsx");
1459
- await writeFileIfChanged(mainPath, mainContent);
1460
- const sharedMainContent = `import { browserAppLocale, browserAppMessages } from "@sixb/app/locale"
1461
- import {
1462
- configureSixbSharedBrowserClient,
1463
- isSixbApiError,
1464
- readSixbBrowserRuntimeConfig,
1465
- type SixbSharedBrowserClientController,
1466
- } from "@sixb/client/browser"
1467
-
1468
- export interface SharedAppBootstrap {
1469
- readonly basename: string
1470
- readonly grantId: string
1471
- readonly requestedPath: string
1472
- readonly secret: string | null
1473
- }
1474
-
1475
- export interface SharedAppStartOptions {
1476
- readonly loadAppStyles?: () => Promise<void>
1477
- }
1478
-
1479
- let activeController: SixbSharedBrowserClientController | null = null
1480
-
1481
- if (import.meta.hot) {
1482
- import.meta.hot.accept()
1483
- import.meta.hot.dispose(() => {
1484
- activeController?.dispose()
1485
- activeController = null
1486
- })
1487
- }
1488
-
1489
- export function startSharedApp(
1490
- bootstrap: SharedAppBootstrap,
1491
- options: SharedAppStartOptions = {}
1492
- ): void {
1493
- // A shared link speaks the reader's language: the grant cannot read the project's.
1494
- document.documentElement.lang = browserAppLocale()
1495
- if (!isValidBootstrap(bootstrap)) {
1496
- renderSharedFallback("unavailable")
1497
- return
1498
- }
1499
- const { basename, grantId } = bootstrap
1500
- let loadAppStyles = options.loadAppStyles
1501
-
1502
- activeController?.dispose()
1503
- let controller: SixbSharedBrowserClientController
1504
- try {
1505
- const runtimeConfig = readSixbBrowserRuntimeConfig({
1506
- audience: "app",
1507
- authEnabled: false,
1508
- })
1509
- controller = configureSixbSharedBrowserClient(runtimeConfig, {
1510
- grantId,
1511
- })
1512
- activeController = controller
1513
- } catch {
1514
- renderSharedFallback("unavailable")
1515
- return
1516
- }
1517
-
1518
- let secret = bootstrap.secret
1519
- let canonicalDestinationPath: string | null = null
1520
- let appStylesLoaded = false
1521
- let pending = false
1522
-
1523
- const open = async () => {
1524
- if (pending) return
1525
- pending = true
1526
- renderSharedFallback("loading")
1527
-
1528
- try {
1529
- const exchangedSecret = secret !== null
1530
- const session = await controller.establish(secret)
1531
- // Once a server session exists the one-time link credential must not survive a retry.
1532
- secret = null
1533
- if (exchangedSecret) canonicalDestinationPath = session.destinationPath
1534
- // Keep the trusted destination pending until this document is canonical or a hard
1535
- // navigation to it has started. Application code never imports under the caller's path.
1536
- if (canonicalDestinationPath !== null) {
1537
- try {
1538
- if (!canonicalizeInitialDestination(basename, canonicalDestinationPath)) return
1539
- } catch (error) {
1540
- // Both same-document canonicalization and the hard-navigation fallback failed. Retire
1541
- // the newly established session before showing a terminal error so a reload cannot
1542
- // restore it under the caller-controlled path.
1543
- await controller.signOut().catch(() => undefined)
1544
- controller.dispose()
1545
- if (activeController === controller) activeController = null
1546
- throw error
1547
- }
1548
- canonicalDestinationPath = null
1549
- }
1550
- if (!appStylesLoaded) {
1551
- await loadAppStyles?.()
1552
- loadAppStyles = undefined
1553
- appStylesLoaded = true
1554
- }
1555
-
1556
- const { startApp } = await import("./app-runtime")
1557
- startApp({ basename })
1558
- } catch (error) {
1559
- if (isRetryableSharedFailure(error)) {
1560
- console.error("[SixbSharedApp] Shared access could not be opened; retry is available.")
1561
- renderSharedFallback("retryable", () => void open())
1562
- } else {
1563
- renderSharedFallback("unavailable")
1564
- }
1565
- } finally {
1566
- pending = false
1567
- }
1568
- }
1569
-
1570
- void open()
24
+ useAppMessages2
25
+ } from "./chunk-g3f4cm8x.js";
26
+
27
+ // src/index.ts
28
+ import { agentContext } from "@sixb/core/agents/context";
29
+
30
+ // src/agent/agent-panel.tsx
31
+ import { cn } from "@sixb/ui/lib/utils";
32
+ import { useCallback, useState } from "react";
33
+ import { jsx } from "react/jsx-runtime";
34
+ function AgentPanel({
35
+ context,
36
+ threadId: controlledThreadId,
37
+ defaultThreadId = null,
38
+ onThreadChange,
39
+ onNewThread,
40
+ artifactHost,
41
+ splitArtifacts,
42
+ conversationHeaderActions,
43
+ composerPlaceholder,
44
+ compact = true,
45
+ className,
46
+ welcomeContent
47
+ }) {
48
+ const registeredContext = useRegisteredAgentContext();
49
+ const ambientContext = context === undefined ? registeredContext : context;
50
+ const controlled = controlledThreadId !== undefined;
51
+ const [localThreadId, setLocalThreadId] = useState(defaultThreadId);
52
+ const threadId = controlled ? controlledThreadId : localThreadId;
53
+ const changeThread = useCallback((nextThreadId) => {
54
+ if (!controlled)
55
+ setLocalThreadId(nextThreadId);
56
+ onThreadChange?.(nextThreadId);
57
+ }, [controlled, onThreadChange]);
58
+ return /* @__PURE__ */ jsx(AgentChat, {
59
+ threadId,
60
+ ambientContext,
61
+ compact,
62
+ artifactHost,
63
+ splitArtifacts,
64
+ conversationHeaderActions,
65
+ composerPlaceholder,
66
+ welcomeContent,
67
+ onNavigateHome: () => {
68
+ changeThread(null);
69
+ onNewThread?.();
70
+ },
71
+ onNavigateThread: changeThread,
72
+ className: cn("min-h-0 overflow-hidden bg-background", className)
73
+ });
1571
74
  }
1572
-
1573
- function isValidBootstrap(value: SharedAppBootstrap): boolean {
1574
- return (
1575
- typeof value.grantId === "string" &&
1576
- value.basename === "/shared/" + encodeURIComponent(value.grantId) &&
1577
- value.requestedPath.startsWith("/") &&
1578
- (value.secret === null || typeof value.secret === "string")
1579
- )
75
+ // src/agent/agent-surface.tsx
76
+ import { Button } from "@sixb/ui/components";
77
+ import { cn as cn2 } from "@sixb/ui/lib/utils";
78
+ import { ChevronRight, Maximize2, MessageSquareText, Minimize2 } from "lucide-react";
79
+ import {
80
+ useCallback as useCallback2,
81
+ useEffect,
82
+ useRef,
83
+ useState as useState2
84
+ } from "react";
85
+
86
+ // src/agent/agent-surface-state.ts
87
+ var DEFAULT_AGENT_SURFACE_WIDTH = 384;
88
+ var MIN_AGENT_SURFACE_WIDTH = 320;
89
+ var MAX_AGENT_SURFACE_WIDTH = 720;
90
+ var AGENT_SURFACE_STATE_EVENT = "sixb:agent-surface-state";
91
+ function agentSurfaceSessionStorageKey(override) {
92
+ if (override === false)
93
+ return null;
94
+ return override ?? "sixb.agent-ui.surface.v1:agents";
1580
95
  }
1581
-
1582
- function canonicalizeInitialDestination(basename: string, destinationPath: string): boolean {
1583
- const canonicalPath = basename + destinationPath
1584
- if (
1585
- window.location.pathname !== canonicalPath ||
1586
- window.location.search !== "" ||
1587
- window.location.hash !== ""
1588
- ) {
1589
- try {
1590
- window.history.replaceState(window.history.state, "", canonicalPath)
1591
- } catch {
1592
- // Preserve the authority boundary even when a browser or embedding policy denies History
1593
- // mutation: a fresh document at the trusted server destination is still safe.
1594
- window.location.replace(canonicalPath)
1595
- return false
1596
- }
96
+ function parseAgentSurfaceSessionState(raw, defaults, minimumWidth = MIN_AGENT_SURFACE_WIDTH, maximumWidth = MAX_AGENT_SURFACE_WIDTH) {
97
+ if (!raw)
98
+ return defaults;
99
+ try {
100
+ const value = JSON.parse(raw);
101
+ if (!isRecord(value))
102
+ return defaults;
103
+ return {
104
+ mode: value.mode === "collapsed" || value.mode === "dock" ? value.mode : defaults.mode,
105
+ dockWidth: typeof value.dockWidth === "number" && Number.isFinite(value.dockWidth) ? clampAgentSurfaceWidth(value.dockWidth, minimumWidth, maximumWidth) : defaults.dockWidth,
106
+ threadId: value.threadId === null || typeof value.threadId === "string" && value.threadId.length > 0 ? value.threadId : defaults.threadId
107
+ };
108
+ } catch {
109
+ return defaults;
1597
110
  }
1598
- return true
1599
- }
1600
-
1601
- function isRetryableSharedFailure(error: unknown): boolean {
1602
- if (error instanceof TypeError) return true
1603
- return (
1604
- isSixbApiError(error) &&
1605
- (error.status === 408 || error.status === 429 || error.status >= 500)
1606
- )
1607
111
  }
1608
-
1609
- function renderSharedFallback(
1610
- state: "loading" | "retryable" | "unavailable",
1611
- retry?: () => void
1612
- ): void {
1613
- const root = document.getElementById("root")
1614
- if (!root) return
1615
-
1616
- const main = document.createElement("main")
1617
- main.setAttribute("role", state === "loading" ? "status" : "alert")
1618
- main.style.cssText =
1619
- "min-height:100dvh;display:flex;flex-direction:column;align-items:center;" +
1620
- "justify-content:center;gap:.75rem;padding:2rem;text-align:center;" +
1621
- "font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
1622
-
1623
- const messages = browserAppMessages().shared
1624
- const title = document.createElement("h1")
1625
- title.style.cssText = "margin:0;font-size:1.5rem"
1626
- title.textContent =
1627
- state === "loading"
1628
- ? messages.opening
1629
- : state === "retryable"
1630
- ? messages.retryableTitle
1631
- : messages.unavailableTitle
1632
- const detail = document.createElement("p")
1633
- detail.style.cssText = "margin:0;max-width:32rem"
1634
- detail.textContent =
1635
- state === "loading"
1636
- ? messages.verifying
1637
- : state === "retryable"
1638
- ? messages.retryableDetail
1639
- : messages.unavailableDetail
1640
- main.append(title, detail)
1641
-
1642
- if (retry) {
1643
- const button = document.createElement("button")
1644
- button.type = "button"
1645
- button.textContent = messages.tryAgain
1646
- button.style.cssText =
1647
- "margin-top:.25rem;padding:.625rem 1rem;border:1px solid currentColor;" +
1648
- "border-radius:.375rem;background:transparent;color:inherit;cursor:pointer;font:inherit"
1649
- button.addEventListener("click", retry, { once: true })
1650
- main.append(button)
1651
- }
1652
-
1653
- root.replaceChildren(main)
112
+ function clampAgentSurfaceWidth(width, minimumWidth, maximumWidth) {
113
+ return Math.min(Math.max(Math.round(width), minimumWidth), maximumWidth);
1654
114
  }
1655
- `;
1656
- const sharedMainPath = join4(generatedDir, "shared-main.tsx");
1657
- await writeFileIfChanged(sharedMainPath, sharedMainContent);
1658
- const metadataHead = renderMetadataHead(metadata);
1659
- const htmlContent = `<!DOCTYPE html>
1660
- <html lang="en">
1661
- <head>
1662
- <meta charset="UTF-8" />
1663
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
1664
- ${metadataHead}
1665
- ${runtimeConfigScript}
1666
- <style>
1667
- * {
1668
- box-sizing: border-box;
1669
- }
1670
- html,
1671
- body,
1672
- #root {
1673
- margin: 0;
1674
- min-height: 100%;
1675
- }
1676
- body,
1677
- #root {
1678
- min-height: 100vh;
1679
- min-height: 100dvh;
1680
- }
1681
- @media (display-mode: standalone) {
1682
- html,
1683
- body {
1684
- overscroll-behavior: none;
1685
- }
1686
- }
1687
- </style>
1688
- </head>
1689
- <body>
1690
- <div id="root"></div>
1691
- <script type="module" src="./main.tsx"></script>
1692
- </body>
1693
- </html>
1694
- `;
1695
- const htmlPath = join4(generatedDir, "index.html");
1696
- await writeFileIfChanged(htmlPath, htmlContent);
1697
- const sharedRuntimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
1698
- api: { baseUrl: options.apiBaseUrl },
1699
- auth: { audience: "app", enabled: false }
1700
- }) : "";
1701
- const sharedHtmlContent = `<!DOCTYPE html>
1702
- <html lang="en">
1703
- <head>
1704
- <meta charset="UTF-8" />
1705
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
1706
- <meta name="robots" content="noindex, nofollow, noarchive" />
1707
- <meta name="referrer" content="no-referrer" />
1708
- ${renderSharedMetadataHead(metadata)}
1709
- ${sharedRuntimeConfigScript}
1710
- <style>
1711
- * { box-sizing: border-box; }
1712
- html, body, #root { margin: 0; min-height: 100%; }
1713
- body, #root { min-height: 100vh; min-height: 100dvh; }
1714
- </style>
1715
- </head>
1716
- <body>
1717
- <div id="root"></div>
1718
- <script>
1719
- function renderUnavailable() {
1720
- const root = document.getElementById("root")
1721
- if (!root) return
1722
- const main = document.createElement("main")
1723
- main.setAttribute("role", "alert")
1724
- main.style.cssText =
1725
- "min-height:100dvh;display:grid;place-items:center;padding:2rem;text-align:center;" +
1726
- "font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
1727
- const message = document.createElement("p")
1728
- // Inline and dependency-free: the translations travel with the page.
1729
- const translations = ${JSON.stringify(sharedUnavailableTranslations())}
1730
- const language = (navigator.languages || [navigator.language])
1731
- .map((tag) => String(tag).split("-")[0].toLowerCase())
1732
- .find((tag) => tag in translations)
1733
- document.documentElement.lang = language || "en"
1734
- message.textContent = translations[language || "en"]
1735
- main.append(message)
1736
- root.replaceChildren(main)
1737
- }
1738
-
1739
- function consumeBootstrap() {
1740
- const rawFragment = window.location.hash.startsWith("#")
1741
- ? window.location.hash.slice(1)
1742
- : window.location.hash
1743
- // Only the canonical 32-byte bearer belongs to the transport. Ordinary page anchors must
1744
- // remain intact when an established shared session is reloaded.
1745
- const secret = /^[A-Za-z0-9_-]{43}$/.test(rawFragment) ? rawFragment : null
1746
- if (secret !== null) {
1747
- try {
1748
- window.history.replaceState(
1749
- window.history.state,
1750
- "",
1751
- window.location.pathname + window.location.search
1752
- )
1753
- } catch {
1754
- return null
1755
- }
1756
- }
1757
-
1758
- const match = /^\\/shared\\/([^/]+)(\\/.*)?$/.exec(window.location.pathname)
1759
- if (!match) return null
1760
- let grantId
1761
- try {
1762
- grantId = decodeURIComponent(match[1])
1763
- } catch {
1764
- return null
1765
- }
1766
- if (encodeURIComponent(grantId) !== match[1]) return null
1767
- return {
1768
- basename: "/shared/" + match[1],
1769
- grantId,
1770
- requestedPath: match[2] ?? "/",
1771
- secret,
1772
- }
1773
- }
1774
-
1775
- async function bootstrapSharedApp() {
1776
- const bootstrap = consumeBootstrap()
1777
- if (!bootstrap) {
1778
- renderUnavailable()
1779
- return
1780
- }
1781
-
1782
- try {
1783
- const { startSharedApp } = await import("./shared-main.tsx")
1784
- startSharedApp(bootstrap)
1785
- } catch {
1786
- console.error("[SixbSharedApp] Shared application bootstrap failed.")
1787
- renderUnavailable()
1788
- }
1789
- }
1790
-
1791
- void bootstrapSharedApp()
1792
- </script>
1793
- </body>
1794
- </html>
1795
- `;
1796
- const sharedHtmlPath = join4(generatedDir, "shared-index.html");
1797
- await writeFileIfChanged(sharedHtmlPath, sharedHtmlContent);
1798
- return {
1799
- htmlPath,
1800
- mainPath,
1801
- manifestPath,
1802
- runtimePath,
1803
- sharedHtmlPath,
1804
- sharedMainPath
115
+ function setAgentSurfaceMode(mode, override) {
116
+ const storageKey = agentSurfaceSessionStorageKey(override);
117
+ if (!storageKey || typeof window === "undefined")
118
+ return;
119
+ const defaults = {
120
+ mode,
121
+ dockWidth: DEFAULT_AGENT_SURFACE_WIDTH,
122
+ threadId: null
1805
123
  };
124
+ updateAgentSurfaceState(storageKey, defaults, (current) => ({ ...current, mode }));
125
+ }
126
+ function updateAgentSurfaceState(storageKey, defaults, update) {
127
+ const current = readAgentSurfaceState(storageKey, defaults);
128
+ const state = update(current);
129
+ writeAgentSurfaceState(storageKey, state);
130
+ window.dispatchEvent(new CustomEvent(AGENT_SURFACE_STATE_EVENT, {
131
+ detail: { storageKey, state }
132
+ }));
1806
133
  }
1807
- function renderSharedMetadataHead(metadata) {
1808
- return [
1809
- ` <title>${escapeHtmlText(metadata.title)}</title>`,
1810
- ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
1811
- ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`
1812
- ].join(`
1813
- `);
1814
- }
1815
- function renderMetadataHead(metadata) {
1816
- const tags = [
1817
- ` <title>${escapeHtmlText(metadata.title)}</title>`,
1818
- ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
1819
- ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
1820
- ' <link rel="manifest" href="/app.webmanifest" />',
1821
- ...metadata.favicon ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : [],
1822
- ...metadata.appleTouchIcon ? [` <link rel="apple-touch-icon" href="${metadata.appleTouchIcon}" />`] : []
1823
- ];
1824
- return tags.join(`
1825
- `);
1826
- }
1827
- function renderAuthMetadataHead(metadata) {
1828
- const tags = [
1829
- ` <title>${escapeHtmlText(metadata.title)}</title>`,
1830
- ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
1831
- ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
1832
- ...metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon) ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : []
1833
- ];
1834
- return tags.join(`
1835
- `);
1836
- }
1837
- function escapeHtmlText(value) {
1838
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1839
- }
1840
- function escapeHtmlAttribute(value) {
1841
- return escapeHtmlText(value).replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1842
- }
1843
- async function writeFileIfChanged(path, content) {
1844
- try {
1845
- if (await readFile3(path, "utf-8") === content) {
1846
- return;
1847
- }
1848
- } catch (error) {
1849
- if (!isFileNotFoundError(error)) {
1850
- throw error;
1851
- }
1852
- }
1853
- await writeFile2(path, content, "utf-8");
1854
- }
1855
- function isFileNotFoundError(error) {
1856
- return error instanceof Error && "code" in error && error.code === "ENOENT";
1857
- }
1858
- function relativeTo(from, to) {
1859
- let rel = relative2(from, to);
1860
- if (!rel.startsWith("."))
1861
- rel = `./${rel}`;
1862
- return rel;
134
+ function isRecord(value) {
135
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1863
136
  }
1864
- async function fileExists2(path) {
137
+ function readAgentSurfaceState(storageKey, defaults, minimumWidth = MIN_AGENT_SURFACE_WIDTH, maximumWidth = MAX_AGENT_SURFACE_WIDTH) {
138
+ if (!storageKey || typeof window === "undefined")
139
+ return defaults;
1865
140
  try {
1866
- await access(path);
1867
- return true;
141
+ return parseAgentSurfaceSessionState(window.sessionStorage.getItem(storageKey), defaults, minimumWidth, maximumWidth);
1868
142
  } catch {
1869
- return false;
1870
- }
1871
- }
1872
-
1873
- // src/dev-reload.ts
1874
- function devReloadResponse(request) {
1875
- const generation = process.env.SIXB_DEV_GENERATION;
1876
- const headers = new Headers({
1877
- "content-type": "text/javascript; charset=utf-8",
1878
- "cache-control": "no-store"
1879
- });
1880
- if (generation && process.env.SIXB_DEV_READY === "1") {
1881
- headers.set("x-sixb-dev-generation", generation);
143
+ return defaults;
1882
144
  }
1883
- if (request.method === "HEAD")
1884
- return new Response(null, { headers });
1885
- const script = generation ? `(() => {
1886
- if (window.__sixbDevReload) return;
1887
- window.__sixbDevReload = true;
1888
- const generation = ${JSON.stringify(generation).replaceAll("<", "\\u003c")};
1889
- let timer;
1890
- let checking = false;
1891
- let finished = false;
1892
- let failures = 0;
1893
- const hidden = () => document.visibilityState === "hidden";
1894
- function schedule(delay) {
1895
- clearTimeout(timer);
1896
- timer = setTimeout(poll, delay);
1897
- }
1898
- async function poll() {
1899
- if (checking || finished) return;
1900
- if (hidden()) { schedule(15000); return; }
1901
- checking = true;
1902
- try {
1903
- const response = await fetch("/__sixb/dev-reload.js", {
1904
- method: "HEAD", cache: "no-store", signal: AbortSignal.timeout(3000)
1905
- });
1906
- const next = response.headers.get("x-sixb-dev-generation");
1907
- if (response.ok && next && next !== generation) {
1908
- finished = true;
1909
- document.removeEventListener("visibilitychange", visible);
1910
- location.reload();
1911
- return;
1912
- }
1913
- failures = response.ok && next ? 0 : Math.min(failures + 1, 4);
1914
- } catch { failures = Math.min(failures + 1, 4); }
1915
- finally { checking = false; }
1916
- schedule(Math.min(1000 * 2 ** failures, 10000));
1917
- }
1918
- function visible() {
1919
- if (!hidden()) { clearTimeout(timer); void poll(); }
1920
- }
1921
- document.addEventListener("visibilitychange", visible);
1922
- void poll();
1923
- })();` : "";
1924
- return new Response(script, { headers });
1925
145
  }
1926
-
1927
- // src/styles.ts
1928
- import { readFile as readFile4 } from "fs/promises";
1929
- import { join as join6 } from "path";
1930
-
1931
- // src/tailwind.ts
1932
- import { mkdir as mkdir3 } from "fs/promises";
1933
- import { dirname as dirname2, join as join5 } from "path";
1934
- function resolveTailwindCliEntry(resolveFrom) {
146
+ function writeAgentSurfaceState(storageKey, state) {
147
+ if (!storageKey || typeof window === "undefined")
148
+ return;
1935
149
  try {
1936
- const packageJsonPath = Bun.resolveSync("@tailwindcss/cli/package.json", resolveFrom);
1937
- return join5(dirname2(packageJsonPath), "dist", "index.mjs");
1938
- } catch {
1939
- return null;
1940
- }
1941
- }
1942
- function createTailwindCssCompiler(options) {
1943
- const cwd = options.cwd ?? dirname2(options.inputPath);
1944
- const resolveFrom = options.resolveFrom ?? cwd;
1945
- const label = options.label ?? "[SixbTailwind]";
1946
- const debounceMs = options.debounceMs ?? 50;
1947
- const timeoutMs = options.timeoutMs ?? 60000;
1948
- const onError = options.onError ?? ((error) => console.error(`${label} ${error.message}`));
1949
- let chain = Promise.resolve();
1950
- let timer = null;
1951
- let stopped = false;
1952
- let activeProcess = null;
1953
- async function runCompile() {
1954
- if (stopped)
1955
- return;
1956
- const cliEntry = resolveTailwindCliEntry(resolveFrom);
1957
- if (!cliEntry) {
1958
- throw new Error(`${label} Tailwind CSS build requires '@tailwindcss/cli'. Install it with: bun add tailwindcss @tailwindcss/cli`);
1959
- }
1960
- await mkdir3(dirname2(options.outputPath), { recursive: true });
1961
- if (stopped)
1962
- return;
1963
- const args = [process.execPath, cliEntry, "-i", options.inputPath, "-o", options.outputPath];
1964
- if (options.minify) {
1965
- args.push("--minify");
1966
- }
1967
- const proc = Bun.spawn(args, {
1968
- cwd,
1969
- stdout: "ignore",
1970
- stderr: "pipe"
1971
- });
1972
- activeProcess = proc;
1973
- const stderr = new Response(proc.stderr).text().catch(() => "");
1974
- let timeout;
1975
- const timedOut = new Promise((resolve) => {
1976
- timeout = setTimeout(() => resolve("timeout"), timeoutMs);
1977
- });
1978
- try {
1979
- const outcome = await Promise.race([proc.exited, timedOut]);
1980
- if (stopped)
1981
- return;
1982
- if (outcome === "timeout") {
1983
- proc.kill("SIGKILL");
1984
- await proc.exited;
1985
- throw new Error(`${label} Tailwind CSS build did not finish within ${timeoutMs}ms and was killed. ` + `Check ${options.inputPath} and the sources Tailwind scans from ${cwd}.`);
1986
- }
1987
- if (outcome !== 0) {
1988
- throw new Error(`${label} Tailwind CSS build failed: ${(await stderr).trim()}`);
1989
- }
1990
- } finally {
1991
- clearTimeout(timeout);
1992
- activeProcess = null;
1993
- }
1994
- }
1995
- function compile() {
1996
- stopped = false;
1997
- const build = chain.then(() => runCompile());
1998
- chain = build.then(() => {}, () => {});
1999
- return build;
2000
- }
2001
- return {
2002
- compile,
2003
- schedule() {
2004
- if (stopped)
2005
- return;
2006
- if (timer) {
2007
- clearTimeout(timer);
2008
- }
2009
- timer = setTimeout(() => {
2010
- timer = null;
2011
- compile().catch((error) => {
2012
- onError(error instanceof Error ? error : new Error(String(error)));
2013
- });
2014
- }, debounceMs);
2015
- },
2016
- async stop() {
2017
- stopped = true;
2018
- if (timer) {
2019
- clearTimeout(timer);
2020
- timer = null;
2021
- }
2022
- activeProcess?.kill("SIGKILL");
2023
- await chain;
2024
- }
2025
- };
150
+ window.sessionStorage.setItem(storageKey, JSON.stringify(state));
151
+ } catch {}
2026
152
  }
2027
153
 
2028
- // src/styles.ts
2029
- async function resolveCustomAppStylesheet(input) {
2030
- const sourcePath = join6(input.appDir, "globals.css");
2031
- let css;
2032
- try {
2033
- css = await readFile4(sourcePath, "utf-8");
2034
- } catch {
2035
- return { kind: "none" };
2036
- }
2037
- if (!usesTailwind(css)) {
2038
- return { kind: "static", path: sourcePath };
2039
- }
2040
- if (!resolveTailwindCliEntry(input.rootDir)) {
2041
- throw new Error("[SixbCustomApp] app/globals.css uses Tailwind features but '@tailwindcss/cli' is not installed. Install it with: bun add tailwindcss @tailwindcss/cli");
2042
- }
2043
- return {
2044
- kind: "tailwind",
2045
- sourcePath,
2046
- outputPath: join6(input.generatedDir, "app.css")
154
+ // src/agent/agent-surface.tsx
155
+ import { jsx as jsx2, jsxs, Fragment } from "react/jsx-runtime";
156
+ function AgentSurface({
157
+ mode,
158
+ defaultMode = "dock",
159
+ onModeChange,
160
+ fullPage = false,
161
+ onRequestFullPage,
162
+ onRequestDock,
163
+ title,
164
+ launcherLabel,
165
+ composerPlaceholder,
166
+ context,
167
+ threadId,
168
+ defaultThreadId = null,
169
+ onThreadChange,
170
+ onExpandThread,
171
+ dockWidth,
172
+ defaultDockWidth = DEFAULT_AGENT_SURFACE_WIDTH,
173
+ onDockWidthChange,
174
+ minDockWidth = MIN_AGENT_SURFACE_WIDTH,
175
+ maxDockWidth = MAX_AGENT_SURFACE_WIDTH,
176
+ resizable = true,
177
+ persistenceKey,
178
+ className,
179
+ panelClassName,
180
+ welcomeContent
181
+ }) {
182
+ const messages = useAgentMessages().surface;
183
+ const surfaceTitle = title ?? messages.title;
184
+ const launcher = launcherLabel ?? messages.open;
185
+ const minimumWidth = Math.min(minDockWidth, maxDockWidth);
186
+ const maximumWidth = Math.max(minDockWidth, maxDockWidth);
187
+ const storageKey = agentSurfaceSessionStorageKey(persistenceKey);
188
+ const defaults = {
189
+ mode: defaultMode,
190
+ dockWidth: clampAgentSurfaceWidth(defaultDockWidth, minimumWidth, maximumWidth),
191
+ threadId: defaultThreadId
2047
192
  };
2048
- }
2049
- var TAILWIND_AT_RULES = /@(?:tailwind|source|theme|plugin|config|utility|custom-variant|variant|apply)\b/;
2050
- function usesTailwind(css) {
2051
- const stripped = css.replace(/\/\*[\s\S]*?\*\//g, "");
2052
- if (TAILWIND_AT_RULES.test(stripped)) {
2053
- return true;
2054
- }
2055
- for (const match of stripped.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
2056
- const specifier = match[1];
2057
- if (!specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("#") && !/^(?:https?:|data:)/.test(specifier)) {
2058
- return true;
2059
- }
2060
- }
2061
- return false;
2062
- }
2063
-
2064
- // src/createCustomApp.ts
2065
- var packageRoot = resolve3(import.meta.dir, "..");
2066
- var builtInAgentRouteModule = "@sixb/app/agents";
2067
- var builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threadId"];
2068
- var builtInAgentRouteSourcePath = join7(packageRoot, "src", "agents.ts");
2069
- var customAppManifestRoute = "/app.webmanifest";
2070
- var internalAppShellRoute = "/__sixb/generated/app-shell";
2071
- var internalSharedAppShellRoute = "/__sixb/generated/shared-app-shell";
2072
- async function createCustomApp(options) {
2073
- const rootDir = resolve3(options.rootDir);
2074
- const appDir = options.appDir ? resolve3(rootDir, options.appDir) : resolve3(rootDir, "app");
2075
- const generatedDir = resolve3(rootDir, options.generatedDir ?? join7(".sixb", "generated"));
2076
- const publicDir = options.publicDir ? resolve3(rootDir, options.publicDir) : resolve3(appDir, "public");
2077
- const apiBaseUrl = options.apiBaseUrl;
2078
- const audience = options.audience ?? "app";
2079
- const authEnabled = options.authEnabled ?? true;
2080
- const agentRoutesEnabled = options.agentRoutes ?? true;
2081
- async function scanRoutes() {
2082
- return [...(await scanAppRoutes(appDir)).pages];
2083
- }
2084
- let tailwindCompiler = null;
2085
- let tailwindCompilerKey = null;
2086
- let authTailwindCompiler = null;
2087
- let builtInAgentCssCompiler = null;
2088
- async function prepareStylesheet(stylesheet) {
2089
- stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
2090
- if (stylesheet.kind !== "tailwind") {
2091
- return stylesheet;
2092
- }
2093
- await compileAppTailwindStylesheet(stylesheet.sourcePath, stylesheet.outputPath);
2094
- return stylesheet;
2095
- }
2096
- async function compileAppTailwindStylesheet(inputPath, outputPath) {
2097
- const key = `${inputPath}\x00${outputPath}`;
2098
- if (tailwindCompilerKey !== key) {
2099
- await tailwindCompiler?.stop();
2100
- tailwindCompiler = createTailwindCssCompiler({
2101
- inputPath,
2102
- outputPath,
2103
- cwd: appDir,
2104
- resolveFrom: rootDir,
2105
- label: "[SixbCustomApp]"
2106
- });
2107
- tailwindCompilerKey = key;
2108
- }
2109
- const compiler = tailwindCompiler;
2110
- if (!compiler) {
2111
- throw new Error("[SixbCustomApp] Tailwind CSS compiler was not initialized");
2112
- }
2113
- await compiler.compile();
2114
- }
2115
- async function prepareCombinedBuiltInAgentStylesheet(stylesheet) {
2116
- const inputPath = join7(generatedDir, "app.input.css");
2117
- const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
2118
- const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot);
2119
- await writeFileIfChanged2(inputPath, [
2120
- `@import ${JSON.stringify(uiGlobalsPath)};`,
2121
- `@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
2122
- `@import ${JSON.stringify(stylesheet.sourcePath)};`,
2123
- `@import ${JSON.stringify(agentUiGlobalsPath)};`,
2124
- ""
2125
- ].join(`
2126
- `));
2127
- await compileAppTailwindStylesheet(inputPath, stylesheet.outputPath);
2128
- return stylesheet.outputPath;
2129
- }
2130
- async function prepareStylesheets(builtInRoutes) {
2131
- const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
2132
- if (stylesheet.kind === "tailwind" && builtInRoutes.length > 0) {
2133
- return {
2134
- stylesheetPath: await prepareCombinedBuiltInAgentStylesheet(stylesheet),
2135
- frameworkStylesheetPaths: []
2136
- };
2137
- }
2138
- const preparedStylesheet = await prepareStylesheet(stylesheet);
2139
- const builtInAgentStylesheetPath = await prepareBuiltInAgentStylesheet(builtInRoutes);
2140
- return {
2141
- frameworkStylesheetPaths: builtInAgentStylesheetPath ? [builtInAgentStylesheetPath] : [],
2142
- stylesheetPath: preparedStylesheet.kind === "none" ? null : preparedStylesheet.kind === "static" ? preparedStylesheet.path : preparedStylesheet.outputPath
193
+ const [sessionState, setSessionState] = useState2(() => readAgentSurfaceState(storageKey, defaults, minimumWidth, maximumWidth));
194
+ const [artifactHost, setArtifactHost] = useState2(null);
195
+ const [resizing, setResizing] = useState2(false);
196
+ const resizeStart = useRef(null);
197
+ useEffect(() => {
198
+ writeAgentSurfaceState(storageKey, sessionState);
199
+ }, [storageKey, sessionState]);
200
+ useEffect(() => {
201
+ if (!storageKey || typeof window === "undefined")
202
+ return;
203
+ const receiveState = (event) => {
204
+ const detail = event.detail;
205
+ if (detail?.storageKey !== storageKey)
206
+ return;
207
+ setSessionState(detail.state);
2143
208
  };
209
+ window.addEventListener(AGENT_SURFACE_STATE_EVENT, receiveState);
210
+ return () => window.removeEventListener(AGENT_SURFACE_STATE_EVENT, receiveState);
211
+ }, [storageKey]);
212
+ const currentMode = mode ?? sessionState.mode;
213
+ const currentThreadId = threadId === undefined ? sessionState.threadId : threadId;
214
+ const currentDockWidth = dockWidth ?? sessionState.dockWidth;
215
+ const numericDockWidth = typeof currentDockWidth === "number" ? currentDockWidth : sessionState.dockWidth;
216
+ const visible = fullPage || currentMode !== "collapsed";
217
+ const presentation = fullPage ? "full" : currentMode;
218
+ const dockWidthValue = typeof currentDockWidth === "number" ? `${currentDockWidth}px` : currentDockWidth;
219
+ const surfaceStyle = { "--agent-surface-width": dockWidthValue };
220
+ const changeMode = useCallback2((nextMode) => {
221
+ if (mode === undefined) {
222
+ setSessionState((current) => ({ ...current, mode: nextMode }));
223
+ }
224
+ onModeChange?.(nextMode);
225
+ }, [mode, onModeChange]);
226
+ const changeThread = useCallback2((nextThreadId) => {
227
+ setSessionState((current) => current.threadId === nextThreadId ? current : { ...current, threadId: nextThreadId });
228
+ onThreadChange?.(nextThreadId);
229
+ }, [onThreadChange]);
230
+ useEffect(() => {
231
+ if (threadId === undefined)
232
+ return;
233
+ setSessionState((current) => current.threadId === threadId ? current : { ...current, threadId });
234
+ }, [threadId]);
235
+ useEffect(() => {
236
+ if (!fullPage || sessionState.mode === "dock")
237
+ return;
238
+ setSessionState((current) => ({ ...current, mode: "dock" }));
239
+ }, [fullPage, sessionState.mode]);
240
+ const changeDockWidth = useCallback2((nextWidth) => {
241
+ const viewportMaximum = typeof window === "undefined" ? maximumWidth : Math.max(minimumWidth, Math.min(maximumWidth, window.innerWidth - minimumWidth));
242
+ const clamped = clampAgentSurfaceWidth(nextWidth, minimumWidth, viewportMaximum);
243
+ if (dockWidth === undefined) {
244
+ setSessionState((current) => ({ ...current, dockWidth: clamped }));
245
+ }
246
+ onDockWidthChange?.(clamped);
247
+ }, [dockWidth, maximumWidth, minimumWidth, onDockWidthChange]);
248
+ function startResize(event) {
249
+ if (event.button !== 0)
250
+ return;
251
+ event.preventDefault();
252
+ event.currentTarget.setPointerCapture(event.pointerId);
253
+ resizeStart.current = {
254
+ pointerId: event.pointerId,
255
+ clientX: event.clientX,
256
+ width: numericDockWidth
257
+ };
258
+ setResizing(true);
2144
259
  }
2145
- async function prepareBuiltInAgentStylesheet(builtInRoutes) {
2146
- if (builtInRoutes.length === 0) {
2147
- return null;
2148
- }
2149
- const inputPath = join7(generatedDir, "agent-ui.input.css");
2150
- const outputPath = join7(generatedDir, "agent-ui.css");
2151
- const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
2152
- const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot);
2153
- await writeFileIfChanged2(inputPath, [
2154
- `@import ${JSON.stringify(uiGlobalsPath)};`,
2155
- `@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
2156
- `@import ${JSON.stringify(agentUiGlobalsPath)};`,
2157
- ""
2158
- ].join(`
2159
- `));
2160
- builtInAgentCssCompiler ??= createTailwindCssCompiler({
2161
- inputPath,
2162
- outputPath,
2163
- cwd: packageRoot,
2164
- resolveFrom: packageRoot,
2165
- label: "[SixbCustomApp]"
2166
- });
2167
- await builtInAgentCssCompiler.compile();
2168
- return outputPath;
2169
- }
2170
- async function prepareGeneratedApp() {
2171
- const discovery = await scanAppRoutes(appDir);
2172
- const routes = [...discovery.pages];
2173
- if (routes.length === 0) {
2174
- throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`);
2175
- }
2176
- const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : [];
2177
- const stylesheets = await prepareStylesheets(builtInRoutes);
2178
- await generateRouteManifest(routes, generatedDir, {
2179
- builtInRoutes,
2180
- layouts: discovery.layouts
2181
- });
2182
- const entry = await generateAppEntry(rootDir, generatedDir, {
2183
- apiBaseUrl,
2184
- audience,
2185
- authEnabled,
2186
- appDir,
2187
- publicDir,
2188
- frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
2189
- stylesheetPath: stylesheets.stylesheetPath
2190
- });
2191
- return { ...entry, routes };
2192
- }
2193
- async function prepareAuthExperience(authOptions = {}) {
2194
- const outdir = authOptions.outdir ? resolve3(rootDir, authOptions.outdir) : join7(generatedDir, "auth");
2195
- if (!await pathExists(join7(appDir, "auth.tsx"))) {
2196
- await rm2(outdir, { recursive: true, force: true });
2197
- return null;
2198
- }
2199
- const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
2200
- let stylesheetPath;
2201
- if (stylesheet.kind === "none") {
2202
- stylesheetPath = null;
2203
- } else if (stylesheet.kind === "static") {
2204
- stylesheetPath = stylesheet.path;
2205
- } else {
2206
- const outputPath = join7(generatedDir, "auth.css");
2207
- authTailwindCompiler ??= createTailwindCssCompiler({
2208
- inputPath: stylesheet.sourcePath,
2209
- outputPath,
2210
- cwd: appDir,
2211
- resolveFrom: rootDir,
2212
- label: "[SixbCustomApp]"
2213
- });
2214
- await authTailwindCompiler.compile();
2215
- stylesheetPath = outputPath;
2216
- }
2217
- const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
2218
- appDir,
2219
- publicDir,
2220
- stylesheetPath
2221
- });
2222
- if (!entry) {
2223
- return null;
2224
- }
2225
- const result = await buildAuthExperience({
2226
- entryPath: entry.htmlPath,
2227
- scriptEntryPath: entry.mainPath,
2228
- outdir
2229
- });
2230
- if (!result.success) {
2231
- throw new Error(`[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join(`
2232
- `)}`);
2233
- }
2234
- return { outdir: result.outdir };
2235
- }
2236
- return {
2237
- async scanRoutes() {
2238
- return await scanRoutes();
2239
- },
2240
- async hasRoutes() {
2241
- const routes = await scanRoutes();
2242
- return routes.length > 0;
2243
- },
2244
- async prepareAuthExperience(options) {
2245
- return await prepareAuthExperience(options);
2246
- },
2247
- async dev(devOptions = {}) {
2248
- const publicEnv = collectPublicEnv();
2249
- const withRuntime = (html) => injectRuntimeConfig(html, { apiBaseUrl, audience, authEnabled, publicEnv });
2250
- const host = devOptions.host ?? "0.0.0.0";
2251
- const port = devOptions.port ?? 3001;
2252
- const { htmlPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
2253
- await prepareAuthExperience();
2254
- let htmlImportVersion = 0;
2255
- let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
2256
- const sharedDevRoot = join7(generatedDir, "shared-dev");
2257
- await rm2(sharedDevRoot, { recursive: true, force: true });
2258
- let sharedBuildVersion = 0;
2259
- let sharedSourceVersion = 0;
2260
- let sharedBuiltSourceVersion = -1;
2261
- let sharedBuild = null;
2262
- let sharedBuildPromise = null;
2263
- let sharedAssetRoutes = {};
2264
- let stopping = false;
2265
- const privateAppShellRoute = `${internalAppShellRoute}-${randomBytes(18).toString("base64url")}`;
2266
- const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
2267
- let internalOrigin = "";
2268
- let server = null;
2269
- const serveOptions = (bundle) => ({
2270
- port,
2271
- hostname: host,
2272
- development: true,
2273
- routes: {
2274
- ...publicRoutes,
2275
- ...sharedAssetRoutes,
2276
- ...reservedSixbRoutes(),
2277
- "/__sixb/dev-reload.js": getHeadRoute(devReloadResponse),
2278
- [customAppManifestRoute]: manifestRoute(manifestPath),
2279
- [privateAppShellRoute]: htmlBundleRoute(bundle),
2280
- ...sharedAppDevRoutes(async () => injectRuntimeConfig((await ensureSharedBuild()).html, {
2281
- apiBaseUrl,
2282
- audience: "app",
2283
- authEnabled: false,
2284
- publicEnv
2285
- }), apiBaseUrl),
2286
- "/": spaHtmlRoute(() => internalOrigin, {
2287
- shellRoute: privateAppShellRoute,
2288
- transformHtml: withRuntime
2289
- }),
2290
- "/*": spaHtmlRoute(() => internalOrigin, {
2291
- shellRoute: privateAppShellRoute,
2292
- transformHtml: withRuntime
2293
- })
2294
- }
2295
- });
2296
- async function ensureSharedBuild() {
2297
- if (stopping) {
2298
- throw new Error("[SixbCustomApp] Shared development build requested while stopping.");
2299
- }
2300
- if (sharedBuild && sharedBuiltSourceVersion === sharedSourceVersion) {
2301
- return sharedBuild;
2302
- }
2303
- if (sharedBuildPromise) {
2304
- await sharedBuildPromise;
2305
- return await ensureSharedBuild();
2306
- }
2307
- const sourceVersion = sharedSourceVersion;
2308
- const outdir = join7(sharedDevRoot, String(sharedBuildVersion++));
2309
- const build = buildSharedAppDev({
2310
- entryPath: sharedHtmlPath,
2311
- outdir,
2312
- scriptEntryPath: sharedMainPath
2313
- }).then((result) => {
2314
- sharedAssetRoutes = {
2315
- ...sharedAssetRoutes,
2316
- ...createGeneratedAssetRoutes(outdir, result.assetPaths)
2317
- };
2318
- sharedBuild = result;
2319
- sharedBuiltSourceVersion = sourceVersion;
2320
- server?.reload(serveOptions(htmlBundle));
2321
- return result;
2322
- }).finally(() => {
2323
- sharedBuildPromise = null;
2324
- });
2325
- sharedBuildPromise = build;
2326
- const result = await build;
2327
- if (!stopping && sourceVersion !== sharedSourceVersion) {
2328
- return await ensureSharedBuild();
2329
- }
2330
- return result;
2331
- }
2332
- server = Bun.serve(serveOptions(htmlBundle));
2333
- internalOrigin = devServerInternalOrigin(host, server.port ?? port);
2334
- let rebuildTimer = null;
2335
- let rebuildChain = Promise.resolve();
2336
- const enqueueRebuild = () => {
2337
- rebuildChain = rebuildChain.then(async () => {
2338
- const { htmlPath: nextHtmlPath } = await prepareGeneratedApp();
2339
- await prepareAuthExperience();
2340
- htmlImportVersion++;
2341
- htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
2342
- sharedSourceVersion++;
2343
- server?.reload(serveOptions(htmlBundle));
2344
- }).catch((error) => {
2345
- const message = error instanceof Error ? error.message : String(error);
2346
- console.error(`[SixbCustomApp] Rebuild failed: ${message}`);
2347
- });
2348
- };
2349
- const watcher = watch(appDir, { recursive: true }, (_eventType, filename) => {
2350
- if (!filename)
2351
- return;
2352
- if (!/\.(ts|tsx|css)$/.test(String(filename)))
2353
- return;
2354
- if (rebuildTimer) {
2355
- clearTimeout(rebuildTimer);
2356
- }
2357
- rebuildTimer = setTimeout(() => {
2358
- rebuildTimer = null;
2359
- enqueueRebuild();
2360
- }, 80);
2361
- });
2362
- watcher.on("error", (error) => {
2363
- const message = error instanceof Error ? error.message : String(error);
2364
- console.error(`[SixbCustomApp] Stopped watching ${appDir}: ${message}. ` + "Serving the last build; restart to resume hot reload.");
2365
- });
2366
- const displayHost = host === "0.0.0.0" ? "localhost" : host;
2367
- return {
2368
- host,
2369
- port,
2370
- url: `http://${displayHost}:${port}`,
2371
- async stop() {
2372
- stopping = true;
2373
- if (rebuildTimer) {
2374
- clearTimeout(rebuildTimer);
2375
- rebuildTimer = null;
2376
- }
2377
- watcher.close();
2378
- await rebuildChain;
2379
- await tailwindCompiler?.stop();
2380
- await authTailwindCompiler?.stop();
2381
- await builtInAgentCssCompiler?.stop();
2382
- const activeServer = server;
2383
- server = null;
2384
- activeServer?.stop(true);
2385
- await sharedBuildPromise?.catch(() => {});
2386
- await rm2(sharedDevRoot, { recursive: true, force: true });
2387
- }
2388
- };
2389
- },
2390
- async build(buildOptions = {}) {
2391
- const outdir = resolve3(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
2392
- const { htmlPath, mainPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
2393
- const result = await buildApp({
2394
- entryPath: htmlPath,
2395
- scriptEntryPath: mainPath,
2396
- sharedEntryPath: sharedHtmlPath,
2397
- sharedScriptEntryPath: sharedMainPath,
2398
- manifestPath,
2399
- outdir
2400
- });
2401
- if (result.success) {
2402
- await prepareAuthExperience({ outdir: join7(outdir, "auth") });
2403
- }
2404
- if (result.success && await pathExists(publicDir)) {
2405
- await cp(publicDir, outdir, {
2406
- recursive: true,
2407
- force: true,
2408
- filter: (source) => {
2409
- const resolvedSource = resolve3(source);
2410
- return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, SHARED_APP_SHELL_FILE_NAME) && resolvedSource !== join7(publicDir, "auth");
2411
- }
2412
- });
2413
- }
2414
- return result;
2415
- },
2416
- async start(startOptions = {}) {
2417
- const publicEnv = collectPublicEnv();
2418
- const host = startOptions.host ?? "0.0.0.0";
2419
- const port = startOptions.port ?? 3001;
2420
- const outdir = resolve3(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
2421
- const indexPath = join7(outdir, "index.html");
2422
- const sharedIndexPath = join7(outdir, SHARED_APP_SHELL_FILE_NAME);
2423
- if (!await pathExists(indexPath)) {
2424
- throw new Error(`[SixbCustomApp] No built app found in ${outdir}`);
2425
- }
2426
- if (!await pathExists(sharedIndexPath)) {
2427
- throw new Error(`[SixbCustomApp] Built app in ${outdir} is missing ${SHARED_APP_SHELL_FILE_NAME}; rebuild required.`);
2428
- }
2429
- const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
2430
- apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
2431
- audience: startOptions.audience ?? audience,
2432
- authEnabled: startOptions.authEnabled ?? authEnabled,
2433
- publicEnv
2434
- });
2435
- const sharedIndexHtml = injectRuntimeConfig(await Bun.file(sharedIndexPath).text(), {
2436
- apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
2437
- audience: "app",
2438
- authEnabled: false,
2439
- publicEnv
2440
- });
2441
- const runtimeApiBaseUrl = startOptions.apiBaseUrl ?? apiBaseUrl;
2442
- const server = Bun.serve({
2443
- port,
2444
- hostname: host,
2445
- development: false,
2446
- async fetch(req) {
2447
- const url = new URL(req.url);
2448
- if (isReservedSixbRoute(url.pathname)) {
2449
- return notFoundResponse();
2450
- }
2451
- if (isFrameworkPrivateRoute(url.pathname)) {
2452
- return notFoundResponse();
2453
- }
2454
- if (req.method !== "GET" && req.method !== "HEAD") {
2455
- return notFoundResponse();
2456
- }
2457
- if (isSharedAppRoute(url.pathname)) {
2458
- if (isAssetRequest(url.pathname)) {
2459
- return notFoundResponse();
2460
- }
2461
- return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl);
2462
- }
2463
- if (isSharedNamespace(url.pathname)) {
2464
- return notFoundResponse();
2465
- }
2466
- if (url.pathname === "/" || url.pathname === "") {
2467
- return htmlResponse(req, indexHtml);
2468
- }
2469
- const resolvedPath = resolveStaticPath(outdir, url.pathname);
2470
- if (!resolvedPath) {
2471
- return notFoundResponse();
2472
- }
2473
- const directFile = Bun.file(resolvedPath);
2474
- if (await directFile.exists()) {
2475
- if (resolvedPath === indexPath) {
2476
- return htmlResponse(req, indexHtml);
2477
- }
2478
- return staticFileResponse(req, resolvedPath, staticAssetHeaders(url.pathname));
2479
- }
2480
- if (isAssetRequest(url.pathname)) {
2481
- return notFoundResponse();
2482
- }
2483
- const htmlFile = Bun.file(`${resolvedPath}.html`);
2484
- if (await htmlFile.exists()) {
2485
- if (`${resolvedPath}.html` === indexPath) {
2486
- return htmlResponse(req, indexHtml);
2487
- }
2488
- return fileResponse(req, htmlFile);
2489
- }
2490
- const nestedIndexFile = Bun.file(join7(resolvedPath, "index.html"));
2491
- if (await nestedIndexFile.exists()) {
2492
- return fileResponse(req, nestedIndexFile);
2493
- }
2494
- return htmlResponse(req, indexHtml);
2495
- }
2496
- });
2497
- const displayHost = host === "0.0.0.0" ? "localhost" : host;
2498
- return {
2499
- host,
2500
- port,
2501
- url: `http://${displayHost}:${port}`,
2502
- async stop() {
2503
- server.stop(true);
2504
- }
2505
- };
2506
- }
2507
- };
2508
- }
2509
- async function pathExists(path) {
2510
- try {
2511
- await access2(path);
2512
- return true;
2513
- } catch {
2514
- return false;
260
+ function continueResize(event) {
261
+ const start = resizeStart.current;
262
+ if (!start || start.pointerId !== event.pointerId)
263
+ return;
264
+ changeDockWidth(start.width + start.clientX - event.clientX);
2515
265
  }
2516
- }
2517
- function builtInAgentRoutesFor(routes) {
2518
- const projectRoutePatterns = new Set(routes.map((route) => routePatternKey(route.path)));
2519
- return builtInAgentRoutePaths.filter((path) => !projectRoutePatterns.has(routePatternKey(path))).map((path) => ({
2520
- path,
2521
- moduleSpecifier: builtInAgentRouteModule
2522
- }));
2523
- }
2524
- async function writeFileIfChanged2(path, content) {
2525
- try {
2526
- if (await readFile5(path, "utf-8") === content) {
266
+ function finishResize(event) {
267
+ if (resizeStart.current?.pointerId !== event.pointerId)
2527
268
  return;
2528
- }
2529
- } catch (error) {
2530
- if (!isFileNotFoundError2(error)) {
2531
- throw error;
269
+ resizeStart.current = null;
270
+ setResizing(false);
271
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
272
+ event.currentTarget.releasePointerCapture(event.pointerId);
2532
273
  }
2533
274
  }
2534
- await mkdir4(dirname3(path), { recursive: true });
2535
- await writeFile3(path, content, "utf-8");
2536
- }
2537
- function isFileNotFoundError2(error) {
2538
- return error instanceof Error && "code" in error && error.code === "ENOENT";
2539
- }
2540
- async function createPublicRoutes(publicDir) {
2541
- const files = new Bun.Glob("**/*").scan({
2542
- cwd: publicDir,
2543
- absolute: true,
2544
- onlyFiles: true
275
+ function resizeWithKeyboard(event) {
276
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
277
+ return;
278
+ event.preventDefault();
279
+ const step = event.shiftKey ? 32 : 16;
280
+ changeDockWidth(numericDockWidth + (event.key === "ArrowLeft" ? step : -step));
281
+ }
282
+ return /* @__PURE__ */ jsxs(Fragment, {
283
+ children: [
284
+ !visible ? /* @__PURE__ */ jsx2(Button, {
285
+ type: "button",
286
+ size: "icon",
287
+ className: "fixed right-5 bottom-5 z-40 size-11 rounded-full shadow-lg max-sm:right-3 max-sm:bottom-3",
288
+ "aria-label": launcher,
289
+ title: launcher,
290
+ onClick: () => changeMode("dock"),
291
+ children: /* @__PURE__ */ jsx2(MessageSquareText, {
292
+ className: "size-4"
293
+ })
294
+ }) : null,
295
+ /* @__PURE__ */ jsx2("div", {
296
+ ref: setArtifactHost,
297
+ "data-agent-artifact-host": "",
298
+ "aria-hidden": !visible,
299
+ inert: !visible,
300
+ className: cn2("pointer-events-none fixed inset-y-3 left-3 z-40 max-sm:hidden", (!visible || fullPage) && "hidden"),
301
+ style: { right: `calc(${dockWidthValue} + 0.75rem)` }
302
+ }),
303
+ /* @__PURE__ */ jsxs("aside", {
304
+ "data-agent-surface": presentation,
305
+ "data-agent-surface-resizing": resizing ? "" : undefined,
306
+ "aria-label": surfaceTitle,
307
+ "aria-hidden": !visible,
308
+ inert: !visible,
309
+ style: surfaceStyle,
310
+ className: cn2("shrink-0 overflow-hidden bg-background", fullPage ? "absolute inset-0 z-40 h-full min-w-0 w-full" : "relative h-full", resizing && "select-none", !visible && "w-0 border-l border-transparent", visible && !fullPage && "w-[var(--agent-surface-width)] border-l border-border max-sm:fixed max-sm:inset-y-0 max-sm:right-0 max-sm:z-50 max-sm:w-screen", className),
311
+ children: [
312
+ visible && !fullPage && resizable ? /* @__PURE__ */ jsx2("div", {
313
+ role: "separator",
314
+ "aria-label": messages.resize,
315
+ "aria-orientation": "vertical",
316
+ "aria-valuemin": minimumWidth,
317
+ "aria-valuemax": maximumWidth,
318
+ "aria-valuenow": Math.round(numericDockWidth),
319
+ tabIndex: 0,
320
+ onPointerDown: startResize,
321
+ onPointerMove: continueResize,
322
+ onPointerUp: finishResize,
323
+ onPointerCancel: finishResize,
324
+ onKeyDown: resizeWithKeyboard,
325
+ className: "absolute inset-y-0 left-0 z-30 w-1 cursor-ew-resize touch-none bg-transparent outline-none transition-colors hover:bg-ring/40 focus-visible:bg-ring/60 max-sm:hidden"
326
+ }) : null,
327
+ /* @__PURE__ */ jsxs("div", {
328
+ className: cn2("relative flex h-full min-w-0 flex-col", fullPage ? "w-full" : "w-[var(--agent-surface-width)] max-sm:w-screen"),
329
+ children: [
330
+ !fullPage ? /* @__PURE__ */ jsx2(Button, {
331
+ type: "button",
332
+ variant: "ghost",
333
+ size: "icon-lg",
334
+ "aria-label": messages.collapse,
335
+ onClick: () => changeMode("collapsed"),
336
+ className: "absolute top-0.5 left-1.5 z-20 bg-background/90 backdrop-blur-sm [&_svg]:size-5",
337
+ children: /* @__PURE__ */ jsx2(ChevronRight, {})
338
+ }) : null,
339
+ /* @__PURE__ */ jsx2(AgentPanel, {
340
+ compact: !fullPage,
341
+ context,
342
+ composerPlaceholder,
343
+ threadId: currentThreadId,
344
+ onThreadChange: changeThread,
345
+ welcomeContent,
346
+ conversationHeaderActions: fullPage && onRequestDock ? /* @__PURE__ */ jsx2(Button, {
347
+ type: "button",
348
+ variant: "ghost",
349
+ size: "icon-lg",
350
+ "aria-label": messages.dock,
351
+ onClick: () => {
352
+ changeMode("dock");
353
+ onRequestDock?.();
354
+ },
355
+ className: "[&_svg]:size-5",
356
+ children: /* @__PURE__ */ jsx2(Minimize2, {})
357
+ }) : !fullPage && (onRequestFullPage || onExpandThread && currentThreadId) ? /* @__PURE__ */ jsx2(Button, {
358
+ type: "button",
359
+ variant: "ghost",
360
+ size: "icon-lg",
361
+ "aria-label": messages.expand,
362
+ onClick: () => {
363
+ if (onExpandThread && currentThreadId)
364
+ onExpandThread(currentThreadId);
365
+ else
366
+ onRequestFullPage?.();
367
+ },
368
+ className: "[&_svg]:size-5",
369
+ children: /* @__PURE__ */ jsx2(Maximize2, {})
370
+ }) : null,
371
+ artifactHost: fullPage ? null : artifactHost,
372
+ className: cn2("min-h-0 flex-1", !fullPage && "[&_[data-agent-conversation-header]]:pl-12", panelClassName)
373
+ })
374
+ ]
375
+ })
376
+ ]
377
+ })
378
+ ]
2545
379
  });
2546
- const routes = {};
2547
- for await (const filePath of files) {
2548
- const routePath = `/${filePath.slice(publicDir.length + 1).split("\\").join("/")}`;
2549
- if (isReservedSixbRoute(routePath) || isSharedNamespace(routePath) || isFrameworkPrivateRoute(routePath) || routePath === customAppManifestRoute) {
2550
- continue;
2551
- }
2552
- routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath));
2553
- }
2554
- return routes;
2555
- }
2556
- function createGeneratedAssetRoutes(outputRoot, assetPaths) {
2557
- const routes = {};
2558
- for (const assetPath of assetPaths) {
2559
- const relativePath = relative3(outputRoot, assetPath);
2560
- if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
2561
- throw new Error(`[SixbCustomApp] Shared development asset escaped its output directory.`);
2562
- }
2563
- const routePath = `/${relativePath.split("\\").join("/")}`;
2564
- routes[routePath] = getHeadRoute((request) => fileResponse(request, Bun.file(assetPath), { "cache-control": "no-store" }));
2565
- }
2566
- return routes;
2567
- }
2568
- function reservedSixbRoutes() {
2569
- const handler = () => notFoundResponse();
2570
- return {
2571
- [internalAppShellRoute]: allMethodsRoute(handler),
2572
- [`${internalAppShellRoute}/*`]: allMethodsRoute(handler),
2573
- [internalSharedAppShellRoute]: allMethodsRoute(handler),
2574
- [`${internalSharedAppShellRoute}/*`]: allMethodsRoute(handler),
2575
- [`/${SHARED_APP_SHELL_FILE_NAME}`]: allMethodsRoute(handler),
2576
- "/api": allMethodsRoute(handler),
2577
- "/api/*": allMethodsRoute(handler),
2578
- "/auth": allMethodsRoute(handler),
2579
- "/auth/*": allMethodsRoute(handler),
2580
- "/ws": allMethodsRoute(handler),
2581
- "/ws/*": allMethodsRoute(handler),
2582
- "/docs": allMethodsRoute(handler),
2583
- "/docs/*": allMethodsRoute(handler)
2584
- };
2585
- }
2586
- function sharedAppDevRoutes(html, apiBaseUrl) {
2587
- const reject = () => notFoundResponse();
2588
- const guardedHandler = async (request) => {
2589
- const pathname = new URL(request.url).pathname;
2590
- if (!isSharedAppRoute(pathname) || isAssetRequest(pathname)) {
2591
- return notFoundResponse();
2592
- }
2593
- return sharedHtmlResponse(request, await html(), apiBaseUrl);
2594
- };
2595
- return {
2596
- "/shared": allMethodsRoute(reject),
2597
- "/shared/*": {
2598
- GET: guardedHandler,
2599
- HEAD: guardedHandler,
2600
- POST: reject,
2601
- PUT: reject,
2602
- PATCH: reject,
2603
- DELETE: reject,
2604
- OPTIONS: reject
2605
- }
2606
- };
2607
- }
2608
- function isSharedAppRoute(pathname) {
2609
- return /^\/shared\/[^/]+(?:\/.*)?$/.test(pathname);
2610
- }
2611
- function isSharedNamespace(pathname) {
2612
- const decoded = decodeRoutePathname(pathname);
2613
- return decoded === "/shared" || decoded?.startsWith("/shared/") === true;
2614
380
  }
2615
- function isFrameworkPrivateRoute(pathname) {
2616
- const decoded = decodeRoutePathname(pathname)?.toLowerCase();
2617
- if (!decoded)
2618
- return false;
2619
- const sharedShellRoute = `/${SHARED_APP_SHELL_FILE_NAME}`;
2620
- return decoded === sharedShellRoute || decoded.startsWith(`${sharedShellRoute}/`) || decoded === internalAppShellRoute || decoded.startsWith(`${internalAppShellRoute}/`) || decoded === internalSharedAppShellRoute || decoded.startsWith(`${internalSharedAppShellRoute}/`);
2621
- }
2622
- function decodeRoutePathname(pathname) {
2623
- try {
2624
- return decodeURIComponent(pathname).replaceAll("\\", "/");
2625
- } catch {
2626
- return null;
2627
- }
2628
- }
2629
- function isReservedSixbRoute(pathname) {
2630
- const decoded = decodeRoutePathname(pathname);
2631
- if (!decoded)
2632
- return false;
2633
- return decoded === "/api" || decoded.startsWith("/api/") || decoded === "/auth" || decoded.startsWith("/auth/") || decoded === "/ws" || decoded.startsWith("/ws/") || decoded === "/docs" || decoded.startsWith("/docs/");
2634
- }
2635
- var ASSET_EXTENSIONS = new Set([
2636
- "js",
2637
- "mjs",
2638
- "cjs",
2639
- "css",
2640
- "map",
2641
- "json",
2642
- "wasm",
2643
- "ico",
2644
- "png",
2645
- "jpg",
2646
- "jpeg",
2647
- "gif",
2648
- "svg",
2649
- "webp",
2650
- "avif",
2651
- "bmp",
2652
- "woff",
2653
- "woff2",
2654
- "ttf",
2655
- "otf",
2656
- "eot",
2657
- "mp4",
2658
- "webm",
2659
- "ogg",
2660
- "mp3",
2661
- "wav",
2662
- "txt",
2663
- "xml",
2664
- "webmanifest",
2665
- "pdf"
2666
- ]);
2667
- function isAssetRequest(pathname) {
2668
- let decoded = pathname;
2669
- try {
2670
- decoded = decodeURIComponent(pathname);
2671
- } catch {}
2672
- const lastSegment = decoded.split(/[\\/]+/).pop() ?? "";
2673
- const dot = lastSegment.lastIndexOf(".");
2674
- if (dot <= 0 || dot === lastSegment.length - 1)
2675
- return false;
2676
- return ASSET_EXTENSIONS.has(lastSegment.slice(dot + 1).toLowerCase());
2677
- }
2678
- function resolveStaticPath(appRoot, pathname) {
2679
- let decodedPath;
2680
- try {
2681
- decodedPath = decodeURIComponent(pathname);
2682
- } catch {
2683
- return null;
2684
- }
2685
- if (decodedPath.includes("\x00"))
2686
- return null;
2687
- const segments = decodedPath.split(/[\\/]+/);
2688
- if (segments.includes(".."))
2689
- return null;
2690
- const normalizedPath = normalize(decodedPath).replace(/^[\\/]+/, "");
2691
- const resolvedPath = resolve3(appRoot, normalizedPath);
2692
- const rel = relative3(appRoot, resolvedPath);
2693
- if (rel.startsWith("..") || isAbsolute(rel))
381
+ // src/public-env.ts
382
+ var runtime = typeof window === "undefined" ? undefined : window.__SIXB_RUNTIME__;
383
+ var publicEnv = Object.freeze(Object.assign(Object.create(null), runtime?.publicEnv));
384
+ // src/shell/agent-dock.tsx
385
+ import { getAgentOptions } from "@sixb/client/hooks";
386
+ import { useQuery } from "@tanstack/react-query";
387
+ import { useLocation, useNavigate } from "react-router-dom";
388
+ import { jsx as jsx3 } from "react/jsx-runtime";
389
+ function AgentDock() {
390
+ const messages = useAppMessages2().agent;
391
+ const navigate = useNavigate();
392
+ const { pathname } = useLocation();
393
+ const enabled = useSectionsEnabled();
394
+ const agent = useQuery({ ...getAgentOptions(), enabled, retry: false, staleTime: 5 * 60000 });
395
+ const conversationPage = pathname === "/" || pathname === "/agents" || pathname.startsWith("/agents/");
396
+ if (!enabled || !agent.data || conversationPage)
2694
397
  return null;
2695
- return resolvedPath;
2696
- }
2697
- function injectRuntimeConfig(html, config) {
2698
- const existingRuntimeScript = /<script>window\.__SIXB_RUNTIME__ = (.*?);<\/script>/;
2699
- const existingConfig = html.match(existingRuntimeScript)?.[1];
2700
- const script = renderCustomAppRuntimeScript({
2701
- auth: { audience: config.audience, enabled: config.authEnabled },
2702
- ...existingConfig ? JSON.parse(existingConfig) : {},
2703
- ...config.apiBaseUrl ? {
2704
- api: { baseUrl: config.apiBaseUrl },
2705
- auth: { audience: config.audience, enabled: config.authEnabled }
2706
- } : {},
2707
- publicEnv: config.publicEnv
398
+ return /* @__PURE__ */ jsx3(AgentSurface, {
399
+ title: messages.title,
400
+ launcherLabel: messages.open,
401
+ defaultMode: "collapsed",
402
+ onExpandThread: (threadId) => navigate(`/agents/${encodeURIComponent(threadId)}`),
403
+ persistenceKey: "sixb.app.agent-dock.v1"
2708
404
  });
2709
- if (existingRuntimeScript.test(html)) {
2710
- return html.replace(existingRuntimeScript, () => script);
2711
- }
2712
- if (/<head\b[^>]*>/i.test(html)) {
2713
- return html.replace(/<head\b[^>]*>/i, (head) => `${head}
2714
- ${script}`);
2715
- }
2716
- return `${script}
2717
- ${html}`;
2718
405
  }
2719
- function htmlResponse(request, html) {
2720
- return new Response(request.method === "HEAD" ? null : html, {
2721
- headers: {
2722
- "content-type": "text/html; charset=utf-8",
2723
- "cache-control": "no-store"
2724
- }
406
+ // src/shell/app-shell.tsx
407
+ import {
408
+ Sidebar,
409
+ SidebarCollapseToggle,
410
+ SidebarContent,
411
+ SidebarFooter,
412
+ SidebarGroup as SidebarGroup2,
413
+ SidebarGroupContent as SidebarGroupContent2,
414
+ SidebarHeader,
415
+ SidebarInset,
416
+ SidebarMenu as SidebarMenu4,
417
+ SidebarMenuItem as SidebarMenuItem4,
418
+ SidebarProvider,
419
+ SidebarRail,
420
+ SidebarTrigger,
421
+ useSidebar as useSidebar2
422
+ } from "@sixb/ui/components";
423
+ import { ThemeProvider } from "@sixb/ui/hooks";
424
+ import { cn as cn4 } from "@sixb/ui/lib/utils";
425
+
426
+ // src/shell/search-command.tsx
427
+ import { searchObjectsOptions } from "@sixb/client/hooks";
428
+ import {
429
+ CommandDialog,
430
+ CommandEmpty,
431
+ CommandGroup,
432
+ CommandInput,
433
+ CommandItem,
434
+ CommandList,
435
+ Kbd,
436
+ SidebarMenu,
437
+ SidebarMenuButton,
438
+ SidebarMenuItem
439
+ } from "@sixb/ui/components";
440
+ import { keepPreviousData, useQuery as useQuery2 } from "@tanstack/react-query";
441
+ import { Box, Layers, Search } from "lucide-react";
442
+ import { useDeferredValue, useEffect as useEffect2, useState as useState3 } from "react";
443
+ import { useNavigate as useNavigate2 } from "react-router-dom";
444
+ import { jsx as jsx4, jsxs as jsxs2, Fragment as Fragment2 } from "react/jsx-runtime";
445
+ function SearchCommand({ pages = [] }) {
446
+ const appMessages = useAppMessages2();
447
+ const messages = appMessages.search;
448
+ const navigate = useNavigate2();
449
+ const sections = useSections2();
450
+ const enabled = useSectionsEnabled();
451
+ const [open, setOpen] = useState3(false);
452
+ const [query, setQuery] = useState3("");
453
+ const term = useDeferredValue(query.trim());
454
+ const searching = term.length > 1;
455
+ const objects = useQuery2({
456
+ ...searchObjectsOptions({ query: { q: term, limit: "8" } }),
457
+ enabled: enabled && open && searching,
458
+ placeholderData: keepPreviousData,
459
+ retry: false
2725
460
  });
2726
- }
2727
- function sharedHtmlResponse(request, html, apiBaseUrl) {
2728
- const secured = secureSharedHtml(html, request, { apiBaseUrl });
2729
- return new Response(request.method === "HEAD" ? null : secured.html, {
2730
- headers: {
2731
- "content-type": "text/html; charset=utf-8",
2732
- ...secured.headers
2733
- }
461
+ useEffect2(() => {
462
+ if (!enabled)
463
+ return;
464
+ const toggle = (event) => {
465
+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {
466
+ event.preventDefault();
467
+ setOpen((current) => !current);
468
+ }
469
+ };
470
+ window.addEventListener("keydown", toggle);
471
+ return () => window.removeEventListener("keydown", toggle);
472
+ }, [enabled]);
473
+ const go = (href) => {
474
+ setOpen(false);
475
+ setQuery("");
476
+ if (isExternal(href))
477
+ window.location.assign(href);
478
+ else
479
+ navigate(href);
480
+ };
481
+ if (!enabled)
482
+ return null;
483
+ const appPages = [
484
+ ...pages.flatMap((entry) => ("group" in entry) ? entry.items : [entry]),
485
+ { label: appMessages.artifacts, href: ARTIFACTS_HREF, icon: Layers }
486
+ ];
487
+ return /* @__PURE__ */ jsxs2(Fragment2, {
488
+ children: [
489
+ /* @__PURE__ */ jsx4(SidebarMenu, {
490
+ children: /* @__PURE__ */ jsx4(SidebarMenuItem, {
491
+ children: /* @__PURE__ */ jsxs2(SidebarMenuButton, {
492
+ tooltip: messages.label,
493
+ onClick: () => setOpen(true),
494
+ className: "border border-sidebar-border text-sidebar-foreground/80 hover:border-foreground/15",
495
+ children: [
496
+ /* @__PURE__ */ jsx4(Search, {}),
497
+ /* @__PURE__ */ jsx4("span", {
498
+ children: messages.label
499
+ }),
500
+ /* @__PURE__ */ jsx4(Kbd, {
501
+ className: "ml-auto group-data-[collapsible=icon]:hidden",
502
+ children: "\u2318K"
503
+ })
504
+ ]
505
+ })
506
+ })
507
+ }),
508
+ /* @__PURE__ */ jsxs2(CommandDialog, {
509
+ open,
510
+ onOpenChange: (next) => {
511
+ setOpen(next);
512
+ if (!next)
513
+ setQuery("");
514
+ },
515
+ title: messages.label,
516
+ className: "max-w-xl rounded-xl",
517
+ children: [
518
+ /* @__PURE__ */ jsx4(CommandInput, {
519
+ value: query,
520
+ onValueChange: setQuery,
521
+ placeholder: messages.placeholder
522
+ }),
523
+ /* @__PURE__ */ jsxs2(CommandList, {
524
+ className: "max-h-[min(28rem,70vh)]",
525
+ children: [
526
+ /* @__PURE__ */ jsx4(CommandEmpty, {
527
+ children: objects.isFetching ? messages.searching : messages.empty
528
+ }),
529
+ searching && objects.data && objects.data.items.length > 0 ? /* @__PURE__ */ jsx4(CommandGroup, {
530
+ heading: messages.objects,
531
+ children: objects.data.items.map((item) => /* @__PURE__ */ jsxs2(CommandItem, {
532
+ value: `object:${item.ref.objectTypeId}:${item.ref.primaryId}`,
533
+ keywords: [item.label, query],
534
+ onSelect: () => go(objectHref(item.ref.objectTypeId, item.ref.primaryId)),
535
+ children: [
536
+ /* @__PURE__ */ jsx4(Box, {}),
537
+ /* @__PURE__ */ jsx4("span", {
538
+ className: "min-w-0 flex-1 truncate",
539
+ children: item.label
540
+ }),
541
+ /* @__PURE__ */ jsx4("span", {
542
+ className: "text-xs text-muted-foreground",
543
+ children: item.ref.objectTypeId
544
+ })
545
+ ]
546
+ }, `${item.ref.objectTypeId}:${item.ref.primaryId}`))
547
+ }) : null,
548
+ appPages.length > 0 ? /* @__PURE__ */ jsx4(CommandGroup, {
549
+ heading: messages.pages,
550
+ children: appPages.map((page) => /* @__PURE__ */ jsx4(PageItem, {
551
+ page,
552
+ onSelect: go
553
+ }, page.href))
554
+ }) : null,
555
+ sections.map((section) => /* @__PURE__ */ jsx4(CommandGroup, {
556
+ heading: section.label,
557
+ children: section.pages.flatMap((entry) => ("group" in entry) ? entry.items : [entry]).map((page) => /* @__PURE__ */ jsx4(PageItem, {
558
+ page,
559
+ keywords: [section.label],
560
+ onSelect: go
561
+ }, page.href))
562
+ }, section.id))
563
+ ]
564
+ })
565
+ ]
566
+ })
567
+ ]
2734
568
  });
2735
569
  }
2736
- function secureSharedHtml(html, request, options) {
2737
- const nonce = randomBytes(18).toString("base64url");
2738
- const requestOrigin = new URL(request.url).origin;
2739
- let apiOrigin = requestOrigin;
2740
- try {
2741
- apiOrigin = new URL(options.apiBaseUrl ?? requestOrigin, requestOrigin).origin;
2742
- } catch {}
2743
- const apiSources = apiOrigin === requestOrigin ? [] : [apiOrigin];
2744
- const connectSources = ["'self'", ...apiSources];
2745
- const fileSources = ["'self'", ...apiSources, "data:", "blob:", "https:"];
2746
- const scriptSources = [`'nonce-${nonce}'`, "'strict-dynamic'", "'self'"];
2747
- const contentSecurityPolicy = [
2748
- "default-src 'none'",
2749
- "base-uri 'none'",
2750
- "object-src 'none'",
2751
- "frame-ancestors 'none'",
2752
- "form-action 'none'",
2753
- `script-src ${scriptSources.join(" ")}`,
2754
- "style-src 'self' 'unsafe-inline'",
2755
- `img-src ${fileSources.join(" ")}`,
2756
- `media-src ${fileSources.join(" ")}`,
2757
- "font-src 'self' data: https:",
2758
- `connect-src ${connectSources.join(" ")}`,
2759
- "manifest-src 'none'"
2760
- ].join("; ");
2761
- return {
2762
- html: html.replace(/<script(?![^>]*\snonce=)/g, `<script nonce="${nonce}"`),
2763
- headers: {
2764
- "cache-control": "no-store",
2765
- "content-security-policy": contentSecurityPolicy,
2766
- "permissions-policy": "camera=(), geolocation=(), microphone=(), payment=(), usb=(), browsing-topics=()",
2767
- "referrer-policy": "no-referrer",
2768
- "x-content-type-options": "nosniff",
2769
- "x-frame-options": "DENY",
2770
- "x-robots-tag": "noindex, nofollow, noarchive"
2771
- }
2772
- };
570
+ function PageItem({
571
+ page,
572
+ keywords,
573
+ onSelect
574
+ }) {
575
+ return /* @__PURE__ */ jsxs2(CommandItem, {
576
+ value: `page:${page.href}`,
577
+ keywords: [page.label, ...keywords ?? []],
578
+ onSelect: () => onSelect(page.href),
579
+ children: [
580
+ page.icon ? /* @__PURE__ */ jsx4(page.icon, {}) : null,
581
+ /* @__PURE__ */ jsx4("span", {
582
+ children: page.label
583
+ })
584
+ ]
585
+ });
2773
586
  }
2774
- var IMMUTABLE_ASSET_PATTERN = /^(?:(?:app|shared|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/;
2775
- function staticAssetHeaders(pathname) {
2776
- if (pathname === customAppManifestRoute) {
2777
- return {
2778
- "content-type": "application/manifest+json; charset=utf-8",
2779
- "cache-control": "no-cache"
2780
- };
2781
- }
2782
- const lastSegment = pathname.split("/").pop() ?? "";
2783
- if (!IMMUTABLE_ASSET_PATTERN.test(lastSegment)) {
587
+
588
+ // src/shell/section-nav.tsx
589
+ import {
590
+ SidebarGroup,
591
+ SidebarGroupContent,
592
+ SidebarMenu as SidebarMenu2,
593
+ SidebarMenuButton as SidebarMenuButton2,
594
+ SidebarMenuItem as SidebarMenuItem2
595
+ } from "@sixb/ui/components";
596
+ import { ChevronLeft } from "lucide-react";
597
+ import { Link } from "react-router-dom";
598
+
599
+ // src/sections/counts.ts
600
+ import {
601
+ listActionsOptions,
602
+ listObjectTypesOptions,
603
+ listRulesOptions,
604
+ listWorkflowsOptions,
605
+ objectCountOptions
606
+ } from "@sixb/client/hooks";
607
+ import { useQuery as useQuery3 } from "@tanstack/react-query";
608
+ function usePageCounts(section) {
609
+ const ontology = { enabled: section === "ontology", retry: false, staleTime: 30000 };
610
+ const types = useQuery3({ ...listObjectTypesOptions(), ...ontology }).data;
611
+ const objects = useQuery3({ ...objectCountOptions(), ...ontology }).data;
612
+ const actions = useQuery3({ ...listActionsOptions(), ...ontology }).data;
613
+ const workflows = useQuery3({ ...listWorkflowsOptions(), ...ontology }).data;
614
+ const rules = useQuery3({ ...listRulesOptions(), ...ontology }).data;
615
+ if (section !== "ontology")
2784
616
  return {};
2785
- }
2786
- return { "cache-control": "public, max-age=31536000, immutable" };
2787
- }
2788
- async function staticFileResponse(request, path, headers) {
2789
- const responseHeaders = new Headers(headers);
2790
- const originalFile = Bun.file(path);
2791
- let responseFile = originalFile;
2792
- if (isPrecompressedAsset(path)) {
2793
- responseHeaders.append("vary", "Accept-Encoding");
2794
- if (!request.headers.has("range")) {
2795
- for (const encoding of acceptedPrecompressedEncodings(request)) {
2796
- const candidate = Bun.file(`${path}.${encoding === "br" ? "br" : "gz"}`);
2797
- if (!await candidate.exists())
2798
- continue;
2799
- responseFile = candidate;
2800
- responseHeaders.set("content-encoding", encoding);
2801
- responseHeaders.set("content-type", originalFile.type);
2802
- break;
2803
- }
2804
- }
2805
- }
2806
- return new Response(request.method === "HEAD" ? null : responseFile, {
2807
- headers: responseHeaders
617
+ const counts = {
618
+ "/ontology/object-types": types?.length,
619
+ "/ontology/objects": objects,
620
+ "/ontology/actions": actions?.length,
621
+ "/ontology/workflows": workflows?.length,
622
+ "/ontology/rules": rules?.length
623
+ };
624
+ return Object.fromEntries(Object.entries(counts).filter((entry) => entry[1] !== undefined));
625
+ }
626
+
627
+ // src/shell/section-nav.tsx
628
+ import { jsx as jsx5, jsxs as jsxs3, Fragment as Fragment3 } from "react/jsx-runtime";
629
+ function SectionNav({ fallback = null, backHref = "/" }) {
630
+ useRegisterSectionNav();
631
+ const messages = useAppMessages2().sections;
632
+ const section = useCurrentSection2();
633
+ const counts = usePageCounts(section?.id);
634
+ if (!section)
635
+ return fallback;
636
+ const counted = (item) => counts[item.href] === undefined ? item : { ...item, badge: counts[item.href] };
637
+ const pages = section.pages.map((entry) => ("group" in entry) ? { ...entry, items: entry.items.map(counted) } : counted(entry));
638
+ return /* @__PURE__ */ jsxs3(Fragment3, {
639
+ children: [
640
+ /* @__PURE__ */ jsx5(SidebarGroup, {
641
+ children: /* @__PURE__ */ jsx5(SidebarGroupContent, {
642
+ children: /* @__PURE__ */ jsx5(SidebarMenu2, {
643
+ children: /* @__PURE__ */ jsx5(SidebarMenuItem2, {
644
+ children: /* @__PURE__ */ jsx5(SidebarMenuButton2, {
645
+ asChild: true,
646
+ tooltip: messages.back,
647
+ children: /* @__PURE__ */ jsxs3(Link, {
648
+ to: backHref,
649
+ children: [
650
+ /* @__PURE__ */ jsx5(ChevronLeft, {}),
651
+ /* @__PURE__ */ jsx5("span", {
652
+ className: "font-medium",
653
+ children: section.label
654
+ })
655
+ ]
656
+ })
657
+ })
658
+ })
659
+ })
660
+ })
661
+ }),
662
+ /* @__PURE__ */ jsx5(NavItems2, {
663
+ items: pages
664
+ })
665
+ ]
2808
666
  });
2809
667
  }
2810
- function isPrecompressedAsset(path) {
2811
- return path.endsWith(".js") || path.endsWith(".css");
2812
- }
2813
- function acceptedPrecompressedEncodings(request) {
2814
- const header = request.headers.get("accept-encoding");
2815
- if (!header)
2816
- return [];
2817
- const qualities = new Map;
2818
- for (const item of header.split(",")) {
2819
- const [rawName, ...parameters] = item.trim().split(";");
2820
- const name = rawName.toLowerCase();
2821
- let quality = 1;
2822
- for (const parameter of parameters) {
2823
- const match = parameter.trim().match(/^q=(0(?:\.\d+)?|1(?:\.0+)?)$/);
2824
- if (match)
2825
- quality = Number(match[1]);
2826
- }
2827
- qualities.set(name, quality);
2828
- }
2829
- const wildcard = qualities.get("*") ?? 0;
2830
- return ["br", "gzip"].map((encoding, preference) => ({
2831
- encoding,
2832
- preference,
2833
- quality: qualities.get(encoding) ?? wildcard
2834
- })).filter((candidate) => candidate.quality > 0).sort((left, right) => right.quality - left.quality || left.preference - right.preference).map((candidate) => candidate.encoding);
2835
- }
2836
- function fileResponse(request, file, headers = {}) {
2837
- return new Response(request.method === "HEAD" ? null : file, { headers });
2838
- }
2839
- function filePathResponse(request, path) {
2840
- return fileResponse(request, Bun.file(path));
2841
- }
2842
- function notFoundResponse() {
2843
- return new Response("Not Found", {
2844
- status: 404,
2845
- headers: {
2846
- "cache-control": "no-store"
2847
- }
668
+
669
+ // src/shell/user-menu.tsx
670
+ import {
671
+ Avatar,
672
+ AvatarFallback,
673
+ AvatarImage,
674
+ DropdownMenu,
675
+ DropdownMenuContent,
676
+ DropdownMenuItem,
677
+ DropdownMenuLabel,
678
+ DropdownMenuSeparator,
679
+ DropdownMenuTrigger,
680
+ nextTheme,
681
+ SidebarMenu as SidebarMenu3,
682
+ SidebarMenuButton as SidebarMenuButton3,
683
+ SidebarMenuItem as SidebarMenuItem3,
684
+ ThemePicker,
685
+ useSidebar
686
+ } from "@sixb/ui/components";
687
+ import { useOptionalTheme } from "@sixb/ui/hooks";
688
+ import { cn as cn3 } from "@sixb/ui/lib/utils";
689
+ import { ChevronsUpDown, CircleUserRound, Layers as Layers2, LogOut, SunMoon } from "lucide-react";
690
+ import { jsx as jsx6, jsxs as jsxs4, Fragment as Fragment4 } from "react/jsx-runtime";
691
+ function UserMenuRoot({ children }) {
692
+ const user = useCurrentUser2();
693
+ const signOut = useSignOut2();
694
+ const sections = useSections2();
695
+ const appMessages = useAppMessages2();
696
+ const messages = appMessages.userMenu;
697
+ const themeControls = useOptionalTheme();
698
+ const { isMobile } = useSidebar();
699
+ const items = /* @__PURE__ */ jsxs4(Fragment4, {
700
+ children: [
701
+ /* @__PURE__ */ jsx6(UserMenuItem, {
702
+ href: ARTIFACTS_HREF,
703
+ icon: Layers2,
704
+ children: appMessages.artifacts
705
+ }),
706
+ sections.map((section) => /* @__PURE__ */ jsx6(UserMenuItem, {
707
+ href: section.href,
708
+ icon: section.icon,
709
+ children: section.label
710
+ }, section.id)),
711
+ children
712
+ ]
713
+ });
714
+ return /* @__PURE__ */ jsx6(SidebarMenu3, {
715
+ children: /* @__PURE__ */ jsx6(SidebarMenuItem3, {
716
+ children: /* @__PURE__ */ jsxs4(DropdownMenu, {
717
+ children: [
718
+ /* @__PURE__ */ jsx6(DropdownMenuTrigger, {
719
+ asChild: true,
720
+ children: user ? /* @__PURE__ */ jsxs4(SidebarMenuButton3, {
721
+ size: "lg",
722
+ tooltip: displayName(user),
723
+ className: "data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",
724
+ children: [
725
+ /* @__PURE__ */ jsx6(Identity, {
726
+ user,
727
+ emailClassName: "text-sidebar-foreground/70"
728
+ }),
729
+ /* @__PURE__ */ jsx6(ChevronsUpDown, {
730
+ className: "ml-auto size-4"
731
+ })
732
+ ]
733
+ }) : /* @__PURE__ */ jsxs4(SidebarMenuButton3, {
734
+ tooltip: messages.signInOff,
735
+ className: "text-sidebar-foreground data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",
736
+ children: [
737
+ /* @__PURE__ */ jsx6(CircleUserRound, {}),
738
+ /* @__PURE__ */ jsx6("span", {
739
+ children: messages.signInOff
740
+ })
741
+ ]
742
+ })
743
+ }),
744
+ /* @__PURE__ */ jsxs4(DropdownMenuContent, {
745
+ side: isMobile ? "bottom" : "top",
746
+ align: "end",
747
+ sideOffset: 4,
748
+ className: "min-w-56 rounded-lg",
749
+ onCloseAutoFocus: (event) => event.preventDefault(),
750
+ children: [
751
+ user ? /* @__PURE__ */ jsxs4(Fragment4, {
752
+ children: [
753
+ /* @__PURE__ */ jsx6(DropdownMenuLabel, {
754
+ className: "p-0 font-normal",
755
+ children: /* @__PURE__ */ jsx6("div", {
756
+ className: "flex items-center gap-2 px-1 py-1.5 text-left text-sm",
757
+ children: /* @__PURE__ */ jsx6(Identity, {
758
+ user,
759
+ emailClassName: "text-muted-foreground"
760
+ })
761
+ })
762
+ }),
763
+ /* @__PURE__ */ jsx6(DropdownMenuSeparator, {})
764
+ ]
765
+ }) : null,
766
+ items,
767
+ themeControls ? /* @__PURE__ */ jsx6(DropdownMenuSeparator, {}) : null,
768
+ themeControls ? /* @__PURE__ */ jsxs4(DropdownMenuItem, {
769
+ "aria-keyshortcuts": "ArrowLeft ArrowRight",
770
+ onSelect: (event) => event.preventDefault(),
771
+ onKeyDown: (event) => {
772
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
773
+ return;
774
+ event.preventDefault();
775
+ themeControls.setTheme(nextTheme(themeControls.theme, event.key === "ArrowRight" ? 1 : -1));
776
+ },
777
+ children: [
778
+ /* @__PURE__ */ jsx6(SunMoon, {}),
779
+ /* @__PURE__ */ jsx6("span", {
780
+ className: "flex-1",
781
+ children: messages.theme
782
+ }),
783
+ /* @__PURE__ */ jsx6(ThemePicker, {
784
+ focusable: false
785
+ })
786
+ ]
787
+ }) : null,
788
+ user ? /* @__PURE__ */ jsxs4(Fragment4, {
789
+ children: [
790
+ /* @__PURE__ */ jsx6(DropdownMenuSeparator, {}),
791
+ /* @__PURE__ */ jsxs4(DropdownMenuItem, {
792
+ onClick: () => {
793
+ signOut().catch((error) => {
794
+ console.error("[SixbApp] Could not sign out:", error);
795
+ });
796
+ },
797
+ children: [
798
+ /* @__PURE__ */ jsx6(LogOut, {}),
799
+ /* @__PURE__ */ jsx6("span", {
800
+ children: messages.signOut
801
+ })
802
+ ]
803
+ })
804
+ ]
805
+ }) : null
806
+ ]
807
+ })
808
+ ]
809
+ })
810
+ })
2848
811
  });
2849
812
  }
2850
- function getHeadRoute(handler) {
2851
- return {
2852
- GET: handler,
2853
- HEAD: handler
2854
- };
2855
- }
2856
- function allMethodsRoute(handler) {
2857
- return {
2858
- GET: handler,
2859
- HEAD: handler,
2860
- POST: handler,
2861
- PUT: handler,
2862
- PATCH: handler,
2863
- DELETE: handler,
2864
- OPTIONS: handler
2865
- };
813
+ function displayName(user) {
814
+ return user.displayName ?? user.email;
2866
815
  }
2867
- async function importHtmlBundle(htmlPath, version) {
2868
- const bundleEntryPath = await prepareAppHtmlBundleEntry(htmlPath);
2869
- const url = pathToFileURL2(bundleEntryPath);
2870
- url.searchParams.set("v", String(version));
2871
- const htmlModule = await import(url.href);
2872
- return htmlModule.default;
816
+ function Identity({
817
+ user,
818
+ emailClassName
819
+ }) {
820
+ const name = displayName(user);
821
+ return /* @__PURE__ */ jsxs4(Fragment4, {
822
+ children: [
823
+ /* @__PURE__ */ jsxs4(Avatar, {
824
+ className: "h-8 w-8 rounded-md",
825
+ children: [
826
+ user.avatarUrl ? /* @__PURE__ */ jsx6(AvatarImage, {
827
+ src: user.avatarUrl,
828
+ alt: name
829
+ }) : null,
830
+ /* @__PURE__ */ jsx6(AvatarFallback, {
831
+ className: "rounded-md text-xs",
832
+ children: initials(name)
833
+ })
834
+ ]
835
+ }),
836
+ /* @__PURE__ */ jsxs4("div", {
837
+ className: "grid flex-1 text-left text-sm leading-tight",
838
+ children: [
839
+ /* @__PURE__ */ jsx6("span", {
840
+ className: "truncate font-semibold",
841
+ children: name
842
+ }),
843
+ user.displayName ? /* @__PURE__ */ jsx6("span", {
844
+ className: cn3("truncate text-xs", emailClassName),
845
+ children: user.email
846
+ }) : null
847
+ ]
848
+ })
849
+ ]
850
+ });
2873
851
  }
2874
- function htmlBundleRoute(bundle) {
2875
- return {
2876
- GET: bundle,
2877
- HEAD: bundle
2878
- };
852
+ function initials(name) {
853
+ const parts = name.trim().split(/\s+/).filter(Boolean);
854
+ if (parts.length === 0)
855
+ return "?";
856
+ if (parts.length === 1)
857
+ return parts[0].slice(0, 2).toUpperCase();
858
+ return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase();
859
+ }
860
+ function UserMenuItem({ href, icon: Icon, onSelect, children }) {
861
+ const content = /* @__PURE__ */ jsxs4(Fragment4, {
862
+ children: [
863
+ Icon ? /* @__PURE__ */ jsx6(Icon, {}) : null,
864
+ /* @__PURE__ */ jsx6("span", {
865
+ children
866
+ })
867
+ ]
868
+ });
869
+ return href ? /* @__PURE__ */ jsx6(DropdownMenuItem, {
870
+ asChild: true,
871
+ onSelect,
872
+ children: /* @__PURE__ */ jsx6("a", {
873
+ href,
874
+ children: content
875
+ })
876
+ }) : /* @__PURE__ */ jsx6(DropdownMenuItem, {
877
+ onSelect,
878
+ children: content
879
+ });
2879
880
  }
2880
- function manifestRoute(manifestPath) {
2881
- return getHeadRoute((request) => fileResponse(request, Bun.file(manifestPath), staticAssetHeaders(customAppManifestRoute)));
881
+ var UserMenu = Object.assign(UserMenuRoot, { Item: UserMenuItem });
882
+
883
+ // src/shell/app-shell.tsx
884
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
885
+ function AppShellProvider({ className, children, ...sidebarState }) {
886
+ return /* @__PURE__ */ jsx7(ThemeProvider, {
887
+ children: /* @__PURE__ */ jsx7(SidebarProvider, {
888
+ className: cn4("h-dvh overflow-hidden", className),
889
+ ...sidebarState,
890
+ children
891
+ })
892
+ });
2882
893
  }
2883
- function devServerInternalOrigin(host, port) {
2884
- if (host === "0.0.0.0") {
2885
- return `http://127.0.0.1:${port}`;
2886
- }
2887
- if (host === "::" || host === "[::]") {
2888
- return `http://[::1]:${port}`;
2889
- }
2890
- const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
2891
- return `http://${urlHost}:${port}`;
894
+ function AppShell({
895
+ nav,
896
+ brand,
897
+ header,
898
+ footer,
899
+ userMenu,
900
+ agent,
901
+ variant = "inset",
902
+ collapsible = "icon",
903
+ side = "left",
904
+ defaultOpen,
905
+ children
906
+ }) {
907
+ return /* @__PURE__ */ jsxs5(AppShellProvider, {
908
+ defaultOpen,
909
+ children: [
910
+ /* @__PURE__ */ jsxs5(Sidebar, {
911
+ variant,
912
+ collapsible,
913
+ side,
914
+ children: [
915
+ /* @__PURE__ */ jsxs5(SidebarHeader, {
916
+ children: [
917
+ brand === undefined ? /* @__PURE__ */ jsx7(Brand2, {}) : brand,
918
+ header === undefined ? /* @__PURE__ */ jsx7(SearchCommand, {
919
+ pages: isNavData(nav) ? nav : []
920
+ }) : header
921
+ ]
922
+ }),
923
+ /* @__PURE__ */ jsxs5(SidebarContent, {
924
+ children: [
925
+ /* @__PURE__ */ jsx7(SectionNav, {
926
+ fallback: isNavData(nav) ? /* @__PURE__ */ jsx7(NavItems2, {
927
+ items: nav
928
+ }) : nav
929
+ }),
930
+ collapsible === "none" ? null : /* @__PURE__ */ jsx7(CollapseToggle, {})
931
+ ]
932
+ }),
933
+ /* @__PURE__ */ jsxs5(SidebarFooter, {
934
+ children: [
935
+ footer,
936
+ userMenu === undefined ? /* @__PURE__ */ jsx7(UserMenu, {}) : userMenu
937
+ ]
938
+ }),
939
+ collapsible === "none" ? null : /* @__PURE__ */ jsx7(SidebarRail, {
940
+ className: variant === "inset" ? "after:hidden" : undefined
941
+ })
942
+ ]
943
+ }),
944
+ /* @__PURE__ */ jsxs5(SidebarInset, {
945
+ className: "min-h-0 overflow-hidden",
946
+ children: [
947
+ /* @__PURE__ */ jsx7("div", {
948
+ className: "flex h-12 shrink-0 items-center border-b border-border px-3 md:hidden",
949
+ children: /* @__PURE__ */ jsx7(SidebarTrigger, {
950
+ className: "-ml-1"
951
+ })
952
+ }),
953
+ /* @__PURE__ */ jsxs5("div", {
954
+ className: "relative flex min-h-0 flex-1",
955
+ children: [
956
+ /* @__PURE__ */ jsx7("div", {
957
+ className: "min-h-0 min-w-0 flex-1 overflow-y-auto",
958
+ children
959
+ }),
960
+ agent === undefined ? /* @__PURE__ */ jsx7(AgentDock, {}) : agent
961
+ ]
962
+ })
963
+ ]
964
+ })
965
+ ]
966
+ });
2892
967
  }
2893
- function spaHtmlRoute(internalOrigin, options = {}) {
2894
- return getHeadRoute(async (request) => {
2895
- const publicUrl = new URL(request.url);
2896
- if (isReservedSixbRoute(publicUrl.pathname) || isSharedNamespace(publicUrl.pathname) || isFrameworkPrivateRoute(publicUrl.pathname)) {
2897
- return notFoundResponse();
2898
- }
2899
- if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
2900
- return notFoundResponse();
2901
- }
2902
- const url = new URL(options.shellRoute ?? internalAppShellRoute, internalOrigin());
2903
- url.search = publicUrl.search;
2904
- const requestHeaders = new Headers(request.headers);
2905
- for (const header of [
2906
- "forwarded",
2907
- "host",
2908
- "x-forwarded-host",
2909
- "x-forwarded-port",
2910
- "x-forwarded-proto"
2911
- ]) {
2912
- requestHeaders.delete(header);
2913
- }
2914
- const bundleResponse = await fetch(new Request(url, { method: request.method, headers: requestHeaders }));
2915
- const responseHeaders = new Headers(bundleResponse.headers);
2916
- responseHeaders.delete("content-length");
2917
- responseHeaders.delete("etag");
2918
- if (request.method === "HEAD") {
2919
- return new Response(null, {
2920
- status: bundleResponse.status,
2921
- statusText: bundleResponse.statusText,
2922
- headers: responseHeaders
2923
- });
2924
- }
2925
- const html = restoreAppStaticUrls(await bundleResponse.text()).replace("</head>", '<script src="/__sixb/dev-reload.js"></script></head>');
2926
- return new Response(options.transformHtml?.(html) ?? html, {
2927
- status: bundleResponse.status,
2928
- statusText: bundleResponse.statusText,
2929
- headers: responseHeaders
2930
- });
968
+ function CollapseToggle() {
969
+ const { isMobile } = useSidebar2();
970
+ if (isMobile)
971
+ return null;
972
+ return /* @__PURE__ */ jsx7(SidebarGroup2, {
973
+ className: "mt-auto",
974
+ children: /* @__PURE__ */ jsx7(SidebarGroupContent2, {
975
+ children: /* @__PURE__ */ jsx7(SidebarMenu4, {
976
+ children: /* @__PURE__ */ jsx7(SidebarMenuItem4, {
977
+ children: /* @__PURE__ */ jsx7(SidebarCollapseToggle, {})
978
+ })
979
+ })
980
+ })
2931
981
  });
2932
982
  }
983
+ function isNavData(nav) {
984
+ return Array.isArray(nav);
985
+ }
2933
986
  export {
2934
- createCustomApp,
2935
- createTailwindCssCompiler,
2936
- devReloadResponse,
2937
- publicEnv2 as publicEnv
987
+ AgentChatPage2 as AgentChatPage,
988
+ AgentContextProvider2 as AgentContextProvider,
989
+ AgentDock,
990
+ AgentPanel,
991
+ AgentSurface,
992
+ AppShell,
993
+ AppShellProvider,
994
+ Brand2 as Brand,
995
+ Composer2 as Composer,
996
+ NavItems2 as NavItems,
997
+ SearchCommand,
998
+ SectionNav,
999
+ SyncButton2 as SyncButton,
1000
+ UserMenu,
1001
+ agentContext,
1002
+ publicEnv,
1003
+ setAgentSurfaceMode,
1004
+ useAgentContext2 as useAgentContext,
1005
+ useCurrentSection2 as useCurrentSection,
1006
+ useCurrentUser2 as useCurrentUser,
1007
+ useSections2 as useSections,
1008
+ useSignOut2 as useSignOut
2938
1009
  };
2939
1010
 
2940
- //# debugId=0F17895FA991402664756E2164756E21
1011
+ //# debugId=368EE3E094E928C464756E2164756E21