@sixb/app 0.1.11 → 0.1.12

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 (583) hide show
  1. package/LICENSE +2 -0
  2. package/README.md +25 -19
  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 +24 -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 +27 -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/bash/bash-tool-view.d.ts +17 -0
  39. package/dist/agent/bash/bash-tool-view.d.ts.map +1 -0
  40. package/dist/agent/bash/data.d.ts +35 -0
  41. package/dist/agent/bash/data.d.ts.map +1 -0
  42. package/dist/agent/bash/interpret.d.ts +84 -0
  43. package/dist/agent/bash/interpret.d.ts.map +1 -0
  44. package/dist/agent/bash/renderers.d.ts +31 -0
  45. package/dist/agent/bash/renderers.d.ts.map +1 -0
  46. package/dist/agent/bash/shell.d.ts +16 -0
  47. package/dist/agent/bash/shell.d.ts.map +1 -0
  48. package/dist/agent/components/activity-status.d.ts +13 -0
  49. package/dist/agent/components/activity-status.d.ts.map +1 -0
  50. package/dist/agent/components/agent-thread-switcher.d.ts +16 -0
  51. package/dist/agent/components/agent-thread-switcher.d.ts.map +1 -0
  52. package/dist/agent/components/composer.d.ts +47 -0
  53. package/dist/agent/components/composer.d.ts.map +1 -0
  54. package/dist/agent/components/context-chips.d.ts +7 -0
  55. package/dist/agent/components/context-chips.d.ts.map +1 -0
  56. package/dist/agent/components/context-picker.d.ts +16 -0
  57. package/dist/agent/components/context-picker.d.ts.map +1 -0
  58. package/dist/agent/components/conversation-panel.d.ts +82 -0
  59. package/dist/agent/components/conversation-panel.d.ts.map +1 -0
  60. package/dist/agent/components/file-attachment-card.d.ts +8 -0
  61. package/dist/agent/components/file-attachment-card.d.ts.map +1 -0
  62. package/dist/agent/components/message-parts.d.ts +13 -0
  63. package/dist/agent/components/message-parts.d.ts.map +1 -0
  64. package/dist/agent/components/message-view.d.ts +58 -0
  65. package/dist/agent/components/message-view.d.ts.map +1 -0
  66. package/dist/agent/components/model-controls.d.ts +20 -0
  67. package/dist/agent/components/model-controls.d.ts.map +1 -0
  68. package/dist/agent/components/model-picker-row.d.ts +8 -0
  69. package/dist/agent/components/model-picker-row.d.ts.map +1 -0
  70. package/dist/agent/components/provider-logo.d.ts +6 -0
  71. package/dist/agent/components/provider-logo.d.ts.map +1 -0
  72. package/dist/agent/components/provider-logos.d.ts +3 -0
  73. package/dist/agent/components/provider-logos.d.ts.map +1 -0
  74. package/dist/agent/components/reasoning-effort-slider.d.ts +11 -0
  75. package/dist/agent/components/reasoning-effort-slider.d.ts.map +1 -0
  76. package/dist/agent/components/sandbox-recovery.d.ts +6 -0
  77. package/dist/agent/components/sandbox-recovery.d.ts.map +1 -0
  78. package/dist/agent/components/transcript.d.ts +36 -0
  79. package/dist/agent/components/transcript.d.ts.map +1 -0
  80. package/dist/agent/components/web-fetch-tool-view.d.ts +5 -0
  81. package/dist/agent/components/web-fetch-tool-view.d.ts.map +1 -0
  82. package/dist/agent/components/web-search-tool-view.d.ts +5 -0
  83. package/dist/agent/components/web-search-tool-view.d.ts.map +1 -0
  84. package/dist/agent/components/web-sources.d.ts +9 -0
  85. package/dist/agent/components/web-sources.d.ts.map +1 -0
  86. package/dist/agent/document-preview/classify.d.ts +4 -0
  87. package/dist/agent/document-preview/classify.d.ts.map +1 -0
  88. package/dist/agent/document-preview/content-policy.d.ts +10 -0
  89. package/dist/agent/document-preview/content-policy.d.ts.map +1 -0
  90. package/dist/agent/document-preview/content.d.ts +26 -0
  91. package/dist/agent/document-preview/content.d.ts.map +1 -0
  92. package/dist/agent/document-preview/delimited.d.ts +19 -0
  93. package/dist/agent/document-preview/delimited.d.ts.map +1 -0
  94. package/dist/agent/document-preview/document-preview-root.d.ts +24 -0
  95. package/dist/agent/document-preview/document-preview-root.d.ts.map +1 -0
  96. package/dist/agent/document-preview/file-size.d.ts +3 -0
  97. package/dist/agent/document-preview/file-size.d.ts.map +1 -0
  98. package/dist/agent/document-preview/html.d.ts +9 -0
  99. package/dist/agent/document-preview/html.d.ts.map +1 -0
  100. package/dist/agent/document-preview/persistence.d.ts +6 -0
  101. package/dist/agent/document-preview/persistence.d.ts.map +1 -0
  102. package/dist/agent/document-preview/presentation.d.ts +3 -0
  103. package/dist/agent/document-preview/presentation.d.ts.map +1 -0
  104. package/dist/agent/document-preview/rendering.d.ts +14 -0
  105. package/dist/agent/document-preview/rendering.d.ts.map +1 -0
  106. package/dist/agent/document-preview/source.d.ts +13 -0
  107. package/dist/agent/document-preview/source.d.ts.map +1 -0
  108. package/dist/agent/document-preview/state.d.ts +27 -0
  109. package/dist/agent/document-preview/state.d.ts.map +1 -0
  110. package/dist/agent/document-preview/types.d.ts +33 -0
  111. package/dist/agent/document-preview/types.d.ts.map +1 -0
  112. package/dist/agent/format.d.ts +12 -0
  113. package/dist/agent/format.d.ts.map +1 -0
  114. package/dist/agent/hooks/use-agent-conversation.d.ts +338 -0
  115. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -0
  116. package/dist/agent/hooks/use-thread-stream.d.ts +22 -0
  117. package/dist/agent/hooks/use-thread-stream.d.ts.map +1 -0
  118. package/dist/agent/i18n/en.d.ts +589 -0
  119. package/dist/agent/i18n/en.d.ts.map +1 -0
  120. package/dist/agent/i18n/fr.d.ts +4 -0
  121. package/dist/agent/i18n/fr.d.ts.map +1 -0
  122. package/dist/agent/i18n/index.d.ts +1161 -0
  123. package/dist/agent/i18n/index.d.ts.map +1 -0
  124. package/dist/agent/live-run.d.ts +48 -0
  125. package/dist/agent/live-run.d.ts.map +1 -0
  126. package/dist/agent/model-selection.d.ts +33 -0
  127. package/dist/agent/model-selection.d.ts.map +1 -0
  128. package/dist/agent/object-context-title.d.ts +22 -0
  129. package/dist/agent/object-context-title.d.ts.map +1 -0
  130. package/dist/agent/parts.d.ts +42 -0
  131. package/dist/agent/parts.d.ts.map +1 -0
  132. package/dist/agent/react-router.d.ts +8 -0
  133. package/dist/agent/react-router.d.ts.map +1 -0
  134. package/dist/agent/read/interpret.d.ts +24 -0
  135. package/dist/agent/read/interpret.d.ts.map +1 -0
  136. package/dist/agent/read/read-tool-view.d.ts +5 -0
  137. package/dist/agent/read/read-tool-view.d.ts.map +1 -0
  138. package/dist/agent/requester-settings.d.ts +15 -0
  139. package/dist/agent/requester-settings.d.ts.map +1 -0
  140. package/dist/agent/run-presentation.d.ts +70 -0
  141. package/dist/agent/run-presentation.d.ts.map +1 -0
  142. package/dist/agent/thread-navigation.d.ts +5 -0
  143. package/dist/agent/thread-navigation.d.ts.map +1 -0
  144. package/dist/agent/types.d.ts +22 -0
  145. package/dist/agent/types.d.ts.map +1 -0
  146. package/dist/agent/utils/context-display.d.ts +5 -0
  147. package/dist/agent/utils/context-display.d.ts.map +1 -0
  148. package/dist/agent/utils/context-mention.d.ts +12 -0
  149. package/dist/agent/utils/context-mention.d.ts.map +1 -0
  150. package/dist/agent/utils/web-fetch.d.ts +4 -0
  151. package/dist/agent/utils/web-fetch.d.ts.map +1 -0
  152. package/dist/agent/utils/web-search.d.ts +20 -0
  153. package/dist/agent/utils/web-search.d.ts.map +1 -0
  154. package/dist/agent/view-file/interpret.d.ts +9 -0
  155. package/dist/agent/view-file/interpret.d.ts.map +1 -0
  156. package/dist/agent/view-file/view-file-tool-view.d.ts +9 -0
  157. package/dist/agent/view-file/view-file-tool-view.d.ts.map +1 -0
  158. package/dist/agent/workspace.d.ts +11 -0
  159. package/dist/agent/workspace.d.ts.map +1 -0
  160. package/dist/chunk-3a99tmwg.js +176 -0
  161. package/dist/chunk-3a99tmwg.js.map +10 -0
  162. package/dist/chunk-48pkffj6.js +20 -0
  163. package/dist/chunk-48pkffj6.js.map +10 -0
  164. package/dist/chunk-6n5pdqp0.js +115 -0
  165. package/dist/chunk-6n5pdqp0.js.map +11 -0
  166. package/dist/chunk-j97e06rg.js +10668 -0
  167. package/dist/chunk-j97e06rg.js.map +80 -0
  168. package/dist/chunk-md3p7qdt.js +379 -0
  169. package/dist/chunk-md3p7qdt.js.map +10 -0
  170. package/dist/chunk-shmw3f8t.js +251 -0
  171. package/dist/chunk-shmw3f8t.js.map +10 -0
  172. package/dist/chunk-yvhzn4ye.js +98 -0
  173. package/dist/chunk-yvhzn4ye.js.map +10 -0
  174. package/dist/chunk-zcxrt24m.js +148 -0
  175. package/dist/chunk-zcxrt24m.js.map +10 -0
  176. package/dist/codegen.d.ts +6 -4
  177. package/dist/codegen.d.ts.map +1 -1
  178. package/dist/createCustomApp.d.ts +14 -7
  179. package/dist/createCustomApp.d.ts.map +1 -1
  180. package/dist/index.d.ts +33 -3
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +958 -2890
  183. package/dist/index.js.map +14 -13
  184. package/dist/locale-messages.d.ts +72 -6
  185. package/dist/locale-messages.d.ts.map +1 -1
  186. package/dist/locale.d.ts +73 -8
  187. package/dist/locale.d.ts.map +1 -1
  188. package/dist/locale.js +10 -19
  189. package/dist/locale.js.map +3 -4
  190. package/dist/metadata.d.ts.map +1 -1
  191. package/dist/pages/data/connectors.d.ts +5 -0
  192. package/dist/pages/data/connectors.d.ts.map +1 -0
  193. package/dist/pages/data/datasets.d.ts +30 -0
  194. package/dist/pages/data/datasets.d.ts.map +1 -0
  195. package/dist/pages/data/live-updates.d.ts +13 -0
  196. package/dist/pages/data/live-updates.d.ts.map +1 -0
  197. package/dist/pages/data/messages.d.ts +354 -0
  198. package/dist/pages/data/messages.d.ts.map +1 -0
  199. package/dist/pages/data/pipeline-canvas.d.ts +34 -0
  200. package/dist/pages/data/pipeline-canvas.d.ts.map +1 -0
  201. package/dist/pages/data/pipelines.d.ts +9 -0
  202. package/dist/pages/data/pipelines.d.ts.map +1 -0
  203. package/dist/pages/data/projections.d.ts +10 -0
  204. package/dist/pages/data/projections.d.ts.map +1 -0
  205. package/dist/pages/data/schema.d.ts +20 -0
  206. package/dist/pages/data/schema.d.ts.map +1 -0
  207. package/dist/pages/data/shared.d.ts +13 -0
  208. package/dist/pages/data/shared.d.ts.map +1 -0
  209. package/dist/pages/data/sync-button.d.ts +15 -0
  210. package/dist/pages/data/sync-button.d.ts.map +1 -0
  211. package/dist/pages/data/syncs.d.ts +5 -0
  212. package/dist/pages/data/syncs.d.ts.map +1 -0
  213. package/dist/pages/home.d.ts +6 -0
  214. package/dist/pages/home.d.ts.map +1 -0
  215. package/dist/pages/mosaic.d.ts +5 -0
  216. package/dist/pages/mosaic.d.ts.map +1 -0
  217. package/dist/pages/observability/action-run.d.ts +19 -0
  218. package/dist/pages/observability/action-run.d.ts.map +1 -0
  219. package/dist/pages/observability/ai-usage/calls.d.ts +27 -0
  220. package/dist/pages/observability/ai-usage/calls.d.ts.map +1 -0
  221. package/dist/pages/observability/ai-usage/charts.d.ts +23 -0
  222. package/dist/pages/observability/ai-usage/charts.d.ts.map +1 -0
  223. package/dist/pages/observability/ai-usage/format.d.ts +101 -0
  224. package/dist/pages/observability/ai-usage/format.d.ts.map +1 -0
  225. package/dist/pages/observability/ai-usage/limits.d.ts +12 -0
  226. package/dist/pages/observability/ai-usage/limits.d.ts.map +1 -0
  227. package/dist/pages/observability/ai-usage/messages.d.ts +431 -0
  228. package/dist/pages/observability/ai-usage/messages.d.ts.map +1 -0
  229. package/dist/pages/observability/ai-usage/page.d.ts +6 -0
  230. package/dist/pages/observability/ai-usage/page.d.ts.map +1 -0
  231. package/dist/pages/observability/live-updates.d.ts +3 -0
  232. package/dist/pages/observability/live-updates.d.ts.map +1 -0
  233. package/dist/pages/observability/logs.d.ts +11 -0
  234. package/dist/pages/observability/logs.d.ts.map +1 -0
  235. package/dist/pages/observability/messages.d.ts +329 -0
  236. package/dist/pages/observability/messages.d.ts.map +1 -0
  237. package/dist/pages/observability/runs.d.ts +7 -0
  238. package/dist/pages/observability/runs.d.ts.map +1 -0
  239. package/dist/pages/observability/workflow-run.d.ts +6 -0
  240. package/dist/pages/observability/workflow-run.d.ts.map +1 -0
  241. package/dist/pages/ontology/actions.d.ts +3 -0
  242. package/dist/pages/ontology/actions.d.ts.map +1 -0
  243. package/dist/pages/ontology/components/action-button.d.ts +12 -0
  244. package/dist/pages/ontology/components/action-button.d.ts.map +1 -0
  245. package/dist/pages/ontology/components/action-param-null-control.d.ts +7 -0
  246. package/dist/pages/ontology/components/action-param-null-control.d.ts.map +1 -0
  247. package/dist/pages/ontology/components/collection-toolbar.d.ts +21 -0
  248. package/dist/pages/ontology/components/collection-toolbar.d.ts.map +1 -0
  249. package/dist/pages/ontology/components/common.d.ts +16 -0
  250. package/dist/pages/ontology/components/common.d.ts.map +1 -0
  251. package/dist/pages/ontology/components/file-ref-upload-field.d.ts +13 -0
  252. package/dist/pages/ontology/components/file-ref-upload-field.d.ts.map +1 -0
  253. package/dist/pages/ontology/components/object-filter-popover.d.ts +9 -0
  254. package/dist/pages/ontology/components/object-filter-popover.d.ts.map +1 -0
  255. package/dist/pages/ontology/components/object-icon.d.ts +7 -0
  256. package/dist/pages/ontology/components/object-icon.d.ts.map +1 -0
  257. package/dist/pages/ontology/components/object-query-bar.d.ts +21 -0
  258. package/dist/pages/ontology/components/object-query-bar.d.ts.map +1 -0
  259. package/dist/pages/ontology/components/telemetry-chart.d.ts +18 -0
  260. package/dist/pages/ontology/components/telemetry-chart.d.ts.map +1 -0
  261. package/dist/pages/ontology/components/telemetry-grid.d.ts +19 -0
  262. package/dist/pages/ontology/components/telemetry-grid.d.ts.map +1 -0
  263. package/dist/pages/ontology/components/telemetry-tile.d.ts +18 -0
  264. package/dist/pages/ontology/components/telemetry-tile.d.ts.map +1 -0
  265. package/dist/pages/ontology/components/telemetry-value.d.ts +10 -0
  266. package/dist/pages/ontology/components/telemetry-value.d.ts.map +1 -0
  267. package/dist/pages/ontology/components/usage-bar.d.ts +12 -0
  268. package/dist/pages/ontology/components/usage-bar.d.ts.map +1 -0
  269. package/dist/pages/ontology/graph.d.ts +6 -0
  270. package/dist/pages/ontology/graph.d.ts.map +1 -0
  271. package/dist/pages/ontology/hooks/object-live-updates.d.ts +5 -0
  272. package/dist/pages/ontology/hooks/object-live-updates.d.ts.map +1 -0
  273. package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts +8 -0
  274. package/dist/pages/ontology/hooks/object-telemetry-updates.d.ts.map +1 -0
  275. package/dist/pages/ontology/hooks/object-type-counts.d.ts +5 -0
  276. package/dist/pages/ontology/hooks/object-type-counts.d.ts.map +1 -0
  277. package/dist/pages/ontology/hooks/rule-live-updates.d.ts +9 -0
  278. package/dist/pages/ontology/hooks/rule-live-updates.d.ts.map +1 -0
  279. package/dist/pages/ontology/hooks/workflow-live-updates.d.ts +6 -0
  280. package/dist/pages/ontology/hooks/workflow-live-updates.d.ts.map +1 -0
  281. package/dist/pages/ontology/lib/action-params.d.ts +55 -0
  282. package/dist/pages/ontology/lib/action-params.d.ts.map +1 -0
  283. package/dist/pages/ontology/lib/format-value.d.ts +3 -0
  284. package/dist/pages/ontology/lib/format-value.d.ts.map +1 -0
  285. package/dist/pages/ontology/lib/labels.d.ts +3 -0
  286. package/dist/pages/ontology/lib/labels.d.ts.map +1 -0
  287. package/dist/pages/ontology/lib/live-update-keys.d.ts +15 -0
  288. package/dist/pages/ontology/lib/live-update-keys.d.ts.map +1 -0
  289. package/dist/pages/ontology/lib/object-query.d.ts +72 -0
  290. package/dist/pages/ontology/lib/object-query.d.ts.map +1 -0
  291. package/dist/pages/ontology/lib/ontology-graph-layout.d.ts +68 -0
  292. package/dist/pages/ontology/lib/ontology-graph-layout.d.ts.map +1 -0
  293. package/dist/pages/ontology/lib/ontology-graph-links.d.ts +4 -0
  294. package/dist/pages/ontology/lib/ontology-graph-links.d.ts.map +1 -0
  295. package/dist/pages/ontology/lib/telemetry-history.d.ts +10 -0
  296. package/dist/pages/ontology/lib/telemetry-history.d.ts.map +1 -0
  297. package/dist/pages/ontology/lib/time.d.ts +3 -0
  298. package/dist/pages/ontology/lib/time.d.ts.map +1 -0
  299. package/dist/pages/ontology/lib/user-preferences.d.ts +8 -0
  300. package/dist/pages/ontology/lib/user-preferences.d.ts.map +1 -0
  301. package/dist/pages/ontology/object-page.d.ts +7 -0
  302. package/dist/pages/ontology/object-page.d.ts.map +1 -0
  303. package/dist/pages/ontology/object-type.d.ts +3 -0
  304. package/dist/pages/ontology/object-type.d.ts.map +1 -0
  305. package/dist/pages/ontology/object-types.d.ts +7 -0
  306. package/dist/pages/ontology/object-types.d.ts.map +1 -0
  307. package/dist/pages/ontology/objects.d.ts +6 -0
  308. package/dist/pages/ontology/objects.d.ts.map +1 -0
  309. package/dist/pages/ontology/rules.d.ts +32 -0
  310. package/dist/pages/ontology/rules.d.ts.map +1 -0
  311. package/dist/pages/ontology/workflow.d.ts +6 -0
  312. package/dist/pages/ontology/workflow.d.ts.map +1 -0
  313. package/dist/pages/ontology/workflows/agent-execution-panel.d.ts +17 -0
  314. package/dist/pages/ontology/workflows/agent-execution-panel.d.ts.map +1 -0
  315. package/dist/pages/ontology/workflows/intervention-panel.d.ts +5 -0
  316. package/dist/pages/ontology/workflows/intervention-panel.d.ts.map +1 -0
  317. package/dist/pages/ontology/workflows/node-execution-panel.d.ts +11 -0
  318. package/dist/pages/ontology/workflows/node-execution-panel.d.ts.map +1 -0
  319. package/dist/pages/ontology/workflows/request-run-dialog.d.ts +5 -0
  320. package/dist/pages/ontology/workflows/request-run-dialog.d.ts.map +1 -0
  321. package/dist/pages/ontology/workflows/run-debug-section.d.ts +11 -0
  322. package/dist/pages/ontology/workflows/run-debug-section.d.ts.map +1 -0
  323. package/dist/pages/ontology/workflows/run-input-form.d.ts +18 -0
  324. package/dist/pages/ontology/workflows/run-input-form.d.ts.map +1 -0
  325. package/dist/pages/ontology/workflows/run-progress.d.ts +15 -0
  326. package/dist/pages/ontology/workflows/run-progress.d.ts.map +1 -0
  327. package/dist/pages/ontology/workflows/schema-shape.d.ts +10 -0
  328. package/dist/pages/ontology/workflows/schema-shape.d.ts.map +1 -0
  329. package/dist/pages/ontology/workflows/status-badge.d.ts +5 -0
  330. package/dist/pages/ontology/workflows/status-badge.d.ts.map +1 -0
  331. package/dist/pages/ontology/workflows/utils.d.ts +29 -0
  332. package/dist/pages/ontology/workflows/utils.d.ts.map +1 -0
  333. package/dist/pages/ontology/workflows/workflow-card.d.ts +5 -0
  334. package/dist/pages/ontology/workflows/workflow-card.d.ts.map +1 -0
  335. package/dist/pages/ontology/workflows.d.ts +3 -0
  336. package/dist/pages/ontology/workflows.d.ts.map +1 -0
  337. package/dist/pages/routes.d.ts +19 -0
  338. package/dist/pages/routes.d.ts.map +1 -0
  339. package/dist/pages/section-page.d.ts +91 -0
  340. package/dist/pages/section-page.d.ts.map +1 -0
  341. package/dist/pages/section-ui.d.ts +211 -0
  342. package/dist/pages/section-ui.d.ts.map +1 -0
  343. package/dist/pages/settings/controls.d.ts +94 -0
  344. package/dist/pages/settings/controls.d.ts.map +1 -0
  345. package/dist/pages/settings/developers.d.ts +3 -0
  346. package/dist/pages/settings/developers.d.ts.map +1 -0
  347. package/dist/pages/settings/members.d.ts +3 -0
  348. package/dist/pages/settings/members.d.ts.map +1 -0
  349. package/dist/pages/settings/messages.d.ts +538 -0
  350. package/dist/pages/settings/messages.d.ts.map +1 -0
  351. package/dist/pages/settings/personal.d.ts +6 -0
  352. package/dist/pages/settings/personal.d.ts.map +1 -0
  353. package/dist/pages/settings/service-accounts.d.ts +3 -0
  354. package/dist/pages/settings/service-accounts.d.ts.map +1 -0
  355. package/dist/pages/settings/sessions.d.ts +3 -0
  356. package/dist/pages/settings/sessions.d.ts.map +1 -0
  357. package/dist/pages/values.d.ts +77 -0
  358. package/dist/pages/values.d.ts.map +1 -0
  359. package/dist/pages.d.ts +42 -0
  360. package/dist/pages.d.ts.map +1 -0
  361. package/dist/pages.js +23931 -0
  362. package/dist/pages.js.map +85 -0
  363. package/dist/runtime.d.ts +0 -2
  364. package/dist/runtime.d.ts.map +1 -1
  365. package/dist/sections/catalog.d.ts +37 -0
  366. package/dist/sections/catalog.d.ts.map +1 -0
  367. package/dist/sections/counts.d.ts +7 -0
  368. package/dist/sections/counts.d.ts.map +1 -0
  369. package/dist/sections/sections.d.ts +67 -0
  370. package/dist/sections/sections.d.ts.map +1 -0
  371. package/dist/server.d.ts +8 -0
  372. package/dist/server.d.ts.map +1 -0
  373. package/dist/server.js +2983 -0
  374. package/dist/server.js.map +19 -0
  375. package/dist/session.d.ts +18 -0
  376. package/dist/session.d.ts.map +1 -0
  377. package/dist/shell/agent-dock.d.ts +7 -0
  378. package/dist/shell/agent-dock.d.ts.map +1 -0
  379. package/dist/shell/app-shell.d.ts +42 -0
  380. package/dist/shell/app-shell.d.ts.map +1 -0
  381. package/dist/shell/brand.d.ts +15 -0
  382. package/dist/shell/brand.d.ts.map +1 -0
  383. package/dist/shell/nav-items.d.ts +34 -0
  384. package/dist/shell/nav-items.d.ts.map +1 -0
  385. package/dist/shell/search-command.d.ts +12 -0
  386. package/dist/shell/search-command.d.ts.map +1 -0
  387. package/dist/shell/section-nav.d.ts +13 -0
  388. package/dist/shell/section-nav.d.ts.map +1 -0
  389. package/dist/shell/user-menu.d.ts +25 -0
  390. package/dist/shell/user-menu.d.ts.map +1 -0
  391. package/dist/tailwind.d.ts +4 -4
  392. package/dist/tailwind.d.ts.map +1 -1
  393. package/package.json +24 -21
  394. package/src/agent/activity-label.ts +63 -0
  395. package/src/agent/agent-chat.tsx +237 -0
  396. package/src/agent/agent-context-provider.tsx +92 -0
  397. package/src/agent/agent-execution-trace.tsx +316 -0
  398. package/src/agent/agent-panel.tsx +79 -0
  399. package/src/agent/agent-surface-state.ts +113 -0
  400. package/src/agent/agent-surface.tsx +363 -0
  401. package/src/agent/agent.css +231 -0
  402. package/src/agent/bash/bash-tool-view.tsx +288 -0
  403. package/src/agent/bash/data.ts +137 -0
  404. package/src/agent/bash/interpret.ts +769 -0
  405. package/src/agent/bash/renderers.tsx +503 -0
  406. package/src/agent/bash/shell.ts +195 -0
  407. package/src/agent/components/activity-status.tsx +86 -0
  408. package/src/agent/components/agent-thread-switcher.tsx +346 -0
  409. package/src/agent/components/composer.tsx +870 -0
  410. package/src/agent/components/context-chips.tsx +63 -0
  411. package/src/agent/components/context-picker.tsx +88 -0
  412. package/src/agent/components/conversation-panel.tsx +352 -0
  413. package/src/agent/components/file-attachment-card.tsx +137 -0
  414. package/src/agent/components/message-parts.tsx +280 -0
  415. package/src/agent/components/message-view.tsx +428 -0
  416. package/src/agent/components/model-controls.tsx +204 -0
  417. package/src/agent/components/model-picker-row.tsx +136 -0
  418. package/src/agent/components/provider-logo.tsx +31 -0
  419. package/src/agent/components/provider-logos.ts +24 -0
  420. package/src/agent/components/reasoning-effort-slider.tsx +121 -0
  421. package/src/agent/components/sandbox-recovery.tsx +49 -0
  422. package/src/agent/components/transcript.tsx +239 -0
  423. package/src/agent/components/web-fetch-tool-view.tsx +69 -0
  424. package/src/agent/components/web-search-tool-view.tsx +37 -0
  425. package/src/agent/components/web-sources.tsx +159 -0
  426. package/src/agent/document-preview/classify.ts +55 -0
  427. package/src/agent/document-preview/content-policy.ts +37 -0
  428. package/src/agent/document-preview/content.ts +82 -0
  429. package/src/agent/document-preview/delimited.ts +118 -0
  430. package/src/agent/document-preview/document-preview-root.tsx +1017 -0
  431. package/src/agent/document-preview/file-size.ts +26 -0
  432. package/src/agent/document-preview/html.ts +67 -0
  433. package/src/agent/document-preview/persistence.ts +115 -0
  434. package/src/agent/document-preview/presentation.ts +13 -0
  435. package/src/agent/document-preview/rendering.ts +48 -0
  436. package/src/agent/document-preview/source.ts +48 -0
  437. package/src/agent/document-preview/state.ts +77 -0
  438. package/src/agent/document-preview/types.ts +36 -0
  439. package/src/agent/format.ts +60 -0
  440. package/src/agent/hooks/use-agent-conversation.ts +536 -0
  441. package/src/agent/hooks/use-thread-stream.ts +121 -0
  442. package/src/agent/i18n/en.ts +542 -0
  443. package/src/agent/i18n/fr.ts +574 -0
  444. package/src/agent/i18n/index.ts +14 -0
  445. package/src/agent/live-run.ts +257 -0
  446. package/src/agent/model-selection.ts +88 -0
  447. package/src/agent/object-context-title.ts +57 -0
  448. package/src/agent/parts.ts +119 -0
  449. package/src/agent/react-router.tsx +84 -0
  450. package/src/agent/read/interpret.ts +101 -0
  451. package/src/agent/read/read-tool-view.tsx +92 -0
  452. package/src/agent/requester-settings.ts +55 -0
  453. package/src/agent/run-presentation.ts +211 -0
  454. package/src/agent/thread-navigation.ts +11 -0
  455. package/src/agent/types.ts +37 -0
  456. package/src/agent/utils/context-display.ts +72 -0
  457. package/src/agent/utils/context-mention.ts +28 -0
  458. package/src/agent/utils/web-fetch.ts +20 -0
  459. package/src/agent/utils/web-search.ts +106 -0
  460. package/src/agent/view-file/interpret.ts +22 -0
  461. package/src/agent/view-file/view-file-tool-view.tsx +120 -0
  462. package/src/{agents.ts → agent/workspace.ts} +4 -19
  463. package/src/codegen.ts +61 -79
  464. package/src/createCustomApp.ts +155 -67
  465. package/src/index.ts +52 -16
  466. package/src/locale-messages.ts +121 -12
  467. package/src/locale.ts +1 -2
  468. package/src/metadata.ts +35 -1
  469. package/src/pages/canvas.css +43 -0
  470. package/src/pages/data/connectors.tsx +317 -0
  471. package/src/pages/data/datasets.tsx +731 -0
  472. package/src/pages/data/live-updates.ts +71 -0
  473. package/src/pages/data/messages.ts +349 -0
  474. package/src/pages/data/pipeline-canvas.tsx +288 -0
  475. package/src/pages/data/pipelines.tsx +710 -0
  476. package/src/pages/data/projections.tsx +482 -0
  477. package/src/pages/data/schema.tsx +62 -0
  478. package/src/pages/data/shared.tsx +78 -0
  479. package/src/pages/data/sync-button.tsx +103 -0
  480. package/src/pages/data/syncs.tsx +326 -0
  481. package/src/pages/home.tsx +64 -0
  482. package/src/pages/mosaic.tsx +97 -0
  483. package/src/pages/observability/action-run.tsx +229 -0
  484. package/src/pages/observability/ai-usage/calls.tsx +541 -0
  485. package/src/pages/observability/ai-usage/charts.tsx +126 -0
  486. package/src/pages/observability/ai-usage/format.ts +276 -0
  487. package/src/pages/observability/ai-usage/limits.tsx +629 -0
  488. package/src/pages/observability/ai-usage/messages.ts +446 -0
  489. package/src/pages/observability/ai-usage/page.tsx +814 -0
  490. package/src/pages/observability/live-updates.ts +19 -0
  491. package/src/pages/observability/logs.tsx +617 -0
  492. package/src/pages/observability/messages.ts +336 -0
  493. package/src/pages/observability/runs.tsx +732 -0
  494. package/src/pages/observability/workflow-run.tsx +323 -0
  495. package/src/pages/ontology/actions.tsx +749 -0
  496. package/src/pages/ontology/components/action-button.tsx +355 -0
  497. package/src/pages/ontology/components/action-param-null-control.tsx +35 -0
  498. package/src/pages/ontology/components/collection-toolbar.tsx +61 -0
  499. package/src/pages/ontology/components/common.tsx +60 -0
  500. package/src/pages/ontology/components/file-ref-upload-field.tsx +279 -0
  501. package/src/pages/ontology/components/object-filter-popover.tsx +311 -0
  502. package/src/pages/ontology/components/object-icon.tsx +133 -0
  503. package/src/pages/ontology/components/object-query-bar.tsx +217 -0
  504. package/src/pages/ontology/components/telemetry-chart.tsx +392 -0
  505. package/src/pages/ontology/components/telemetry-grid.tsx +137 -0
  506. package/src/pages/ontology/components/telemetry-tile.tsx +164 -0
  507. package/src/pages/ontology/components/telemetry-value.tsx +91 -0
  508. package/src/pages/ontology/components/usage-bar.tsx +64 -0
  509. package/src/pages/ontology/graph.tsx +1283 -0
  510. package/src/pages/ontology/hooks/object-live-updates.ts +53 -0
  511. package/src/pages/ontology/hooks/object-telemetry-updates.ts +45 -0
  512. package/src/pages/ontology/hooks/object-type-counts.ts +27 -0
  513. package/src/pages/ontology/hooks/rule-live-updates.ts +28 -0
  514. package/src/pages/ontology/hooks/workflow-live-updates.ts +20 -0
  515. package/src/pages/ontology/lib/action-params.ts +231 -0
  516. package/src/pages/ontology/lib/format-value.ts +34 -0
  517. package/src/pages/ontology/lib/labels.ts +50 -0
  518. package/src/pages/ontology/lib/live-update-keys.ts +62 -0
  519. package/src/pages/ontology/lib/object-query.ts +372 -0
  520. package/src/pages/ontology/lib/ontology-graph-layout.ts +1004 -0
  521. package/src/pages/ontology/lib/ontology-graph-links.ts +15 -0
  522. package/src/pages/ontology/lib/telemetry-history.ts +56 -0
  523. package/src/pages/ontology/lib/time.ts +23 -0
  524. package/src/pages/ontology/lib/user-preferences.ts +52 -0
  525. package/src/pages/ontology/object-page.tsx +1029 -0
  526. package/src/pages/ontology/object-type.tsx +910 -0
  527. package/src/pages/ontology/object-types.tsx +240 -0
  528. package/src/pages/ontology/objects.tsx +938 -0
  529. package/src/pages/ontology/rules.tsx +805 -0
  530. package/src/pages/ontology/workflow.tsx +1485 -0
  531. package/src/pages/ontology/workflows/agent-execution-panel.tsx +340 -0
  532. package/src/pages/ontology/workflows/intervention-panel.tsx +261 -0
  533. package/src/pages/ontology/workflows/node-execution-panel.tsx +86 -0
  534. package/src/pages/ontology/workflows/request-run-dialog.tsx +197 -0
  535. package/src/pages/ontology/workflows/run-debug-section.tsx +54 -0
  536. package/src/pages/ontology/workflows/run-input-form.tsx +900 -0
  537. package/src/pages/ontology/workflows/run-progress.tsx +83 -0
  538. package/src/pages/ontology/workflows/schema-shape.tsx +206 -0
  539. package/src/pages/ontology/workflows/status-badge.tsx +15 -0
  540. package/src/pages/ontology/workflows/utils.ts +107 -0
  541. package/src/pages/ontology/workflows/workflow-card.tsx +48 -0
  542. package/src/pages/ontology/workflows.tsx +143 -0
  543. package/src/pages/routes.ts +48 -0
  544. package/src/pages/section-page.tsx +272 -0
  545. package/src/pages/section-ui.tsx +771 -0
  546. package/src/pages/settings/controls.tsx +721 -0
  547. package/src/pages/settings/developers.tsx +163 -0
  548. package/src/pages/settings/members.tsx +1018 -0
  549. package/src/pages/settings/messages.ts +551 -0
  550. package/src/pages/settings/personal.tsx +97 -0
  551. package/src/pages/settings/service-accounts.tsx +623 -0
  552. package/src/pages/settings/sessions.tsx +183 -0
  553. package/src/pages/values.tsx +700 -0
  554. package/src/pages.ts +56 -0
  555. package/src/runtime.ts +0 -3
  556. package/src/sections/catalog.ts +181 -0
  557. package/src/sections/counts.ts +33 -0
  558. package/src/sections/sections.tsx +257 -0
  559. package/src/server.ts +19 -0
  560. package/src/session.ts +29 -0
  561. package/src/shell/agent-dock.tsx +32 -0
  562. package/src/shell/app-shell.tsx +142 -0
  563. package/src/shell/brand.tsx +47 -0
  564. package/src/shell/nav-items.tsx +136 -0
  565. package/src/shell/search-command.tsx +158 -0
  566. package/src/shell/section-nav.tsx +61 -0
  567. package/src/shell/user-menu.tsx +206 -0
  568. package/src/tailwind.ts +4 -4
  569. package/dist/agents.d.ts +0 -11
  570. package/dist/agents.d.ts.map +0 -1
  571. package/dist/agents.js +0 -41
  572. package/dist/agents.js.map +0 -10
  573. package/dist/auth.js +0 -3
  574. package/dist/auth.js.map +0 -9
  575. package/dist/browser.d.ts +0 -3
  576. package/dist/browser.d.ts.map +0 -1
  577. package/dist/browser.js +0 -9
  578. package/dist/browser.js.map +0 -9
  579. package/dist/chunk-cftmy40z.js +0 -70
  580. package/dist/chunk-cftmy40z.js.map +0 -10
  581. package/dist/chunk-e1gj8c1a.js +0 -8
  582. package/dist/chunk-e1gj8c1a.js.map +0 -10
  583. package/src/browser.ts +0 -2
package/dist/index.js CHANGED
@@ -1,2940 +1,1008 @@
1
1
  // @bun
2
2
  import {
3
- publicEnv2
4
- } from "./chunk-e1gj8c1a.js";
3
+ AgentContextProvider2,
4
+ useAgentContext2,
5
+ useRegisteredAgentContext,
6
+ useAgentMessages,
7
+ Composer2,
8
+ AgentChat,
9
+ AgentChatPage2,
10
+ AgentWorkspaceProvider2,
11
+ SyncButton2,
12
+ useCurrentUser2,
13
+ useSignOut2,
14
+ NavItems2,
15
+ isExternal,
16
+ useSectionsEnabled,
17
+ useSections2,
18
+ useCurrentSection2,
19
+ useRegisterSectionNav,
20
+ Brand2,
21
+ objectHref
22
+ } from "./chunk-j97e06rg.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]"
24
+ useAppMessages2
25
+ } from "./chunk-48pkffj6.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
+ documentPreviewHost,
41
+ splitDocumentPreview,
42
+ conversationHeaderActions,
43
+ composerPlaceholder,
44
+ compact = true,
45
+ className,
46
+ welcomeContent,
47
+ documentPreviewRenderers
48
+ }) {
49
+ const registeredContext = useRegisteredAgentContext();
50
+ const ambientContext = context === undefined ? registeredContext : context;
51
+ const controlled = controlledThreadId !== undefined;
52
+ const [localThreadId, setLocalThreadId] = useState(defaultThreadId);
53
+ const threadId = controlled ? controlledThreadId : localThreadId;
54
+ const changeThread = useCallback((nextThreadId) => {
55
+ if (!controlled)
56
+ setLocalThreadId(nextThreadId);
57
+ onThreadChange?.(nextThreadId);
58
+ }, [controlled, onThreadChange]);
59
+ return /* @__PURE__ */ jsx(AgentChat, {
60
+ threadId,
61
+ ambientContext,
62
+ compact,
63
+ documentPreviewHost,
64
+ splitDocumentPreview,
65
+ conversationHeaderActions,
66
+ composerPlaceholder,
67
+ welcomeContent,
68
+ onNavigateHome: () => {
69
+ changeThread(null);
70
+ onNewThread?.();
114
71
  },
115
- plugins: [extensionlessSourceImportPlugin],
116
- define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
117
- sourcemap: development ? "inline" : "external"
72
+ onNavigateThread: changeThread,
73
+ documentPreviewRenderers,
74
+ className: cn("min-h-0 overflow-hidden bg-background", className)
118
75
  });
119
76
  }
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 };
77
+ // src/agent/agent-surface.tsx
78
+ import { Button } from "@sixb/ui/components";
79
+ import { cn as cn2 } from "@sixb/ui/lib/utils";
80
+ import { ChevronRight, Maximize2, MessageSquareText, Minimize2 } from "lucide-react";
81
+ import {
82
+ useCallback as useCallback2,
83
+ useEffect,
84
+ useRef,
85
+ useState as useState2
86
+ } from "react";
87
+
88
+ // src/agent/agent-surface-state.ts
89
+ var DEFAULT_AGENT_SURFACE_WIDTH = 384;
90
+ var MIN_AGENT_SURFACE_WIDTH = 320;
91
+ var MAX_AGENT_SURFACE_WIDTH = 720;
92
+ var AGENT_SURFACE_STATE_EVENT = "sixb:agent-surface-state";
93
+ function agentSurfaceSessionStorageKey(override) {
94
+ if (override === false)
95
+ return null;
96
+ return override ?? "sixb.agent-ui.surface.v1:agents";
157
97
  }
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) {
98
+ function parseAgentSurfaceSessionState(raw, defaults, minimumWidth = MIN_AGENT_SURFACE_WIDTH, maximumWidth = MAX_AGENT_SURFACE_WIDTH) {
99
+ if (!raw)
100
+ return defaults;
101
+ try {
102
+ const value = JSON.parse(raw);
103
+ if (!isRecord(value))
104
+ return defaults;
181
105
  return {
182
- success: false,
183
- outdir,
184
- logs: result.logs.map(String)
106
+ mode: value.mode === "collapsed" || value.mode === "dock" ? value.mode : defaults.mode,
107
+ dockWidth: typeof value.dockWidth === "number" && Number.isFinite(value.dockWidth) ? clampAgentSurfaceWidth(value.dockWidth, minimumWidth, maximumWidth) : defaults.dockWidth,
108
+ threadId: value.threadId === null || typeof value.threadId === "string" && value.threadId.length > 0 ? value.threadId : defaults.threadId
185
109
  };
110
+ } catch {
111
+ return defaults;
186
112
  }
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
113
  }
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
- `;
114
+ function clampAgentSurfaceWidth(width, minimumWidth, maximumWidth) {
115
+ return Math.min(Math.max(Math.round(width), minimumWidth), maximumWidth);
296
116
  }
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
117
+ function setAgentSurfaceMode(mode, override) {
118
+ const storageKey = agentSurfaceSessionStorageKey(override);
119
+ if (!storageKey || typeof window === "undefined")
120
+ return;
121
+ const defaults = {
122
+ mode,
123
+ dockWidth: DEFAULT_AGENT_SURFACE_WIDTH,
124
+ threadId: null
364
125
  };
126
+ updateAgentSurfaceState(storageKey, defaults, (current) => ({ ...current, mode }));
127
+ }
128
+ function updateAgentSurfaceState(storageKey, defaults, update) {
129
+ const current = readAgentSurfaceState(storageKey, defaults);
130
+ const state = update(current);
131
+ writeAgentSurfaceState(storageKey, state);
132
+ window.dispatchEvent(new CustomEvent(AGENT_SURFACE_STATE_EVENT, {
133
+ detail: { storageKey, state }
134
+ }));
365
135
  }
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
- }
136
+ function isRecord(value) {
137
+ return typeof value === "object" && value !== null && !Array.isArray(value);
428
138
  }
429
- async function fileExists(path) {
139
+ function readAgentSurfaceState(storageKey, defaults, minimumWidth = MIN_AGENT_SURFACE_WIDTH, maximumWidth = MAX_AGENT_SURFACE_WIDTH) {
140
+ if (!storageKey || typeof window === "undefined")
141
+ return defaults;
430
142
  try {
431
- return (await stat(path)).isFile();
143
+ return parseAgentSurfaceSessionState(window.sessionStorage.getItem(storageKey), defaults, minimumWidth, maximumWidth);
432
144
  } catch {
433
- return false;
145
+ return defaults;
434
146
  }
435
147
  }
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)
148
+ function writeAgentSurfaceState(storageKey, state) {
149
+ if (!storageKey || typeof window === "undefined")
469
150
  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
151
  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/.`);
152
+ window.sessionStorage.setItem(storageKey, JSON.stringify(state));
153
+ } catch {}
590
154
  }
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
155
 
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}'.`);
156
+ // src/agent/agent-surface.tsx
157
+ import { jsx as jsx2, jsxs, Fragment } from "react/jsx-runtime";
158
+ function AgentSurface({
159
+ mode,
160
+ defaultMode = "dock",
161
+ onModeChange,
162
+ fullPage = false,
163
+ onRequestFullPage,
164
+ onRequestDock,
165
+ title,
166
+ launcherLabel,
167
+ composerPlaceholder,
168
+ context,
169
+ threadId,
170
+ defaultThreadId = null,
171
+ onThreadChange,
172
+ onExpandThread,
173
+ dockWidth,
174
+ defaultDockWidth = DEFAULT_AGENT_SURFACE_WIDTH,
175
+ onDockWidthChange,
176
+ minDockWidth = MIN_AGENT_SURFACE_WIDTH,
177
+ maxDockWidth = MAX_AGENT_SURFACE_WIDTH,
178
+ resizable = true,
179
+ persistenceKey,
180
+ className,
181
+ panelClassName,
182
+ welcomeContent
183
+ }) {
184
+ const messages = useAgentMessages().surface;
185
+ const surfaceTitle = title ?? messages.title;
186
+ const launcher = launcherLabel ?? messages.open;
187
+ const minimumWidth = Math.min(minDockWidth, maxDockWidth);
188
+ const maximumWidth = Math.max(minDockWidth, maxDockWidth);
189
+ const storageKey = agentSurfaceSessionStorageKey(persistenceKey);
190
+ const defaults = {
191
+ mode: defaultMode,
192
+ dockWidth: clampAgentSurfaceWidth(defaultDockWidth, minimumWidth, maximumWidth),
193
+ threadId: defaultThreadId
194
+ };
195
+ const [sessionState, setSessionState] = useState2(() => readAgentSurfaceState(storageKey, defaults, minimumWidth, maximumWidth));
196
+ const [documentHost, setDocumentHost] = useState2(null);
197
+ const [resizing, setResizing] = useState2(false);
198
+ const resizeStart = useRef(null);
199
+ useEffect(() => {
200
+ writeAgentSurfaceState(storageKey, sessionState);
201
+ }, [storageKey, sessionState]);
202
+ useEffect(() => {
203
+ if (!storageKey || typeof window === "undefined")
204
+ return;
205
+ const receiveState = (event) => {
206
+ const detail = event.detail;
207
+ if (detail?.storageKey !== storageKey)
208
+ return;
209
+ setSessionState(detail.state);
210
+ };
211
+ window.addEventListener(AGENT_SURFACE_STATE_EVENT, receiveState);
212
+ return () => window.removeEventListener(AGENT_SURFACE_STATE_EVENT, receiveState);
213
+ }, [storageKey]);
214
+ const currentMode = mode ?? sessionState.mode;
215
+ const currentThreadId = threadId === undefined ? sessionState.threadId : threadId;
216
+ const currentDockWidth = dockWidth ?? sessionState.dockWidth;
217
+ const numericDockWidth = typeof currentDockWidth === "number" ? currentDockWidth : sessionState.dockWidth;
218
+ const visible = fullPage || currentMode !== "collapsed";
219
+ const presentation = fullPage ? "full" : currentMode;
220
+ const dockWidthValue = typeof currentDockWidth === "number" ? `${currentDockWidth}px` : currentDockWidth;
221
+ const surfaceStyle = { "--agent-surface-width": dockWidthValue };
222
+ const changeMode = useCallback2((nextMode) => {
223
+ if (mode === undefined) {
224
+ setSessionState((current) => ({ ...current, mode: nextMode }));
225
+ }
226
+ onModeChange?.(nextMode);
227
+ }, [mode, onModeChange]);
228
+ const changeThread = useCallback2((nextThreadId) => {
229
+ setSessionState((current) => current.threadId === nextThreadId ? current : { ...current, threadId: nextThreadId });
230
+ onThreadChange?.(nextThreadId);
231
+ }, [onThreadChange]);
232
+ useEffect(() => {
233
+ if (threadId === undefined)
234
+ return;
235
+ setSessionState((current) => current.threadId === threadId ? current : { ...current, threadId });
236
+ }, [threadId]);
237
+ useEffect(() => {
238
+ if (!fullPage || sessionState.mode === "dock")
239
+ return;
240
+ setSessionState((current) => ({ ...current, mode: "dock" }));
241
+ }, [fullPage, sessionState.mode]);
242
+ const changeDockWidth = useCallback2((nextWidth) => {
243
+ const viewportMaximum = typeof window === "undefined" ? maximumWidth : Math.max(minimumWidth, Math.min(maximumWidth, window.innerWidth - minimumWidth));
244
+ const clamped = clampAgentSurfaceWidth(nextWidth, minimumWidth, viewportMaximum);
245
+ if (dockWidth === undefined) {
246
+ setSessionState((current) => ({ ...current, dockWidth: clamped }));
247
+ }
248
+ onDockWidthChange?.(clamped);
249
+ }, [dockWidth, maximumWidth, minimumWidth, onDockWidthChange]);
250
+ function startResize(event) {
251
+ if (event.button !== 0)
252
+ return;
253
+ event.preventDefault();
254
+ event.currentTarget.setPointerCapture(event.pointerId);
255
+ resizeStart.current = {
256
+ pointerId: event.pointerId,
257
+ clientX: event.clientX,
258
+ width: numericDockWidth
259
+ };
260
+ setResizing(true);
663
261
  }
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}'.`);
262
+ function continueResize(event) {
263
+ const start = resizeStart.current;
264
+ if (!start || start.pointerId !== event.pointerId)
265
+ return;
266
+ changeDockWidth(start.width + start.clientX - event.clientX);
670
267
  }
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;
268
+ function finishResize(event) {
269
+ if (resizeStart.current?.pointerId !== event.pointerId)
270
+ return;
271
+ resizeStart.current = null;
272
+ setResizing(false);
273
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
274
+ event.currentTarget.releasePointerCapture(event.pointerId);
684
275
  }
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
276
  }
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);
277
+ function resizeWithKeyboard(event) {
278
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
279
+ return;
280
+ event.preventDefault();
281
+ const step = event.shiftKey ? 32 : 16;
282
+ changeDockWidth(numericDockWidth + (event.key === "ArrowLeft" ? step : -step));
283
+ }
284
+ return /* @__PURE__ */ jsxs(Fragment, {
285
+ children: [
286
+ !visible ? /* @__PURE__ */ jsx2(Button, {
287
+ type: "button",
288
+ size: "icon",
289
+ className: "fixed right-5 bottom-5 z-40 size-11 rounded-full shadow-lg max-sm:right-3 max-sm:bottom-3",
290
+ "aria-label": launcher,
291
+ title: launcher,
292
+ onClick: () => changeMode("dock"),
293
+ children: /* @__PURE__ */ jsx2(MessageSquareText, {
294
+ className: "size-4"
295
+ })
296
+ }) : null,
297
+ /* @__PURE__ */ jsx2("div", {
298
+ ref: setDocumentHost,
299
+ "data-agent-document-host": "",
300
+ "aria-hidden": !visible,
301
+ inert: !visible,
302
+ className: cn2("pointer-events-none fixed inset-y-3 left-3 z-40 max-sm:hidden", (!visible || fullPage) && "hidden"),
303
+ style: { right: `calc(${dockWidthValue} + 0.75rem)` }
304
+ }),
305
+ /* @__PURE__ */ jsxs("aside", {
306
+ "data-agent-surface": presentation,
307
+ "data-agent-surface-resizing": resizing ? "" : undefined,
308
+ "aria-label": surfaceTitle,
309
+ "aria-hidden": !visible,
310
+ inert: !visible,
311
+ style: surfaceStyle,
312
+ 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),
313
+ children: [
314
+ visible && !fullPage && resizable ? /* @__PURE__ */ jsx2("div", {
315
+ role: "separator",
316
+ "aria-label": messages.resize,
317
+ "aria-orientation": "vertical",
318
+ "aria-valuemin": minimumWidth,
319
+ "aria-valuemax": maximumWidth,
320
+ "aria-valuenow": Math.round(numericDockWidth),
321
+ tabIndex: 0,
322
+ onPointerDown: startResize,
323
+ onPointerMove: continueResize,
324
+ onPointerUp: finishResize,
325
+ onPointerCancel: finishResize,
326
+ onKeyDown: resizeWithKeyboard,
327
+ 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"
328
+ }) : null,
329
+ /* @__PURE__ */ jsxs("div", {
330
+ className: cn2("relative flex h-full min-w-0 flex-col", fullPage ? "w-full" : "w-[var(--agent-surface-width)] max-sm:w-screen"),
331
+ children: [
332
+ !fullPage ? /* @__PURE__ */ jsx2(Button, {
333
+ type: "button",
334
+ variant: "ghost",
335
+ size: "icon-lg",
336
+ "aria-label": messages.collapse,
337
+ onClick: () => changeMode("collapsed"),
338
+ className: "absolute top-0.5 left-1.5 z-20 bg-background/90 backdrop-blur-sm [&_svg]:size-5",
339
+ children: /* @__PURE__ */ jsx2(ChevronRight, {})
340
+ }) : null,
341
+ /* @__PURE__ */ jsx2(AgentPanel, {
342
+ compact: !fullPage,
343
+ context,
344
+ composerPlaceholder,
345
+ threadId: currentThreadId,
346
+ onThreadChange: changeThread,
347
+ welcomeContent,
348
+ conversationHeaderActions: fullPage && onRequestDock ? /* @__PURE__ */ jsx2(Button, {
349
+ type: "button",
350
+ variant: "ghost",
351
+ size: "icon-lg",
352
+ "aria-label": messages.dock,
353
+ onClick: () => {
354
+ changeMode("dock");
355
+ onRequestDock?.();
356
+ },
357
+ className: "[&_svg]:size-5",
358
+ children: /* @__PURE__ */ jsx2(Minimize2, {})
359
+ }) : !fullPage && (onRequestFullPage || onExpandThread && currentThreadId) ? /* @__PURE__ */ jsx2(Button, {
360
+ type: "button",
361
+ variant: "ghost",
362
+ size: "icon-lg",
363
+ "aria-label": messages.expand,
364
+ onClick: () => {
365
+ if (onExpandThread && currentThreadId)
366
+ onExpandThread(currentThreadId);
367
+ else
368
+ onRequestFullPage?.();
369
+ },
370
+ className: "[&_svg]:size-5",
371
+ children: /* @__PURE__ */ jsx2(Maximize2, {})
372
+ }) : null,
373
+ documentPreviewHost: fullPage ? null : documentHost,
374
+ className: cn2("min-h-0 flex-1", !fullPage && "[&_[data-agent-conversation-header]]:pl-12", panelClassName)
375
+ })
376
+ ]
377
+ })
378
+ ]
379
+ })
380
+ ]
731
381
  });
732
382
  }
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)) {
383
+ // src/public-env.ts
384
+ var runtime = typeof window === "undefined" ? undefined : window.__SIXB_RUNTIME__;
385
+ var publicEnv = Object.freeze(Object.assign(Object.create(null), runtime?.publicEnv));
386
+ // src/shell/agent-dock.tsx
387
+ import { getAgentOptions } from "@sixb/client/hooks";
388
+ import { useQuery } from "@tanstack/react-query";
389
+ import { useLocation, useNavigate } from "react-router-dom";
390
+ import { jsx as jsx3 } from "react/jsx-runtime";
391
+ function AgentDock() {
392
+ const messages = useAppMessages2().agent;
393
+ const navigate = useNavigate();
394
+ const { pathname } = useLocation();
395
+ const enabled = useSectionsEnabled();
396
+ const agent = useQuery({ ...getAgentOptions(), enabled, retry: false, staleTime: 5 * 60000 });
397
+ const conversationPage = pathname === "/" || pathname === "/agents" || pathname.startsWith("/agents/");
398
+ if (!enabled || !agent.data || conversationPage)
765
399
  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 };
400
+ return /* @__PURE__ */ jsx3(AgentSurface, {
401
+ title: messages.title,
402
+ launcherLabel: messages.open,
403
+ defaultMode: "collapsed",
404
+ onExpandThread: (threadId) => navigate(`/agents/${encodeURIComponent(threadId)}`),
405
+ persistenceKey: "sixb.app.agent-dock.v1"
406
+ });
872
407
  }
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"
408
+ // src/shell/app-shell.tsx
902
409
  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
- })
410
+ Sidebar,
411
+ SidebarCollapseToggle,
412
+ SidebarContent,
413
+ SidebarFooter,
414
+ SidebarGroup as SidebarGroup2,
415
+ SidebarGroupContent as SidebarGroupContent2,
416
+ SidebarHeader,
417
+ SidebarInset,
418
+ SidebarMenu as SidebarMenu4,
419
+ SidebarMenuItem as SidebarMenuItem4,
420
+ SidebarProvider,
421
+ SidebarRail,
422
+ SidebarTrigger,
423
+ useSidebar as useSidebar2
424
+ } from "@sixb/ui/components";
425
+ import { ThemeProvider } from "@sixb/ui/hooks";
426
+ import { cn as cn4 } from "@sixb/ui/lib/utils";
427
+
428
+ // src/shell/search-command.tsx
429
+ import { searchObjectsOptions } from "@sixb/client/hooks";
430
+ import {
431
+ CommandDialog,
432
+ CommandEmpty,
433
+ CommandGroup,
434
+ CommandInput,
435
+ CommandItem,
436
+ CommandList,
437
+ Kbd,
438
+ SidebarMenu,
439
+ SidebarMenuButton,
440
+ SidebarMenuItem
441
+ } from "@sixb/ui/components";
442
+ import { keepPreviousData, useQuery as useQuery2 } from "@tanstack/react-query";
443
+ import { Box, Search } from "lucide-react";
444
+ import { useDeferredValue, useEffect as useEffect2, useState as useState3 } from "react";
445
+ import { useNavigate as useNavigate2 } from "react-router-dom";
446
+ import { jsx as jsx4, jsxs as jsxs2, Fragment as Fragment2 } from "react/jsx-runtime";
447
+ function SearchCommand({ pages = [] }) {
448
+ const messages = useAppMessages2().search;
449
+ const navigate = useNavigate2();
450
+ const sections = useSections2();
451
+ const enabled = useSectionsEnabled();
452
+ const [open, setOpen] = useState3(false);
453
+ const [query, setQuery] = useState3("");
454
+ const term = useDeferredValue(query.trim());
455
+ const searching = term.length > 1;
456
+ const objects = useQuery2({
457
+ ...searchObjectsOptions({ query: { q: term, limit: "8" } }),
458
+ enabled: enabled && open && searching,
459
+ placeholderData: keepPreviousData,
460
+ retry: false
461
+ });
462
+ useEffect2(() => {
463
+ if (!enabled)
464
+ return;
465
+ const toggle = (event) => {
466
+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {
467
+ event.preventDefault();
468
+ setOpen((current) => !current);
469
+ }
470
+ };
471
+ window.addEventListener("keydown", toggle);
472
+ return () => window.removeEventListener("keydown", toggle);
473
+ }, [enabled]);
474
+ const go = (href) => {
475
+ setOpen(false);
476
+ setQuery("");
477
+ if (isExternal(href))
478
+ window.location.assign(href);
479
+ else
480
+ navigate(href);
481
+ };
482
+ if (!enabled)
483
+ return null;
484
+ const appPages = pages.flatMap((entry) => ("group" in entry) ? entry.items : [entry]);
485
+ return /* @__PURE__ */ jsxs2(Fragment2, {
486
+ children: [
487
+ /* @__PURE__ */ jsx4(SidebarMenu, {
488
+ children: /* @__PURE__ */ jsx4(SidebarMenuItem, {
489
+ children: /* @__PURE__ */ jsxs2(SidebarMenuButton, {
490
+ tooltip: messages.label,
491
+ onClick: () => setOpen(true),
492
+ className: "border border-sidebar-border text-sidebar-foreground/80 hover:border-foreground/15",
493
+ children: [
494
+ /* @__PURE__ */ jsx4(Search, {}),
495
+ /* @__PURE__ */ jsx4("span", {
496
+ children: messages.label
497
+ }),
498
+ /* @__PURE__ */ jsx4(Kbd, {
499
+ className: "ml-auto group-data-[collapsible=icon]:hidden",
500
+ children: "\u2318K"
501
+ })
502
+ ]
503
+ })
504
+ })
505
+ }),
506
+ /* @__PURE__ */ jsxs2(CommandDialog, {
507
+ open,
508
+ onOpenChange: (next) => {
509
+ setOpen(next);
510
+ if (!next)
511
+ setQuery("");
512
+ },
513
+ title: messages.label,
514
+ className: "max-w-xl rounded-xl",
515
+ children: [
516
+ /* @__PURE__ */ jsx4(CommandInput, {
517
+ value: query,
518
+ onValueChange: setQuery,
519
+ placeholder: messages.placeholder
520
+ }),
521
+ /* @__PURE__ */ jsxs2(CommandList, {
522
+ className: "max-h-[min(28rem,70vh)]",
523
+ children: [
524
+ /* @__PURE__ */ jsx4(CommandEmpty, {
525
+ children: objects.isFetching ? messages.searching : messages.empty
526
+ }),
527
+ searching && objects.data && objects.data.items.length > 0 ? /* @__PURE__ */ jsx4(CommandGroup, {
528
+ heading: messages.objects,
529
+ children: objects.data.items.map((item) => /* @__PURE__ */ jsxs2(CommandItem, {
530
+ value: `object:${item.ref.objectTypeId}:${item.ref.primaryId}`,
531
+ keywords: [item.label, query],
532
+ onSelect: () => go(objectHref(item.ref.objectTypeId, item.ref.primaryId)),
533
+ children: [
534
+ /* @__PURE__ */ jsx4(Box, {}),
535
+ /* @__PURE__ */ jsx4("span", {
536
+ className: "min-w-0 flex-1 truncate",
537
+ children: item.label
538
+ }),
539
+ /* @__PURE__ */ jsx4("span", {
540
+ className: "text-xs text-muted-foreground",
541
+ children: item.ref.objectTypeId
542
+ })
543
+ ]
544
+ }, `${item.ref.objectTypeId}:${item.ref.primaryId}`))
545
+ }) : null,
546
+ appPages.length > 0 ? /* @__PURE__ */ jsx4(CommandGroup, {
547
+ heading: messages.pages,
548
+ children: appPages.map((page) => /* @__PURE__ */ jsx4(PageItem, {
549
+ page,
550
+ onSelect: go
551
+ }, page.href))
552
+ }) : null,
553
+ sections.map((section) => /* @__PURE__ */ jsx4(CommandGroup, {
554
+ heading: section.label,
555
+ children: section.pages.flatMap((entry) => ("group" in entry) ? entry.items : [entry]).map((page) => /* @__PURE__ */ jsx4(PageItem, {
556
+ page,
557
+ keywords: [section.label],
558
+ onSelect: go
559
+ }, page.href))
560
+ }, section.id))
561
+ ]
562
+ })
563
+ ]
564
+ })
565
+ ]
566
+ });
964
567
  }
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
- )
568
+ function PageItem({
569
+ page,
570
+ keywords,
571
+ onSelect
572
+ }) {
573
+ return /* @__PURE__ */ jsxs2(CommandItem, {
574
+ value: `page:${page.href}`,
575
+ keywords: [page.label, ...keywords ?? []],
576
+ onSelect: () => onSelect(page.href),
577
+ children: [
578
+ page.icon ? /* @__PURE__ */ jsx4(page.icon, {}) : null,
579
+ /* @__PURE__ */ jsx4("span", {
580
+ children: page.label
581
+ })
582
+ ]
583
+ });
972
584
  }
973
585
 
974
- function isSharedTransportPath(pathname: string): boolean {
975
- return pathname === "/shared" || pathname.startsWith("/shared/")
586
+ // src/shell/section-nav.tsx
587
+ import {
588
+ SidebarGroup,
589
+ SidebarGroupContent,
590
+ SidebarMenu as SidebarMenu2,
591
+ SidebarMenuButton as SidebarMenuButton2,
592
+ SidebarMenuItem as SidebarMenuItem2
593
+ } from "@sixb/ui/components";
594
+ import { ChevronLeft } from "lucide-react";
595
+ import { Link } from "react-router-dom";
596
+
597
+ // src/sections/counts.ts
598
+ import {
599
+ listActionsOptions,
600
+ listObjectTypesOptions,
601
+ listRulesOptions,
602
+ listWorkflowsOptions,
603
+ objectCountOptions
604
+ } from "@sixb/client/hooks";
605
+ import { useQuery as useQuery3 } from "@tanstack/react-query";
606
+ function usePageCounts(section) {
607
+ const ontology = { enabled: section === "ontology", retry: false, staleTime: 30000 };
608
+ const types = useQuery3({ ...listObjectTypesOptions(), ...ontology }).data;
609
+ const objects = useQuery3({ ...objectCountOptions(), ...ontology }).data;
610
+ const actions = useQuery3({ ...listActionsOptions(), ...ontology }).data;
611
+ const workflows = useQuery3({ ...listWorkflowsOptions(), ...ontology }).data;
612
+ const rules = useQuery3({ ...listRulesOptions(), ...ontology }).data;
613
+ if (section !== "ontology")
614
+ return {};
615
+ const counts = {
616
+ "/ontology/object-types": types?.length,
617
+ "/ontology/objects": objects,
618
+ "/ontology/actions": actions?.length,
619
+ "/ontology/workflows": workflows?.length,
620
+ "/ontology/rules": rules?.length
621
+ };
622
+ return Object.fromEntries(Object.entries(counts).filter((entry) => entry[1] !== undefined));
623
+ }
624
+
625
+ // src/shell/section-nav.tsx
626
+ import { jsx as jsx5, jsxs as jsxs3, Fragment as Fragment3 } from "react/jsx-runtime";
627
+ function SectionNav({ fallback = null, backHref = "/" }) {
628
+ useRegisterSectionNav();
629
+ const messages = useAppMessages2().sections;
630
+ const section = useCurrentSection2();
631
+ const counts = usePageCounts(section?.id);
632
+ if (!section)
633
+ return fallback;
634
+ const counted = (item) => counts[item.href] === undefined ? item : { ...item, badge: counts[item.href] };
635
+ const pages = section.pages.map((entry) => ("group" in entry) ? { ...entry, items: entry.items.map(counted) } : counted(entry));
636
+ return /* @__PURE__ */ jsxs3(Fragment3, {
637
+ children: [
638
+ /* @__PURE__ */ jsx5(SidebarGroup, {
639
+ children: /* @__PURE__ */ jsx5(SidebarGroupContent, {
640
+ children: /* @__PURE__ */ jsx5(SidebarMenu2, {
641
+ children: /* @__PURE__ */ jsx5(SidebarMenuItem2, {
642
+ children: /* @__PURE__ */ jsx5(SidebarMenuButton2, {
643
+ asChild: true,
644
+ tooltip: messages.back,
645
+ children: /* @__PURE__ */ jsxs3(Link, {
646
+ to: backHref,
647
+ children: [
648
+ /* @__PURE__ */ jsx5(ChevronLeft, {}),
649
+ /* @__PURE__ */ jsx5("span", {
650
+ className: "font-medium",
651
+ children: section.label
652
+ })
653
+ ]
654
+ })
655
+ })
656
+ })
657
+ })
658
+ })
659
+ }),
660
+ /* @__PURE__ */ jsx5(NavItems2, {
661
+ items: pages
662
+ })
663
+ ]
664
+ });
976
665
  }
977
666
 
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
667
+ // src/shell/user-menu.tsx
668
+ import {
669
+ Avatar,
670
+ AvatarFallback,
671
+ AvatarImage,
672
+ DropdownMenu,
673
+ DropdownMenuContent,
674
+ DropdownMenuItem,
675
+ DropdownMenuLabel,
676
+ DropdownMenuSeparator,
677
+ DropdownMenuTrigger,
678
+ nextTheme,
679
+ SidebarMenu as SidebarMenu3,
680
+ SidebarMenuButton as SidebarMenuButton3,
681
+ SidebarMenuItem as SidebarMenuItem3,
682
+ ThemePicker,
683
+ useSidebar
684
+ } from "@sixb/ui/components";
685
+ import { useOptionalTheme } from "@sixb/ui/hooks";
686
+ import { cn as cn3 } from "@sixb/ui/lib/utils";
687
+ import { ChevronsUpDown, CircleUserRound, LogOut, SunMoon } from "lucide-react";
688
+ import { jsx as jsx6, jsxs as jsxs4, Fragment as Fragment4 } from "react/jsx-runtime";
689
+ function UserMenuRoot({ children }) {
690
+ const user = useCurrentUser2();
691
+ const signOut = useSignOut2();
692
+ const sections = useSections2();
693
+ const messages = useAppMessages2().userMenu;
694
+ const themeControls = useOptionalTheme();
695
+ const { isMobile } = useSidebar();
696
+ const items = sections.length > 0 || children ? /* @__PURE__ */ jsxs4(Fragment4, {
697
+ children: [
698
+ sections.map((section) => /* @__PURE__ */ jsx6(UserMenuItem, {
699
+ href: section.href,
700
+ icon: section.icon,
701
+ children: section.label
702
+ }, section.id)),
703
+ children
704
+ ]
705
+ }) : null;
706
+ return /* @__PURE__ */ jsx6(SidebarMenu3, {
707
+ children: /* @__PURE__ */ jsx6(SidebarMenuItem3, {
708
+ children: /* @__PURE__ */ jsxs4(DropdownMenu, {
709
+ children: [
710
+ /* @__PURE__ */ jsx6(DropdownMenuTrigger, {
711
+ asChild: true,
712
+ children: user ? /* @__PURE__ */ jsxs4(SidebarMenuButton3, {
713
+ size: "lg",
714
+ tooltip: displayName(user),
715
+ className: "data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",
716
+ children: [
717
+ /* @__PURE__ */ jsx6(Identity, {
718
+ user,
719
+ emailClassName: "text-sidebar-foreground/70"
720
+ }),
721
+ /* @__PURE__ */ jsx6(ChevronsUpDown, {
722
+ className: "ml-auto size-4"
723
+ })
724
+ ]
725
+ }) : /* @__PURE__ */ jsxs4(SidebarMenuButton3, {
726
+ tooltip: messages.signInOff,
727
+ className: "text-sidebar-foreground data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",
728
+ children: [
729
+ /* @__PURE__ */ jsx6(CircleUserRound, {}),
730
+ /* @__PURE__ */ jsx6("span", {
731
+ children: messages.signInOff
732
+ })
733
+ ]
734
+ })
735
+ }),
736
+ /* @__PURE__ */ jsxs4(DropdownMenuContent, {
737
+ side: isMobile ? "bottom" : "top",
738
+ align: "end",
739
+ sideOffset: 4,
740
+ className: "min-w-56 rounded-lg",
741
+ onCloseAutoFocus: (event) => event.preventDefault(),
742
+ children: [
743
+ user ? /* @__PURE__ */ jsxs4(Fragment4, {
744
+ children: [
745
+ /* @__PURE__ */ jsx6(DropdownMenuLabel, {
746
+ className: "p-0 font-normal",
747
+ children: /* @__PURE__ */ jsx6("div", {
748
+ className: "flex items-center gap-2 px-1 py-1.5 text-left text-sm",
749
+ children: /* @__PURE__ */ jsx6(Identity, {
750
+ user,
751
+ emailClassName: "text-muted-foreground"
752
+ })
753
+ })
754
+ }),
755
+ /* @__PURE__ */ jsx6(DropdownMenuSeparator, {})
756
+ ]
757
+ }) : null,
758
+ items ? /* @__PURE__ */ jsxs4(Fragment4, {
759
+ children: [
760
+ items,
761
+ themeControls ? /* @__PURE__ */ jsx6(DropdownMenuSeparator, {}) : null
762
+ ]
763
+ }) : null,
764
+ themeControls ? /* @__PURE__ */ jsxs4(DropdownMenuItem, {
765
+ "aria-keyshortcuts": "ArrowLeft ArrowRight",
766
+ onSelect: (event) => event.preventDefault(),
767
+ onKeyDown: (event) => {
768
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight")
769
+ return;
770
+ event.preventDefault();
771
+ themeControls.setTheme(nextTheme(themeControls.theme, event.key === "ArrowRight" ? 1 : -1));
772
+ },
773
+ children: [
774
+ /* @__PURE__ */ jsx6(SunMoon, {}),
775
+ /* @__PURE__ */ jsx6("span", {
776
+ className: "flex-1",
777
+ children: messages.theme
778
+ }),
779
+ /* @__PURE__ */ jsx6(ThemePicker, {
780
+ focusable: false
781
+ })
782
+ ]
783
+ }) : null,
784
+ user ? /* @__PURE__ */ jsxs4(Fragment4, {
785
+ children: [
786
+ /* @__PURE__ */ jsx6(DropdownMenuSeparator, {}),
787
+ /* @__PURE__ */ jsxs4(DropdownMenuItem, {
788
+ onClick: () => {
789
+ signOut().catch((error) => {
790
+ console.error("[SixbApp] Could not sign out:", error);
791
+ });
792
+ },
793
+ children: [
794
+ /* @__PURE__ */ jsx6(LogOut, {}),
795
+ /* @__PURE__ */ jsx6("span", {
796
+ children: messages.signOut
797
+ })
798
+ ]
799
+ })
800
+ ]
801
+ }) : null
802
+ ]
803
+ })
804
+ ]
805
+ })
806
+ })
807
+ });
992
808
  }
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
809
+ function displayName(user) {
810
+ return user.displayName ?? user.email;
1022
811
  }
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
812
+ function Identity({
813
+ user,
814
+ emailClassName
815
+ }) {
816
+ const name = displayName(user);
817
+ return /* @__PURE__ */ jsxs4(Fragment4, {
818
+ children: [
819
+ /* @__PURE__ */ jsxs4(Avatar, {
820
+ className: "h-8 w-8 rounded-md",
821
+ children: [
822
+ user.avatarUrl ? /* @__PURE__ */ jsx6(AvatarImage, {
823
+ src: user.avatarUrl,
824
+ alt: name
825
+ }) : null,
826
+ /* @__PURE__ */ jsx6(AvatarFallback, {
827
+ className: "rounded-md text-xs",
828
+ children: initials(name)
829
+ })
830
+ ]
831
+ }),
832
+ /* @__PURE__ */ jsxs4("div", {
833
+ className: "grid flex-1 text-left text-sm leading-tight",
834
+ children: [
835
+ /* @__PURE__ */ jsx6("span", {
836
+ className: "truncate font-semibold",
837
+ children: name
838
+ }),
839
+ user.displayName ? /* @__PURE__ */ jsx6("span", {
840
+ className: cn3("truncate text-xs", emailClassName),
841
+ children: user.email
842
+ }) : null
843
+ ]
844
+ })
845
+ ]
846
+ });
1060
847
  }
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
848
+ function initials(name) {
849
+ const parts = name.trim().split(/\s+/).filter(Boolean);
850
+ if (parts.length === 0)
851
+ return "?";
852
+ if (parts.length === 1)
853
+ return parts[0].slice(0, 2).toUpperCase();
854
+ return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase();
855
+ }
856
+ function UserMenuItem({ href, icon: Icon, onSelect, children }) {
857
+ const content = /* @__PURE__ */ jsxs4(Fragment4, {
858
+ children: [
859
+ Icon ? /* @__PURE__ */ jsx6(Icon, {}) : null,
860
+ /* @__PURE__ */ jsx6("span", {
861
+ children
862
+ })
863
+ ]
864
+ });
865
+ return href ? /* @__PURE__ */ jsx6(DropdownMenuItem, {
866
+ asChild: true,
867
+ onSelect,
868
+ children: /* @__PURE__ */ jsx6("a", {
869
+ href,
870
+ children: content
871
+ })
872
+ }) : /* @__PURE__ */ jsx6(DropdownMenuItem, {
873
+ onSelect,
874
+ children: content
875
+ });
1070
876
  }
877
+ var UserMenu = Object.assign(UserMenuRoot, { Item: UserMenuItem });
1071
878
 
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
879
+ // src/shell/app-shell.tsx
880
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
881
+ function AppShellProvider({ className, children, ...sidebarState }) {
882
+ return /* @__PURE__ */ jsx7(ThemeProvider, {
883
+ children: /* @__PURE__ */ jsx7(SidebarProvider, {
884
+ className: cn4("h-dvh overflow-hidden", className),
885
+ ...sidebarState,
886
+ children
887
+ })
888
+ });
1083
889
  }
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
890
+ function AppShell({
891
+ nav,
892
+ brand,
893
+ header,
894
+ footer,
895
+ userMenu,
896
+ agent,
897
+ variant = "inset",
898
+ collapsible = "icon",
899
+ side = "left",
900
+ defaultOpen,
901
+ children
1101
902
  }) {
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
- )
903
+ return /* @__PURE__ */ jsxs5(AppShellProvider, {
904
+ defaultOpen,
905
+ children: [
906
+ /* @__PURE__ */ jsxs5(Sidebar, {
907
+ variant,
908
+ collapsible,
909
+ side,
910
+ children: [
911
+ /* @__PURE__ */ jsxs5(SidebarHeader, {
912
+ children: [
913
+ brand === undefined ? /* @__PURE__ */ jsx7(Brand2, {}) : brand,
914
+ header === undefined ? /* @__PURE__ */ jsx7(SearchCommand, {
915
+ pages: isNavData(nav) ? nav : []
916
+ }) : header
917
+ ]
918
+ }),
919
+ /* @__PURE__ */ jsxs5(SidebarContent, {
920
+ children: [
921
+ /* @__PURE__ */ jsx7(SectionNav, {
922
+ fallback: isNavData(nav) ? /* @__PURE__ */ jsx7(NavItems2, {
923
+ items: nav
924
+ }) : nav
925
+ }),
926
+ collapsible === "none" ? null : /* @__PURE__ */ jsx7(CollapseToggle, {})
927
+ ]
928
+ }),
929
+ /* @__PURE__ */ jsxs5(SidebarFooter, {
930
+ children: [
931
+ footer,
932
+ userMenu === undefined ? /* @__PURE__ */ jsx7(UserMenu, {}) : userMenu
933
+ ]
934
+ }),
935
+ collapsible === "none" ? null : /* @__PURE__ */ jsx7(SidebarRail, {
936
+ className: variant === "inset" ? "after:hidden" : undefined
937
+ })
938
+ ]
939
+ }),
940
+ /* @__PURE__ */ jsxs5(SidebarInset, {
941
+ className: "min-h-0 overflow-hidden",
942
+ children: [
943
+ /* @__PURE__ */ jsx7("div", {
944
+ className: "flex h-12 shrink-0 items-center border-b border-border px-3 md:hidden",
945
+ children: /* @__PURE__ */ jsx7(SidebarTrigger, {
946
+ className: "-ml-1"
947
+ })
948
+ }),
949
+ /* @__PURE__ */ jsxs5("div", {
950
+ className: "relative flex min-h-0 flex-1",
951
+ children: [
952
+ /* @__PURE__ */ jsx7("div", {
953
+ className: "min-h-0 min-w-0 flex-1 overflow-y-auto",
954
+ children
955
+ }),
956
+ agent === undefined ? /* @__PURE__ */ jsx7(AgentDock, {}) : agent
957
+ ]
958
+ })
959
+ ]
960
+ })
961
+ ]
962
+ });
1201
963
  }
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
- )
964
+ function CollapseToggle() {
965
+ const { isMobile } = useSidebar2();
966
+ if (isMobile)
967
+ return null;
968
+ return /* @__PURE__ */ jsx7(SidebarGroup2, {
969
+ className: "mt-auto",
970
+ children: /* @__PURE__ */ jsx7(SidebarGroupContent2, {
971
+ children: /* @__PURE__ */ jsx7(SidebarMenu4, {
972
+ children: /* @__PURE__ */ jsx7(SidebarMenuItem4, {
973
+ children: /* @__PURE__ */ jsx7(SidebarCollapseToggle, {})
974
+ })
975
+ })
976
+ })
977
+ });
1215
978
  }
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()
1571
- }
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
- )
1580
- }
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
- }
1597
- }
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
- }
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)
1654
- }
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
1805
- };
1806
- }
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;
1863
- }
1864
- async function fileExists2(path) {
1865
- try {
1866
- await access(path);
1867
- return true;
1868
- } 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);
1882
- }
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
- }
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) {
1935
- 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
- };
2026
- }
2027
-
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")
2047
- };
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
2143
- };
2144
- }
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;
2515
- }
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) {
2527
- return;
2528
- }
2529
- } catch (error) {
2530
- if (!isFileNotFoundError2(error)) {
2531
- throw error;
2532
- }
2533
- }
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
2545
- });
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
- }
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))
2694
- 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
2708
- });
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
- }
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
- }
2725
- });
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
- }
2734
- });
2735
- }
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
- };
2773
- }
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)) {
2784
- 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
2808
- });
2809
- }
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
- }
2848
- });
2849
- }
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
- };
2866
- }
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;
2873
- }
2874
- function htmlBundleRoute(bundle) {
2875
- return {
2876
- GET: bundle,
2877
- HEAD: bundle
2878
- };
2879
- }
2880
- function manifestRoute(manifestPath) {
2881
- return getHeadRoute((request) => fileResponse(request, Bun.file(manifestPath), staticAssetHeaders(customAppManifestRoute)));
2882
- }
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}`;
2892
- }
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
- });
2931
- });
979
+ function isNavData(nav) {
980
+ return Array.isArray(nav);
2932
981
  }
2933
982
  export {
2934
- createCustomApp,
2935
- createTailwindCssCompiler,
2936
- devReloadResponse,
2937
- publicEnv2 as publicEnv
983
+ AgentChatPage2 as AgentChatPage,
984
+ AgentContextProvider2 as AgentContextProvider,
985
+ AgentDock,
986
+ AgentPanel,
987
+ AgentSurface,
988
+ AgentWorkspaceProvider2 as AgentWorkspaceProvider,
989
+ AppShell,
990
+ AppShellProvider,
991
+ Brand2 as Brand,
992
+ Composer2 as Composer,
993
+ NavItems2 as NavItems,
994
+ SearchCommand,
995
+ SectionNav,
996
+ SyncButton2 as SyncButton,
997
+ UserMenu,
998
+ agentContext,
999
+ publicEnv,
1000
+ setAgentSurfaceMode,
1001
+ useAgentContext2 as useAgentContext,
1002
+ useCurrentSection2 as useCurrentSection,
1003
+ useCurrentUser2 as useCurrentUser,
1004
+ useSections2 as useSections,
1005
+ useSignOut2 as useSignOut
2938
1006
  };
2939
1007
 
2940
- //# debugId=0F17895FA991402664756E2164756E21
1008
+ //# debugId=7916C4F03DB2976764756E2164756E21