@agent-native/core 0.5.0-dev.b51eaae → 0.6.1

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 (806) hide show
  1. package/README.md +15 -43
  2. package/dist/a2a/agent-card.d.ts.map +1 -1
  3. package/dist/a2a/agent-card.js +12 -1
  4. package/dist/a2a/agent-card.js.map +1 -1
  5. package/dist/a2a/client.d.ts +11 -0
  6. package/dist/a2a/client.d.ts.map +1 -1
  7. package/dist/a2a/client.js +38 -1
  8. package/dist/a2a/client.js.map +1 -1
  9. package/dist/a2a/index.d.ts +1 -1
  10. package/dist/a2a/index.d.ts.map +1 -1
  11. package/dist/a2a/index.js +1 -1
  12. package/dist/a2a/index.js.map +1 -1
  13. package/dist/a2a/server.d.ts +4 -0
  14. package/dist/a2a/server.d.ts.map +1 -1
  15. package/dist/a2a/server.js +53 -8
  16. package/dist/a2a/server.js.map +1 -1
  17. package/dist/a2a/types.d.ts +1 -0
  18. package/dist/a2a/types.d.ts.map +1 -1
  19. package/dist/action.d.ts +64 -30
  20. package/dist/action.d.ts.map +1 -1
  21. package/dist/action.js +224 -27
  22. package/dist/action.js.map +1 -1
  23. package/dist/agent/engine/ai-sdk-engine.d.ts +24 -0
  24. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -0
  25. package/dist/agent/engine/ai-sdk-engine.js +302 -0
  26. package/dist/agent/engine/ai-sdk-engine.js.map +1 -0
  27. package/dist/agent/engine/anthropic-engine.d.ts +24 -0
  28. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -0
  29. package/dist/agent/engine/anthropic-engine.js +169 -0
  30. package/dist/agent/engine/anthropic-engine.js.map +1 -0
  31. package/dist/agent/engine/builtin.d.ts +12 -0
  32. package/dist/agent/engine/builtin.d.ts.map +1 -0
  33. package/dist/agent/engine/builtin.js +72 -0
  34. package/dist/agent/engine/builtin.js.map +1 -0
  35. package/dist/agent/engine/index.d.ts +9 -0
  36. package/dist/agent/engine/index.d.ts.map +1 -0
  37. package/dist/agent/engine/index.js +8 -0
  38. package/dist/agent/engine/index.js.map +1 -0
  39. package/dist/agent/engine/registry.d.ts +61 -0
  40. package/dist/agent/engine/registry.d.ts.map +1 -0
  41. package/dist/agent/engine/registry.js +101 -0
  42. package/dist/agent/engine/registry.js.map +1 -0
  43. package/dist/agent/engine/translate-ai-sdk.d.ts +20 -0
  44. package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -0
  45. package/dist/agent/engine/translate-ai-sdk.js +174 -0
  46. package/dist/agent/engine/translate-ai-sdk.js.map +1 -0
  47. package/dist/agent/engine/translate-anthropic.d.ts +23 -0
  48. package/dist/agent/engine/translate-anthropic.d.ts.map +1 -0
  49. package/dist/agent/engine/translate-anthropic.js +140 -0
  50. package/dist/agent/engine/translate-anthropic.js.map +1 -0
  51. package/dist/agent/engine/types.d.ts +168 -0
  52. package/dist/agent/engine/types.d.ts.map +1 -0
  53. package/dist/agent/engine/types.js +13 -0
  54. package/dist/agent/engine/types.js.map +1 -0
  55. package/dist/agent/production-agent.d.ts +48 -2
  56. package/dist/agent/production-agent.d.ts.map +1 -1
  57. package/dist/agent/production-agent.js +216 -76
  58. package/dist/agent/production-agent.js.map +1 -1
  59. package/dist/agent/run-manager.d.ts +1 -1
  60. package/dist/agent/run-manager.d.ts.map +1 -1
  61. package/dist/agent/run-manager.js +15 -9
  62. package/dist/agent/run-manager.js.map +1 -1
  63. package/dist/agent/run-store.d.ts.map +1 -1
  64. package/dist/agent/run-store.js +5 -5
  65. package/dist/agent/run-store.js.map +1 -1
  66. package/dist/agent/thread-data-builder.d.ts +1 -0
  67. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  68. package/dist/agent/thread-data-builder.js +4 -1
  69. package/dist/agent/thread-data-builder.js.map +1 -1
  70. package/dist/agent/types.d.ts +22 -1
  71. package/dist/agent/types.d.ts.map +1 -1
  72. package/dist/application-state/handlers.d.ts +8 -8
  73. package/dist/application-state/handlers.d.ts.map +1 -1
  74. package/dist/application-state/handlers.js +3 -2
  75. package/dist/application-state/handlers.js.map +1 -1
  76. package/dist/application-state/script-helpers.d.ts.map +1 -1
  77. package/dist/application-state/script-helpers.js +47 -9
  78. package/dist/application-state/script-helpers.js.map +1 -1
  79. package/dist/chat-threads/store.d.ts +14 -0
  80. package/dist/chat-threads/store.d.ts.map +1 -1
  81. package/dist/chat-threads/store.js +32 -0
  82. package/dist/chat-threads/store.js.map +1 -1
  83. package/dist/cli/create.d.ts +8 -2
  84. package/dist/cli/create.d.ts.map +1 -1
  85. package/dist/cli/create.js +287 -32
  86. package/dist/cli/create.js.map +1 -1
  87. package/dist/cli/index.js +19 -6
  88. package/dist/cli/index.js.map +1 -1
  89. package/dist/client/AgentPanel.d.ts +5 -1
  90. package/dist/client/AgentPanel.d.ts.map +1 -1
  91. package/dist/client/AgentPanel.js +407 -111
  92. package/dist/client/AgentPanel.js.map +1 -1
  93. package/dist/client/AgentTaskCard.d.ts +12 -0
  94. package/dist/client/AgentTaskCard.d.ts.map +1 -0
  95. package/dist/client/AgentTaskCard.js +146 -0
  96. package/dist/client/AgentTaskCard.js.map +1 -0
  97. package/dist/client/AssistantChat.d.ts +13 -2
  98. package/dist/client/AssistantChat.d.ts.map +1 -1
  99. package/dist/client/AssistantChat.js +344 -122
  100. package/dist/client/AssistantChat.js.map +1 -1
  101. package/dist/client/MultiTabAssistantChat.d.ts +7 -1
  102. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  103. package/dist/client/MultiTabAssistantChat.js +345 -63
  104. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  105. package/dist/client/PoweredByBadge.js +2 -2
  106. package/dist/client/PoweredByBadge.js.map +1 -1
  107. package/dist/client/Turnstile.d.ts.map +1 -1
  108. package/dist/client/Turnstile.js +2 -3
  109. package/dist/client/Turnstile.js.map +1 -1
  110. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  111. package/dist/client/agent-chat-adapter.js +63 -2
  112. package/dist/client/agent-chat-adapter.js.map +1 -1
  113. package/dist/client/agent-chat.d.ts +14 -1
  114. package/dist/client/agent-chat.d.ts.map +1 -1
  115. package/dist/client/agent-chat.js +4 -2
  116. package/dist/client/agent-chat.js.map +1 -1
  117. package/dist/client/components/CodeAgentIndicator.d.ts +14 -0
  118. package/dist/client/components/CodeAgentIndicator.d.ts.map +1 -0
  119. package/dist/client/components/CodeAgentIndicator.js +29 -0
  120. package/dist/client/components/CodeAgentIndicator.js.map +1 -0
  121. package/dist/client/composer/MentionPopover.d.ts +4 -1
  122. package/dist/client/composer/MentionPopover.d.ts.map +1 -1
  123. package/dist/client/composer/MentionPopover.js +36 -6
  124. package/dist/client/composer/MentionPopover.js.map +1 -1
  125. package/dist/client/composer/TiptapComposer.d.ts +8 -1
  126. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  127. package/dist/client/composer/TiptapComposer.js +146 -16
  128. package/dist/client/composer/TiptapComposer.js.map +1 -1
  129. package/dist/client/composer/index.d.ts +1 -1
  130. package/dist/client/composer/index.d.ts.map +1 -1
  131. package/dist/client/composer/types.d.ts +5 -0
  132. package/dist/client/composer/types.d.ts.map +1 -1
  133. package/dist/client/composer/use-mention-search.d.ts.map +1 -1
  134. package/dist/client/composer/use-mention-search.js +46 -13
  135. package/dist/client/composer/use-mention-search.js.map +1 -1
  136. package/dist/client/frame-protocol.d.ts +54 -0
  137. package/dist/client/frame-protocol.d.ts.map +1 -0
  138. package/dist/client/frame-protocol.js +9 -0
  139. package/dist/client/frame-protocol.js.map +1 -0
  140. package/dist/client/frame.d.ts +56 -0
  141. package/dist/client/frame.d.ts.map +1 -0
  142. package/dist/client/{harness.js → frame.js} +49 -26
  143. package/dist/client/frame.js.map +1 -0
  144. package/dist/client/index.d.ts +7 -3
  145. package/dist/client/index.d.ts.map +1 -1
  146. package/dist/client/index.js +6 -3
  147. package/dist/client/index.js.map +1 -1
  148. package/dist/client/integrations/IntegrationCard.d.ts +6 -0
  149. package/dist/client/integrations/IntegrationCard.d.ts.map +1 -0
  150. package/dist/client/integrations/IntegrationCard.js +45 -0
  151. package/dist/client/integrations/IntegrationCard.js.map +1 -0
  152. package/dist/client/integrations/IntegrationsPanel.d.ts +2 -0
  153. package/dist/client/integrations/IntegrationsPanel.d.ts.map +1 -0
  154. package/dist/client/integrations/IntegrationsPanel.js +149 -0
  155. package/dist/client/integrations/IntegrationsPanel.js.map +1 -0
  156. package/dist/client/integrations/index.d.ts +4 -0
  157. package/dist/client/integrations/index.d.ts.map +1 -0
  158. package/dist/client/integrations/index.js +3 -0
  159. package/dist/client/integrations/index.js.map +1 -0
  160. package/dist/client/integrations/useIntegrationStatus.d.ts +15 -0
  161. package/dist/client/integrations/useIntegrationStatus.d.ts.map +1 -0
  162. package/dist/client/integrations/useIntegrationStatus.js +37 -0
  163. package/dist/client/integrations/useIntegrationStatus.js.map +1 -0
  164. package/dist/client/org/InvitationBanner.d.ts +9 -0
  165. package/dist/client/org/InvitationBanner.d.ts.map +1 -0
  166. package/dist/client/org/InvitationBanner.js +17 -0
  167. package/dist/client/org/InvitationBanner.js.map +1 -0
  168. package/dist/client/org/OrgSwitcher.d.ts +14 -0
  169. package/dist/client/org/OrgSwitcher.d.ts.map +1 -0
  170. package/dist/client/org/OrgSwitcher.js +51 -0
  171. package/dist/client/org/OrgSwitcher.js.map +1 -0
  172. package/dist/client/org/TeamPage.d.ts +23 -0
  173. package/dist/client/org/TeamPage.d.ts.map +1 -0
  174. package/dist/client/org/TeamPage.js +145 -0
  175. package/dist/client/org/TeamPage.js.map +1 -0
  176. package/dist/client/org/hooks.d.ts +14 -0
  177. package/dist/client/org/hooks.d.ts.map +1 -0
  178. package/dist/client/org/hooks.js +101 -0
  179. package/dist/client/org/hooks.js.map +1 -0
  180. package/dist/client/org/index.d.ts +6 -0
  181. package/dist/client/org/index.d.ts.map +1 -0
  182. package/dist/client/org/index.js +6 -0
  183. package/dist/client/org/index.js.map +1 -0
  184. package/dist/client/resources/ResourceEditor.d.ts +8 -1
  185. package/dist/client/resources/ResourceEditor.d.ts.map +1 -1
  186. package/dist/client/resources/ResourceEditor.js +94 -13
  187. package/dist/client/resources/ResourceEditor.js.map +1 -1
  188. package/dist/client/resources/ResourceTree.d.ts +5 -1
  189. package/dist/client/resources/ResourceTree.d.ts.map +1 -1
  190. package/dist/client/resources/ResourceTree.js +18 -3
  191. package/dist/client/resources/ResourceTree.js.map +1 -1
  192. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  193. package/dist/client/resources/ResourcesPanel.js +135 -110
  194. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  195. package/dist/client/resources/use-resources.d.ts +10 -0
  196. package/dist/client/resources/use-resources.d.ts.map +1 -1
  197. package/dist/client/resources/use-resources.js +2 -2
  198. package/dist/client/resources/use-resources.js.map +1 -1
  199. package/dist/client/sse-event-processor.d.ts +9 -1
  200. package/dist/client/sse-event-processor.d.ts.map +1 -1
  201. package/dist/client/sse-event-processor.js +36 -3
  202. package/dist/client/sse-event-processor.js.map +1 -1
  203. package/dist/client/terminal/AgentTerminal.d.ts +4 -4
  204. package/dist/client/terminal/AgentTerminal.d.ts.map +1 -1
  205. package/dist/client/terminal/AgentTerminal.js +14 -14
  206. package/dist/client/terminal/AgentTerminal.js.map +1 -1
  207. package/dist/client/use-action.d.ts +51 -0
  208. package/dist/client/use-action.d.ts.map +1 -0
  209. package/dist/client/use-action.js +102 -0
  210. package/dist/client/use-action.js.map +1 -0
  211. package/dist/client/use-avatar.d.ts +15 -0
  212. package/dist/client/use-avatar.d.ts.map +1 -0
  213. package/dist/client/use-avatar.js +116 -0
  214. package/dist/client/use-avatar.js.map +1 -0
  215. package/dist/client/use-chat-threads.d.ts +1 -1
  216. package/dist/client/use-chat-threads.d.ts.map +1 -1
  217. package/dist/client/use-chat-threads.js +34 -18
  218. package/dist/client/use-chat-threads.js.map +1 -1
  219. package/dist/client/use-dev-mode.d.ts.map +1 -1
  220. package/dist/client/use-dev-mode.js +2 -0
  221. package/dist/client/use-dev-mode.js.map +1 -1
  222. package/dist/client/use-send-to-agent-chat.d.ts +7 -4
  223. package/dist/client/use-send-to-agent-chat.d.ts.map +1 -1
  224. package/dist/client/use-send-to-agent-chat.js +31 -10
  225. package/dist/client/use-send-to-agent-chat.js.map +1 -1
  226. package/dist/collab/awareness.d.ts +41 -0
  227. package/dist/collab/awareness.d.ts.map +1 -0
  228. package/dist/collab/awareness.js +82 -0
  229. package/dist/collab/awareness.js.map +1 -0
  230. package/dist/collab/client.d.ts +49 -0
  231. package/dist/collab/client.d.ts.map +1 -0
  232. package/dist/collab/client.js +250 -0
  233. package/dist/collab/client.js.map +1 -0
  234. package/dist/collab/emitter.d.ts +12 -0
  235. package/dist/collab/emitter.d.ts.map +1 -0
  236. package/dist/collab/emitter.js +16 -0
  237. package/dist/collab/emitter.js.map +1 -0
  238. package/dist/collab/index.d.ts +7 -0
  239. package/dist/collab/index.d.ts.map +1 -0
  240. package/dist/collab/index.js +14 -0
  241. package/dist/collab/index.js.map +1 -0
  242. package/dist/collab/routes.d.ts +69 -0
  243. package/dist/collab/routes.d.ts.map +1 -0
  244. package/dist/collab/routes.js +98 -0
  245. package/dist/collab/routes.js.map +1 -0
  246. package/dist/collab/storage.d.ts +18 -0
  247. package/dist/collab/storage.d.ts.map +1 -0
  248. package/dist/collab/storage.js +94 -0
  249. package/dist/collab/storage.js.map +1 -0
  250. package/dist/collab/text-to-yjs.d.ts +23 -0
  251. package/dist/collab/text-to-yjs.d.ts.map +1 -0
  252. package/dist/collab/text-to-yjs.js +63 -0
  253. package/dist/collab/text-to-yjs.js.map +1 -0
  254. package/dist/collab/xml-ops.d.ts +20 -0
  255. package/dist/collab/xml-ops.d.ts.map +1 -0
  256. package/dist/collab/xml-ops.js +59 -0
  257. package/dist/collab/xml-ops.js.map +1 -0
  258. package/dist/collab/ydoc-manager.d.ts +52 -0
  259. package/dist/collab/ydoc-manager.d.ts.map +1 -0
  260. package/dist/collab/ydoc-manager.js +154 -0
  261. package/dist/collab/ydoc-manager.js.map +1 -0
  262. package/dist/db/client.d.ts +10 -0
  263. package/dist/db/client.d.ts.map +1 -1
  264. package/dist/db/client.js +43 -2
  265. package/dist/db/client.js.map +1 -1
  266. package/dist/db/create-get-db.js.map +1 -1
  267. package/dist/db/index.d.ts +1 -1
  268. package/dist/db/index.d.ts.map +1 -1
  269. package/dist/db/index.js +1 -1
  270. package/dist/db/index.js.map +1 -1
  271. package/dist/db/migrations.d.ts +9 -1
  272. package/dist/db/migrations.d.ts.map +1 -1
  273. package/dist/db/migrations.js +45 -20
  274. package/dist/db/migrations.js.map +1 -1
  275. package/dist/db/schema.d.ts +8 -1
  276. package/dist/db/schema.d.ts.map +1 -1
  277. package/dist/db/schema.js +13 -2
  278. package/dist/db/schema.js.map +1 -1
  279. package/dist/deploy/build.js +607 -42
  280. package/dist/deploy/build.js.map +1 -1
  281. package/dist/deploy/route-discovery.d.ts +17 -4
  282. package/dist/deploy/route-discovery.d.ts.map +1 -1
  283. package/dist/deploy/route-discovery.js +117 -35
  284. package/dist/deploy/route-discovery.js.map +1 -1
  285. package/dist/index.browser.d.ts +2 -0
  286. package/dist/index.browser.d.ts.map +1 -1
  287. package/dist/index.browser.js +4 -0
  288. package/dist/index.browser.js.map +1 -1
  289. package/dist/index.d.ts +3 -3
  290. package/dist/index.d.ts.map +1 -1
  291. package/dist/index.js +2 -2
  292. package/dist/index.js.map +1 -1
  293. package/dist/integrations/adapters/slack.d.ts +10 -0
  294. package/dist/integrations/adapters/slack.d.ts.map +1 -0
  295. package/dist/integrations/adapters/slack.js +215 -0
  296. package/dist/integrations/adapters/slack.js.map +1 -0
  297. package/dist/integrations/adapters/telegram.d.ts +12 -0
  298. package/dist/integrations/adapters/telegram.d.ts.map +1 -0
  299. package/dist/integrations/adapters/telegram.js +184 -0
  300. package/dist/integrations/adapters/telegram.js.map +1 -0
  301. package/dist/integrations/adapters/whatsapp.d.ts +14 -0
  302. package/dist/integrations/adapters/whatsapp.d.ts.map +1 -0
  303. package/dist/integrations/adapters/whatsapp.js +205 -0
  304. package/dist/integrations/adapters/whatsapp.js.map +1 -0
  305. package/dist/integrations/config-store.d.ts +24 -0
  306. package/dist/integrations/config-store.d.ts.map +1 -0
  307. package/dist/integrations/config-store.js +92 -0
  308. package/dist/integrations/config-store.js.map +1 -0
  309. package/dist/integrations/index.d.ts +8 -0
  310. package/dist/integrations/index.d.ts.map +1 -0
  311. package/dist/integrations/index.js +10 -0
  312. package/dist/integrations/index.js.map +1 -0
  313. package/dist/integrations/plugin.d.ts +20 -0
  314. package/dist/integrations/plugin.d.ts.map +1 -0
  315. package/dist/integrations/plugin.js +213 -0
  316. package/dist/integrations/plugin.js.map +1 -0
  317. package/dist/integrations/thread-mapping-store.d.ts +25 -0
  318. package/dist/integrations/thread-mapping-store.d.ts.map +1 -0
  319. package/dist/integrations/thread-mapping-store.js +95 -0
  320. package/dist/integrations/thread-mapping-store.js.map +1 -0
  321. package/dist/integrations/types.d.ts +111 -0
  322. package/dist/integrations/types.d.ts.map +1 -0
  323. package/dist/integrations/types.js +2 -0
  324. package/dist/integrations/types.js.map +1 -0
  325. package/dist/integrations/webhook-handler.d.ts +31 -0
  326. package/dist/integrations/webhook-handler.d.ts.map +1 -0
  327. package/dist/integrations/webhook-handler.js +210 -0
  328. package/dist/integrations/webhook-handler.js.map +1 -0
  329. package/dist/jobs/cron.d.ts +14 -0
  330. package/dist/jobs/cron.d.ts.map +1 -0
  331. package/dist/jobs/cron.js +100 -0
  332. package/dist/jobs/cron.js.map +1 -0
  333. package/dist/jobs/index.d.ts +4 -0
  334. package/dist/jobs/index.d.ts.map +1 -0
  335. package/dist/jobs/index.js +4 -0
  336. package/dist/jobs/index.js.map +1 -0
  337. package/dist/jobs/scheduler.d.ts +29 -0
  338. package/dist/jobs/scheduler.d.ts.map +1 -0
  339. package/dist/jobs/scheduler.js +205 -0
  340. package/dist/jobs/scheduler.js.map +1 -0
  341. package/dist/jobs/tools.d.ts +3 -0
  342. package/dist/jobs/tools.d.ts.map +1 -0
  343. package/dist/jobs/tools.js +192 -0
  344. package/dist/jobs/tools.js.map +1 -0
  345. package/dist/mcp/index.d.ts +3 -0
  346. package/dist/mcp/index.d.ts.map +1 -0
  347. package/dist/mcp/index.js +2 -0
  348. package/dist/mcp/index.js.map +1 -0
  349. package/dist/mcp/server.d.ts +26 -0
  350. package/dist/mcp/server.d.ts.map +1 -0
  351. package/dist/mcp/server.js +182 -0
  352. package/dist/mcp/server.js.map +1 -0
  353. package/dist/oauth-tokens/index.d.ts +1 -1
  354. package/dist/oauth-tokens/index.d.ts.map +1 -1
  355. package/dist/oauth-tokens/index.js +1 -1
  356. package/dist/oauth-tokens/index.js.map +1 -1
  357. package/dist/oauth-tokens/store.d.ts +5 -0
  358. package/dist/oauth-tokens/store.d.ts.map +1 -1
  359. package/dist/oauth-tokens/store.js +30 -7
  360. package/dist/oauth-tokens/store.js.map +1 -1
  361. package/dist/org/context.d.ts +11 -0
  362. package/dist/org/context.d.ts.map +1 -0
  363. package/dist/org/context.js +61 -0
  364. package/dist/org/context.js.map +1 -0
  365. package/dist/org/handlers.d.ts +66 -0
  366. package/dist/org/handlers.d.ts.map +1 -0
  367. package/dist/org/handlers.js +306 -0
  368. package/dist/org/handlers.js.map +1 -0
  369. package/dist/org/index.d.ts +7 -0
  370. package/dist/org/index.d.ts.map +1 -0
  371. package/dist/org/index.js +11 -0
  372. package/dist/org/index.js.map +1 -0
  373. package/dist/org/migrations.d.ts +10 -0
  374. package/dist/org/migrations.d.ts.map +1 -0
  375. package/dist/org/migrations.js +39 -0
  376. package/dist/org/migrations.js.map +1 -0
  377. package/dist/org/plugin.d.ts +26 -0
  378. package/dist/org/plugin.d.ts.map +1 -0
  379. package/dist/org/plugin.js +94 -0
  380. package/dist/org/plugin.js.map +1 -0
  381. package/dist/org/schema.d.ts +301 -0
  382. package/dist/org/schema.d.ts.map +1 -0
  383. package/dist/org/schema.js +23 -0
  384. package/dist/org/schema.js.map +1 -0
  385. package/dist/org/types.d.ts +42 -0
  386. package/dist/org/types.d.ts.map +1 -0
  387. package/dist/org/types.js +5 -0
  388. package/dist/org/types.js.map +1 -0
  389. package/dist/resources/handlers.d.ts +10 -1
  390. package/dist/resources/handlers.d.ts.map +1 -1
  391. package/dist/resources/handlers.js +82 -9
  392. package/dist/resources/handlers.js.map +1 -1
  393. package/dist/resources/store.d.ts +5 -0
  394. package/dist/resources/store.d.ts.map +1 -1
  395. package/dist/resources/store.js +44 -0
  396. package/dist/resources/store.js.map +1 -1
  397. package/dist/scripts/agent-engines/list-agent-engines.d.ts +7 -0
  398. package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -0
  399. package/dist/scripts/agent-engines/list-agent-engines.js +42 -0
  400. package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -0
  401. package/dist/scripts/agent-engines/set-agent-engine.d.ts +7 -0
  402. package/dist/scripts/agent-engines/set-agent-engine.d.ts.map +1 -0
  403. package/dist/scripts/agent-engines/set-agent-engine.js +57 -0
  404. package/dist/scripts/agent-engines/set-agent-engine.js.map +1 -0
  405. package/dist/scripts/agent-engines/test-agent-engine.d.ts +7 -0
  406. package/dist/scripts/agent-engines/test-agent-engine.d.ts.map +1 -0
  407. package/dist/scripts/agent-engines/test-agent-engine.js +102 -0
  408. package/dist/scripts/agent-engines/test-agent-engine.js.map +1 -0
  409. package/dist/scripts/call-agent.d.ts +1 -1
  410. package/dist/scripts/call-agent.d.ts.map +1 -1
  411. package/dist/scripts/call-agent.js +10 -6
  412. package/dist/scripts/call-agent.js.map +1 -1
  413. package/dist/scripts/chat/index.d.ts +2 -0
  414. package/dist/scripts/chat/index.d.ts.map +1 -0
  415. package/dist/scripts/chat/index.js +5 -0
  416. package/dist/scripts/chat/index.js.map +1 -0
  417. package/dist/scripts/chat/open-chat.d.ts +11 -0
  418. package/dist/scripts/chat/open-chat.d.ts.map +1 -0
  419. package/dist/scripts/chat/open-chat.js +48 -0
  420. package/dist/scripts/chat/open-chat.js.map +1 -0
  421. package/dist/scripts/chat/search-chats.d.ts +10 -0
  422. package/dist/scripts/chat/search-chats.d.ts.map +1 -0
  423. package/dist/scripts/chat/search-chats.js +89 -0
  424. package/dist/scripts/chat/search-chats.js.map +1 -0
  425. package/dist/scripts/core-scripts.d.ts.map +1 -1
  426. package/dist/scripts/core-scripts.js +2 -0
  427. package/dist/scripts/core-scripts.js.map +1 -1
  428. package/dist/scripts/db/check-scoping.d.ts +14 -0
  429. package/dist/scripts/db/check-scoping.d.ts.map +1 -0
  430. package/dist/scripts/db/check-scoping.js +174 -0
  431. package/dist/scripts/db/check-scoping.js.map +1 -0
  432. package/dist/scripts/db/exec.d.ts +3 -2
  433. package/dist/scripts/db/exec.d.ts.map +1 -1
  434. package/dist/scripts/db/exec.js +35 -19
  435. package/dist/scripts/db/exec.js.map +1 -1
  436. package/dist/scripts/db/index.d.ts.map +1 -1
  437. package/dist/scripts/db/index.js +2 -0
  438. package/dist/scripts/db/index.js.map +1 -1
  439. package/dist/scripts/db/patch.d.ts +50 -0
  440. package/dist/scripts/db/patch.d.ts.map +1 -0
  441. package/dist/scripts/db/patch.js +392 -0
  442. package/dist/scripts/db/patch.js.map +1 -0
  443. package/dist/scripts/db/scoping.d.ts +8 -2
  444. package/dist/scripts/db/scoping.d.ts.map +1 -1
  445. package/dist/scripts/db/scoping.js +64 -46
  446. package/dist/scripts/db/scoping.js.map +1 -1
  447. package/dist/scripts/dev/index.d.ts.map +1 -1
  448. package/dist/scripts/dev/index.js +64 -1
  449. package/dist/scripts/dev/index.js.map +1 -1
  450. package/dist/scripts/parse-args.d.ts +14 -0
  451. package/dist/scripts/parse-args.d.ts.map +1 -0
  452. package/dist/scripts/parse-args.js +45 -0
  453. package/dist/scripts/parse-args.js.map +1 -0
  454. package/dist/scripts/runner.d.ts.map +1 -1
  455. package/dist/scripts/runner.js +10 -2
  456. package/dist/scripts/runner.js.map +1 -1
  457. package/dist/scripts/utils.d.ts +1 -9
  458. package/dist/scripts/utils.d.ts.map +1 -1
  459. package/dist/scripts/utils.js +2 -40
  460. package/dist/scripts/utils.js.map +1 -1
  461. package/dist/server/action-discovery.d.ts.map +1 -1
  462. package/dist/server/action-discovery.js +84 -16
  463. package/dist/server/action-discovery.js.map +1 -1
  464. package/dist/server/action-routes.d.ts +15 -0
  465. package/dist/server/action-routes.d.ts.map +1 -0
  466. package/dist/server/action-routes.js +105 -0
  467. package/dist/server/action-routes.js.map +1 -0
  468. package/dist/server/agent-chat-plugin.d.ts +20 -0
  469. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  470. package/dist/server/agent-chat-plugin.js +1149 -256
  471. package/dist/server/agent-chat-plugin.js.map +1 -1
  472. package/dist/server/agent-discovery.d.ts +8 -3
  473. package/dist/server/agent-discovery.d.ts.map +1 -1
  474. package/dist/server/agent-discovery.js +69 -8
  475. package/dist/server/agent-discovery.js.map +1 -1
  476. package/dist/server/agent-teams.d.ts +70 -0
  477. package/dist/server/agent-teams.d.ts.map +1 -0
  478. package/dist/server/agent-teams.js +367 -0
  479. package/dist/server/agent-teams.js.map +1 -0
  480. package/dist/server/agents-bundle.d.ts +87 -0
  481. package/dist/server/agents-bundle.d.ts.map +1 -0
  482. package/dist/server/agents-bundle.js +231 -0
  483. package/dist/server/agents-bundle.js.map +1 -0
  484. package/dist/server/auth-plugin.d.ts +3 -3
  485. package/dist/server/auth-plugin.d.ts.map +1 -1
  486. package/dist/server/auth-plugin.js +9 -10
  487. package/dist/server/auth-plugin.js.map +1 -1
  488. package/dist/server/auth.d.ts +54 -33
  489. package/dist/server/auth.d.ts.map +1 -1
  490. package/dist/server/auth.js +529 -611
  491. package/dist/server/auth.js.map +1 -1
  492. package/dist/server/better-auth-instance.d.ts +72 -0
  493. package/dist/server/better-auth-instance.d.ts.map +1 -0
  494. package/dist/server/better-auth-instance.js +144 -0
  495. package/dist/server/better-auth-instance.js.map +1 -0
  496. package/dist/server/collab-plugin.d.ts +29 -0
  497. package/dist/server/collab-plugin.d.ts.map +1 -0
  498. package/dist/server/collab-plugin.js +85 -0
  499. package/dist/server/collab-plugin.js.map +1 -0
  500. package/dist/server/core-routes-plugin.d.ts +0 -3
  501. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  502. package/dist/server/core-routes-plugin.js +97 -27
  503. package/dist/server/core-routes-plugin.js.map +1 -1
  504. package/dist/server/create-server.d.ts +1 -1
  505. package/dist/server/create-server.d.ts.map +1 -1
  506. package/dist/server/create-server.js +39 -16
  507. package/dist/server/create-server.js.map +1 -1
  508. package/dist/server/framework-request-handler.d.ts +47 -0
  509. package/dist/server/framework-request-handler.d.ts.map +1 -0
  510. package/dist/server/framework-request-handler.js +168 -0
  511. package/dist/server/framework-request-handler.js.map +1 -0
  512. package/dist/server/google-auth-plugin.d.ts +4 -0
  513. package/dist/server/google-auth-plugin.d.ts.map +1 -1
  514. package/dist/server/google-auth-plugin.js +13 -12
  515. package/dist/server/google-auth-plugin.js.map +1 -1
  516. package/dist/server/google-oauth.d.ts +3 -3
  517. package/dist/server/google-oauth.d.ts.map +1 -1
  518. package/dist/server/google-oauth.js +40 -18
  519. package/dist/server/google-oauth.js.map +1 -1
  520. package/dist/server/h3-helpers.d.ts +23 -0
  521. package/dist/server/h3-helpers.d.ts.map +1 -0
  522. package/dist/server/h3-helpers.js +37 -0
  523. package/dist/server/h3-helpers.js.map +1 -0
  524. package/dist/server/index.d.ts +9 -4
  525. package/dist/server/index.d.ts.map +1 -1
  526. package/dist/server/index.js +12 -4
  527. package/dist/server/index.js.map +1 -1
  528. package/dist/server/local-migration.d.ts +32 -0
  529. package/dist/server/local-migration.d.ts.map +1 -0
  530. package/dist/server/local-migration.js +205 -0
  531. package/dist/server/local-migration.js.map +1 -0
  532. package/dist/server/oauth-helpers.d.ts +4 -6
  533. package/dist/server/oauth-helpers.d.ts.map +1 -1
  534. package/dist/server/oauth-helpers.js +6 -8
  535. package/dist/server/oauth-helpers.js.map +1 -1
  536. package/dist/server/onboarding-html.d.ts +24 -0
  537. package/dist/server/onboarding-html.d.ts.map +1 -0
  538. package/dist/server/onboarding-html.js +347 -0
  539. package/dist/server/onboarding-html.js.map +1 -0
  540. package/dist/server/poll.d.ts +7 -2
  541. package/dist/server/poll.d.ts.map +1 -1
  542. package/dist/server/poll.js +48 -1
  543. package/dist/server/poll.js.map +1 -1
  544. package/dist/server/resources-plugin.d.ts.map +1 -1
  545. package/dist/server/resources-plugin.js +4 -3
  546. package/dist/server/resources-plugin.js.map +1 -1
  547. package/dist/server/schema-prompt.d.ts +16 -0
  548. package/dist/server/schema-prompt.d.ts.map +1 -0
  549. package/dist/server/schema-prompt.js +275 -0
  550. package/dist/server/schema-prompt.js.map +1 -0
  551. package/dist/server/sse.d.ts +3 -20
  552. package/dist/server/sse.d.ts.map +1 -1
  553. package/dist/server/sse.js +1 -29
  554. package/dist/server/sse.js.map +1 -1
  555. package/dist/server/ssr-handler.d.ts +6 -0
  556. package/dist/server/ssr-handler.d.ts.map +1 -0
  557. package/dist/server/ssr-handler.js +55 -0
  558. package/dist/server/ssr-handler.js.map +1 -0
  559. package/dist/settings/handlers.d.ts +3 -3
  560. package/dist/settings/handlers.d.ts.map +1 -1
  561. package/dist/settings/handlers.js +2 -1
  562. package/dist/settings/handlers.js.map +1 -1
  563. package/dist/settings/index.d.ts +1 -0
  564. package/dist/settings/index.d.ts.map +1 -1
  565. package/dist/settings/index.js +2 -0
  566. package/dist/settings/index.js.map +1 -1
  567. package/dist/settings/org-settings.d.ts +22 -0
  568. package/dist/settings/org-settings.d.ts.map +1 -0
  569. package/dist/settings/org-settings.js +45 -0
  570. package/dist/settings/org-settings.js.map +1 -0
  571. package/dist/shared/agent-chat.d.ts +5 -5
  572. package/dist/shared/agent-chat.d.ts.map +1 -1
  573. package/dist/shared/agent-chat.js +8 -8
  574. package/dist/shared/agent-chat.js.map +1 -1
  575. package/dist/shared/agent-env.d.ts +1 -1
  576. package/dist/shared/agent-env.js +1 -1
  577. package/dist/shared/runtime.d.ts +14 -0
  578. package/dist/shared/runtime.d.ts.map +1 -0
  579. package/dist/shared/runtime.js +25 -0
  580. package/dist/shared/runtime.js.map +1 -0
  581. package/dist/templates/default/.agents/skills/actions/SKILL.md +142 -0
  582. package/dist/templates/default/.agents/skills/agent-engines/SKILL.md +127 -0
  583. package/dist/templates/default/.agents/skills/capture-learnings/SKILL.md +50 -0
  584. package/dist/templates/default/.agents/skills/create-skill/SKILL.md +167 -0
  585. package/dist/templates/default/.agents/skills/delegate-to-agent/SKILL.md +90 -0
  586. package/dist/templates/default/.agents/skills/frontend-design/SKILL.md +69 -0
  587. package/dist/templates/default/.agents/skills/real-time-collab/SKILL.md +183 -0
  588. package/dist/templates/default/.agents/skills/real-time-sync/SKILL.md +112 -0
  589. package/dist/templates/default/.agents/skills/security/SKILL.md +108 -0
  590. package/dist/templates/default/.agents/skills/self-modifying-code/SKILL.md +79 -0
  591. package/dist/templates/default/.claude/settings.json +100 -0
  592. package/dist/templates/default/.env.example +5 -0
  593. package/dist/templates/default/.prettierrc +5 -0
  594. package/dist/templates/default/AGENTS.md +110 -0
  595. package/dist/templates/default/DEVELOPING.md +117 -0
  596. package/dist/templates/default/_gitignore +37 -0
  597. package/dist/templates/default/actions/hello.ts +20 -0
  598. package/dist/templates/default/actions/navigate.ts +53 -0
  599. package/dist/templates/default/actions/run.ts +2 -0
  600. package/dist/templates/default/actions/view-screen.ts +39 -0
  601. package/dist/templates/default/app/entry.client.tsx +4 -0
  602. package/dist/templates/default/app/entry.server.tsx +56 -0
  603. package/dist/templates/default/app/global.css +95 -0
  604. package/dist/templates/default/app/lib/utils.ts +1 -0
  605. package/dist/templates/default/app/root.tsx +107 -0
  606. package/dist/templates/default/app/routes/_index.tsx +62 -0
  607. package/dist/templates/default/app/routes.ts +4 -0
  608. package/dist/templates/default/app/vite-env.d.ts +6 -0
  609. package/dist/templates/default/components.json +20 -0
  610. package/dist/templates/default/data/.gitkeep +0 -0
  611. package/dist/templates/default/data/sync-config.json +1 -0
  612. package/dist/templates/default/learnings.defaults.md +5 -0
  613. package/dist/templates/default/learnings.md +0 -0
  614. package/dist/templates/default/package.json +46 -0
  615. package/dist/templates/default/postcss.config.js +6 -0
  616. package/dist/templates/default/public/icon-180.svg +4 -0
  617. package/dist/templates/default/public/icon-192.svg +4 -0
  618. package/dist/templates/default/public/icon-512.svg +4 -0
  619. package/dist/templates/default/public/manifest.json +13 -0
  620. package/dist/templates/default/react-router.config.ts +6 -0
  621. package/dist/templates/default/server/middleware/auth.ts +15 -0
  622. package/dist/templates/default/server/plugins/.gitkeep +0 -0
  623. package/dist/templates/default/server/routes/[...page].get.ts +5 -0
  624. package/dist/templates/default/server/routes/api/hello.get.ts +5 -0
  625. package/dist/templates/default/shared/api.ts +6 -0
  626. package/dist/templates/default/ssr-entry.ts +20 -0
  627. package/dist/templates/default/tailwind.config.ts +7 -0
  628. package/dist/templates/default/tsconfig.json +11 -0
  629. package/dist/templates/default/vite.config.ts +6 -0
  630. package/dist/templates/templates/default/.agents/skills/actions/SKILL.md +142 -0
  631. package/dist/templates/templates/default/.agents/skills/agent-engines/SKILL.md +127 -0
  632. package/dist/templates/templates/default/.agents/skills/capture-learnings/SKILL.md +50 -0
  633. package/dist/templates/templates/default/.agents/skills/create-skill/SKILL.md +167 -0
  634. package/dist/templates/templates/default/.agents/skills/delegate-to-agent/SKILL.md +90 -0
  635. package/dist/templates/templates/default/.agents/skills/frontend-design/SKILL.md +69 -0
  636. package/dist/templates/templates/default/.agents/skills/real-time-collab/SKILL.md +183 -0
  637. package/dist/templates/templates/default/.agents/skills/real-time-sync/SKILL.md +112 -0
  638. package/dist/templates/templates/default/.agents/skills/security/SKILL.md +108 -0
  639. package/dist/templates/templates/default/.agents/skills/self-modifying-code/SKILL.md +79 -0
  640. package/dist/templates/templates/default/.agents/skills/storing-data/SKILL.md +110 -0
  641. package/dist/templates/templates/default/.claude/settings.json +100 -0
  642. package/dist/templates/templates/default/.env.example +5 -0
  643. package/dist/templates/templates/default/.ignore +0 -0
  644. package/dist/templates/templates/default/.prettierrc +5 -0
  645. package/dist/templates/templates/default/AGENTS.md +110 -0
  646. package/dist/templates/templates/default/DEVELOPING.md +117 -0
  647. package/dist/templates/templates/default/_gitignore +37 -0
  648. package/dist/templates/templates/default/actions/hello.ts +20 -0
  649. package/dist/templates/templates/default/actions/navigate.ts +53 -0
  650. package/dist/templates/templates/default/actions/run.ts +2 -0
  651. package/dist/templates/templates/default/actions/view-screen.ts +39 -0
  652. package/dist/templates/templates/default/app/entry.client.tsx +4 -0
  653. package/dist/templates/templates/default/app/entry.server.tsx +56 -0
  654. package/dist/templates/templates/default/app/global.css +95 -0
  655. package/dist/templates/templates/default/app/lib/utils.ts +1 -0
  656. package/dist/templates/templates/default/app/root.tsx +107 -0
  657. package/dist/templates/templates/default/app/routes/_index.tsx +62 -0
  658. package/dist/templates/templates/default/app/routes.ts +4 -0
  659. package/dist/templates/templates/default/app/vite-env.d.ts +6 -0
  660. package/dist/templates/templates/default/components.json +20 -0
  661. package/dist/templates/templates/default/data/.gitkeep +0 -0
  662. package/dist/templates/templates/default/data/sync-config.json +1 -0
  663. package/dist/templates/templates/default/learnings.defaults.md +5 -0
  664. package/dist/templates/templates/default/learnings.md +0 -0
  665. package/dist/templates/templates/default/package.json +46 -0
  666. package/dist/templates/templates/default/postcss.config.js +6 -0
  667. package/dist/templates/templates/default/public/icon-180.svg +4 -0
  668. package/dist/templates/templates/default/public/icon-192.svg +4 -0
  669. package/dist/templates/templates/default/public/icon-512.svg +4 -0
  670. package/dist/templates/templates/default/public/manifest.json +13 -0
  671. package/dist/templates/templates/default/react-router.config.ts +6 -0
  672. package/dist/templates/templates/default/server/middleware/auth.ts +15 -0
  673. package/dist/templates/templates/default/server/plugins/.gitkeep +0 -0
  674. package/dist/templates/templates/default/server/routes/[...page].get.ts +5 -0
  675. package/dist/templates/templates/default/server/routes/api/hello.get.ts +5 -0
  676. package/dist/templates/templates/default/shared/api.ts +6 -0
  677. package/dist/templates/templates/default/ssr-entry.ts +20 -0
  678. package/dist/templates/templates/default/tailwind.config.ts +7 -0
  679. package/dist/templates/templates/default/tsconfig.json +11 -0
  680. package/dist/templates/templates/default/vite.config.ts +6 -0
  681. package/dist/terminal/cli-registry.d.ts +1 -1
  682. package/dist/terminal/cli-registry.d.ts.map +1 -1
  683. package/dist/terminal/cli-registry.js +7 -7
  684. package/dist/terminal/cli-registry.js.map +1 -1
  685. package/dist/terminal/pty-server.d.ts +1 -1
  686. package/dist/terminal/pty-server.d.ts.map +1 -1
  687. package/dist/terminal/pty-server.js +34 -12
  688. package/dist/terminal/pty-server.js.map +1 -1
  689. package/dist/terminal/terminal-plugin.d.ts +0 -9
  690. package/dist/terminal/terminal-plugin.d.ts.map +1 -1
  691. package/dist/terminal/terminal-plugin.js +57 -14
  692. package/dist/terminal/terminal-plugin.js.map +1 -1
  693. package/dist/usage/store.d.ts +29 -0
  694. package/dist/usage/store.d.ts.map +1 -0
  695. package/dist/usage/store.js +102 -0
  696. package/dist/usage/store.js.map +1 -0
  697. package/dist/vite/action-types-plugin.d.ts +13 -0
  698. package/dist/vite/action-types-plugin.d.ts.map +1 -0
  699. package/dist/vite/action-types-plugin.js +132 -0
  700. package/dist/vite/action-types-plugin.js.map +1 -0
  701. package/dist/vite/agents-bundle-plugin.d.ts +3 -0
  702. package/dist/vite/agents-bundle-plugin.d.ts.map +1 -0
  703. package/dist/vite/agents-bundle-plugin.js +87 -0
  704. package/dist/vite/agents-bundle-plugin.js.map +1 -0
  705. package/dist/vite/client.d.ts +5 -0
  706. package/dist/vite/client.d.ts.map +1 -1
  707. package/dist/vite/client.js +222 -37
  708. package/dist/vite/client.js.map +1 -1
  709. package/dist/vite/index.d.ts +2 -1
  710. package/dist/vite/index.d.ts.map +1 -1
  711. package/dist/vite/index.js +2 -1
  712. package/dist/vite/index.js.map +1 -1
  713. package/package.json +68 -20
  714. package/src/templates/default/.agents/skills/actions/SKILL.md +12 -6
  715. package/src/templates/default/.agents/skills/agent-engines/SKILL.md +127 -0
  716. package/src/templates/default/.agents/skills/real-time-collab/SKILL.md +183 -0
  717. package/src/templates/default/.agents/skills/security/SKILL.md +108 -0
  718. package/src/templates/default/.agents/skills/storing-data/SKILL.md +110 -0
  719. package/src/templates/default/.claude/settings.json +13 -0
  720. package/src/templates/default/AGENTS.md +25 -9
  721. package/src/templates/default/actions/view-screen.ts +1 -1
  722. package/src/templates/default/package.json +2 -2
  723. package/src/templates/default/server/middleware/auth.ts +15 -0
  724. package/src/templates/default/server/routes/[...page].get.ts +2 -9
  725. package/src/templates/default/ssr-entry.ts +20 -0
  726. package/dist/adapters/convex/adapter.d.ts +0 -24
  727. package/dist/adapters/convex/adapter.d.ts.map +0 -1
  728. package/dist/adapters/convex/adapter.js +0 -125
  729. package/dist/adapters/convex/adapter.js.map +0 -1
  730. package/dist/adapters/convex/index.d.ts +0 -4
  731. package/dist/adapters/convex/index.d.ts.map +0 -1
  732. package/dist/adapters/convex/index.js +0 -3
  733. package/dist/adapters/convex/index.js.map +0 -1
  734. package/dist/adapters/drizzle/adapter.d.ts +0 -36
  735. package/dist/adapters/drizzle/adapter.d.ts.map +0 -1
  736. package/dist/adapters/drizzle/adapter.js +0 -210
  737. package/dist/adapters/drizzle/adapter.js.map +0 -1
  738. package/dist/adapters/drizzle/index.d.ts +0 -3
  739. package/dist/adapters/drizzle/index.d.ts.map +0 -1
  740. package/dist/adapters/drizzle/index.js +0 -3
  741. package/dist/adapters/drizzle/index.js.map +0 -1
  742. package/dist/adapters/drizzle/schema.d.ts +0 -146
  743. package/dist/adapters/drizzle/schema.d.ts.map +0 -1
  744. package/dist/adapters/drizzle/schema.js +0 -20
  745. package/dist/adapters/drizzle/schema.js.map +0 -1
  746. package/dist/adapters/firestore/adapter.d.ts +0 -48
  747. package/dist/adapters/firestore/adapter.d.ts.map +0 -1
  748. package/dist/adapters/firestore/adapter.js +0 -62
  749. package/dist/adapters/firestore/adapter.js.map +0 -1
  750. package/dist/adapters/firestore/index.d.ts +0 -4
  751. package/dist/adapters/firestore/index.d.ts.map +0 -1
  752. package/dist/adapters/firestore/index.js +0 -3
  753. package/dist/adapters/firestore/index.js.map +0 -1
  754. package/dist/adapters/supabase/adapter.d.ts +0 -43
  755. package/dist/adapters/supabase/adapter.d.ts.map +0 -1
  756. package/dist/adapters/supabase/adapter.js +0 -137
  757. package/dist/adapters/supabase/adapter.js.map +0 -1
  758. package/dist/adapters/supabase/index.d.ts +0 -3
  759. package/dist/adapters/supabase/index.d.ts.map +0 -1
  760. package/dist/adapters/supabase/index.js +0 -3
  761. package/dist/adapters/supabase/index.js.map +0 -1
  762. package/dist/adapters/sync/config.d.ts +0 -40
  763. package/dist/adapters/sync/config.d.ts.map +0 -1
  764. package/dist/adapters/sync/config.js +0 -209
  765. package/dist/adapters/sync/config.js.map +0 -1
  766. package/dist/adapters/sync/create-file-sync.d.ts +0 -32
  767. package/dist/adapters/sync/create-file-sync.d.ts.map +0 -1
  768. package/dist/adapters/sync/create-file-sync.js +0 -218
  769. package/dist/adapters/sync/create-file-sync.js.map +0 -1
  770. package/dist/adapters/sync/file-sync.d.ts +0 -94
  771. package/dist/adapters/sync/file-sync.d.ts.map +0 -1
  772. package/dist/adapters/sync/file-sync.js +0 -671
  773. package/dist/adapters/sync/file-sync.js.map +0 -1
  774. package/dist/adapters/sync/index.d.ts +0 -6
  775. package/dist/adapters/sync/index.d.ts.map +0 -1
  776. package/dist/adapters/sync/index.js +0 -6
  777. package/dist/adapters/sync/index.js.map +0 -1
  778. package/dist/adapters/sync/merge.d.ts +0 -21
  779. package/dist/adapters/sync/merge.d.ts.map +0 -1
  780. package/dist/adapters/sync/merge.js +0 -132
  781. package/dist/adapters/sync/merge.js.map +0 -1
  782. package/dist/adapters/sync/types.d.ts +0 -62
  783. package/dist/adapters/sync/types.d.ts.map +0 -1
  784. package/dist/adapters/sync/types.js +0 -23
  785. package/dist/adapters/sync/types.js.map +0 -1
  786. package/dist/client/harness.d.ts +0 -48
  787. package/dist/client/harness.d.ts.map +0 -1
  788. package/dist/client/harness.js.map +0 -1
  789. package/dist/client/use-file-sync-status.d.ts +0 -21
  790. package/dist/client/use-file-sync-status.d.ts.map +0 -1
  791. package/dist/client/use-file-sync-status.js +0 -65
  792. package/dist/client/use-file-sync-status.js.map +0 -1
  793. package/dist/server/default-watcher.d.ts +0 -23
  794. package/dist/server/default-watcher.d.ts.map +0 -1
  795. package/dist/server/default-watcher.js +0 -57
  796. package/dist/server/default-watcher.js.map +0 -1
  797. package/dist/server/file-sync-plugin.d.ts +0 -7
  798. package/dist/server/file-sync-plugin.d.ts.map +0 -1
  799. package/dist/server/file-sync-plugin.js +0 -38
  800. package/dist/server/file-sync-plugin.js.map +0 -1
  801. package/dist/vite/dev-api-server.d.ts +0 -10
  802. package/dist/vite/dev-api-server.d.ts.map +0 -1
  803. package/dist/vite/dev-api-server.js +0 -243
  804. package/dist/vite/dev-api-server.js.map +0 -1
  805. /package/{src/templates/default/.agents/skills/files-as-database → dist/templates/default/.agents/skills/storing-data}/SKILL.md +0 -0
  806. /package/{src/templates/default/application-state/.gitkeep → dist/templates/default/.ignore} +0 -0
@@ -1,54 +1,102 @@
1
1
  import crypto from "node:crypto";
2
- import { defineEventHandler, readBody, getMethod, getQuery, getRequestIP, setResponseHeader, setResponseStatus, getCookie, setCookie, deleteCookie, } from "h3";
2
+ import path from "node:path";
3
+ // Lazy fs — loaded via dynamic import() on first use.
4
+ // Avoids static require() which crashes on CF Workers.
5
+ let _fs;
6
+ async function getFs() {
7
+ if (!_fs) {
8
+ _fs = await import("node:fs");
9
+ }
10
+ return _fs;
11
+ }
12
+ import { defineEventHandler, getMethod, getQuery, setResponseHeader, setResponseStatus, getCookie, setCookie, deleteCookie, } from "h3";
13
+ // In h3 v2, `event.req` IS the web Request — no conversion needed.
14
+ function toWebRequest(event) {
15
+ return event.req;
16
+ }
3
17
  import { getDbExec, isPostgres, intType } from "../db/client.js";
18
+ import { getBetterAuth, getBetterAuthSync } from "./better-auth-instance.js";
19
+ import { getOnboardingHtml } from "./onboarding-html.js";
20
+ import { migrateLocalUserData } from "./local-migration.js";
21
+ import { readBody } from "../server/h3-helpers.js";
4
22
  // ---------------------------------------------------------------------------
5
23
  // Constants
6
24
  // ---------------------------------------------------------------------------
7
25
  const COOKIE_NAME = "an_session";
8
26
  const DEFAULT_MAX_AGE = 60 * 60 * 24 * 30; // 30 days
9
- const RATE_LIMIT_WINDOW = 15 * 60 * 1000; // 15 minutes
10
- const RATE_LIMIT_MAX = 10; // max attempts per window
11
- const rateLimitMap = new Map();
12
- // Prune stale entries every 5 minutes to prevent unbounded growth
13
- setInterval(() => {
14
- const now = Date.now();
15
- for (const [key, entry] of rateLimitMap) {
16
- if (now > entry.resetAt)
17
- rateLimitMap.delete(key);
27
+ // ---------------------------------------------------------------------------
28
+ // AUTH_MODE detection
29
+ // ---------------------------------------------------------------------------
30
+ /**
31
+ * Check if the app is in local-only mode (no auth).
32
+ *
33
+ * Returns true when:
34
+ * - AUTH_MODE=local is explicitly set (escape hatch)
35
+ * - In dev environment (NODE_ENV=development) with no explicit auth token
36
+ * configured (no ACCESS_TOKEN, no BYOA). This makes dev "just work"
37
+ * without requiring auth setup, while still respecting auth when configured.
38
+ *
39
+ * NOTE: GOOGLE_CLIENT_ID is intentionally NOT checked here — it is used for
40
+ * Google Calendar / Gmail API access as well as Google Sign-In, and its
41
+ * presence alone should not force authentication. Only ACCESS_TOKEN/ACCESS_TOKENS
42
+ * (explicit token-based auth) or a custom getSession (BYOA) signal that the
43
+ * developer has explicitly opted into requiring authentication.
44
+ *
45
+ * BYOA (customGetSession) opts out of dev auto-local — templates that provide
46
+ * their own auth (e.g. Supabase) shouldn't be silently bypassed in dev.
47
+ */
48
+ function isLocalMode() {
49
+ if (process.env.AUTH_MODE === "local")
50
+ return true;
51
+ // Default to local mode in dev when no explicit auth is configured
52
+ if (isDevEnvironment() &&
53
+ !process.env.ACCESS_TOKEN &&
54
+ !process.env.ACCESS_TOKENS &&
55
+ !customGetSession) {
56
+ return true;
18
57
  }
19
- }, 5 * 60 * 1000).unref();
20
- function getClientIp(event) {
21
- return getRequestIP(event, { xForwardedFor: true }) ?? "unknown";
58
+ return false;
22
59
  }
23
60
  /**
24
- * Check rate limit for a given key (typically IP + route).
25
- * Returns null if allowed, or a response object if blocked.
61
+ * Check if we're in a development/test environment.
62
+ * Used for cookie security settings, not for auth bypass.
26
63
  */
27
- function checkRateLimit(event, key) {
28
- const now = Date.now();
29
- const entry = rateLimitMap.get(key);
30
- if (!entry || now > entry.resetAt) {
31
- rateLimitMap.set(key, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
32
- return null;
33
- }
34
- entry.count++;
35
- if (entry.count > RATE_LIMIT_MAX) {
36
- const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
37
- setResponseStatus(event, 429);
38
- setResponseHeader(event, "Retry-After", retryAfter);
39
- return {
40
- error: "Too many attempts. Please try again later.",
41
- retryAfter,
42
- };
64
+ function isDevEnvironment() {
65
+ const env = process.env.NODE_ENV;
66
+ return env === "development" || env === "test";
67
+ }
68
+ // ---------------------------------------------------------------------------
69
+ // ACCESS_TOKEN resolution
70
+ // ---------------------------------------------------------------------------
71
+ function getAccessTokens() {
72
+ const single = process.env.ACCESS_TOKEN;
73
+ const multi = process.env.ACCESS_TOKENS;
74
+ const tokens = [];
75
+ if (single)
76
+ tokens.push(single);
77
+ if (multi) {
78
+ for (const t of multi.split(",")) {
79
+ const trimmed = t.trim();
80
+ if (trimmed && !tokens.includes(trimmed))
81
+ tokens.push(trimmed);
82
+ }
43
83
  }
44
- return null;
84
+ return tokens;
45
85
  }
46
- /** Reset rate limit on successful auth (so valid users aren't penalized). */
47
- function resetRateLimit(key) {
48
- rateLimitMap.delete(key);
86
+ function safeTokenMatch(input, tokens) {
87
+ const inputBuf = Buffer.from(input);
88
+ for (const token of tokens) {
89
+ const tokenBuf = Buffer.from(token);
90
+ if (inputBuf.length === tokenBuf.length &&
91
+ crypto.timingSafeEqual(inputBuf, tokenBuf)) {
92
+ return true;
93
+ }
94
+ }
95
+ return false;
49
96
  }
50
97
  // ---------------------------------------------------------------------------
51
- // Session store — SQL-backed
98
+ // Legacy session store — kept for backward compat (addSession/getSessionEmail)
99
+ // Used by google-oauth.ts for mobile deep linking session creation.
52
100
  // ---------------------------------------------------------------------------
53
101
  let _sessionInitPromise;
54
102
  let sessionMaxAge = DEFAULT_MAX_AGE;
@@ -63,29 +111,19 @@ async function ensureSessionTable() {
63
111
  created_at ${intType()} NOT NULL
64
112
  )
65
113
  `);
66
- // Migration: add email column to existing tables that lack it
67
114
  try {
68
115
  await client.execute(`ALTER TABLE sessions ADD COLUMN email TEXT`);
69
116
  }
70
117
  catch {
71
- // Column already exists — ignore
118
+ // Column already exists
72
119
  }
73
120
  })();
74
121
  }
75
122
  return _sessionInitPromise;
76
123
  }
77
- async function pruneExpiredSessions() {
78
- await ensureSessionTable();
79
- const client = getDbExec();
80
- const cutoff = Date.now() - sessionMaxAge * 1000;
81
- await client.execute({
82
- sql: `DELETE FROM sessions WHERE created_at < ?`,
83
- args: [cutoff],
84
- });
85
- }
86
124
  /**
87
- * Create a new session. Optionally associate it with an email address
88
- * (used by Google OAuth and other identity-aware auth providers).
125
+ * Create a new session in the legacy sessions table.
126
+ * Used by google-oauth.ts for mobile deep linking.
89
127
  */
90
128
  export async function addSession(token, email) {
91
129
  await ensureSessionTable();
@@ -97,7 +135,7 @@ export async function addSession(token, email) {
97
135
  args: [token, email ?? null, Date.now()],
98
136
  });
99
137
  }
100
- /** Remove a session by token. */
138
+ /** Remove a session from the legacy sessions table. */
101
139
  export async function removeSession(token) {
102
140
  await ensureSessionTable();
103
141
  const client = getDbExec();
@@ -107,7 +145,7 @@ export async function removeSession(token) {
107
145
  });
108
146
  }
109
147
  /**
110
- * Look up the email associated with a session token.
148
+ * Look up the email associated with a legacy session token.
111
149
  * Returns null if the session doesn't exist, is expired, or has no email.
112
150
  */
113
151
  export async function getSessionEmail(token) {
@@ -129,71 +167,111 @@ export async function getSessionEmail(token) {
129
167
  }
130
168
  return rows[0].email ?? null;
131
169
  }
132
- async function hasSession(token) {
133
- await ensureSessionTable();
134
- const client = getDbExec();
135
- const { rows } = await client.execute({
136
- sql: `SELECT created_at FROM sessions WHERE token = ?`,
137
- args: [token],
138
- });
139
- if (rows.length === 0)
140
- return false;
141
- const createdAt = rows[0].created_at;
142
- if (Date.now() - createdAt > sessionMaxAge * 1000) {
143
- await client.execute({
144
- sql: `DELETE FROM sessions WHERE token = ?`,
145
- args: [token],
146
- });
147
- return false;
148
- }
149
- return true;
150
- }
151
170
  // ---------------------------------------------------------------------------
152
- // Token resolution supports ACCESS_TOKEN (single) or ACCESS_TOKENS (multi)
171
+ // getSessionthe auth contract
153
172
  // ---------------------------------------------------------------------------
154
- function getAccessTokens() {
155
- const single = process.env.ACCESS_TOKEN;
156
- const multi = process.env.ACCESS_TOKENS;
157
- const tokens = [];
158
- if (single)
159
- tokens.push(single);
160
- if (multi) {
161
- for (const t of multi.split(",")) {
162
- const trimmed = t.trim();
163
- if (trimmed && !tokens.includes(trimmed))
164
- tokens.push(trimmed);
165
- }
166
- }
167
- return tokens;
173
+ let customGetSession = null;
174
+ let authDisabledMode = false;
175
+ let _authGuardConfig = null;
176
+ /**
177
+ * Module-level auth guard function. Set by autoMountAuth() when auth is active.
178
+ * Called by the server middleware to enforce auth on ALL requests (not just
179
+ * /_agent-native/* routes).
180
+ */
181
+ let _authGuardFn = null;
182
+ /**
183
+ * Run the auth guard on an event. Returns a Response/object to block the
184
+ * request (login page or 401), or undefined to allow it through.
185
+ *
186
+ * Called by the default server middleware (server/middleware/auth.ts) to
187
+ * enforce auth on page routes and API routes — not just framework routes.
188
+ */
189
+ export async function runAuthGuard(event) {
190
+ if (!_authGuardFn)
191
+ return; // Auth not mounted (local mode, etc.)
192
+ return _authGuardFn(event);
168
193
  }
194
+ const LOCAL_SESSION = { email: "local@localhost" };
169
195
  // ---------------------------------------------------------------------------
170
- // Dev mode detection
196
+ // Auth guard factory
171
197
  // ---------------------------------------------------------------------------
172
- function isDevMode() {
173
- // On edge runtimes (e.g. CF Workers), NODE_ENV may not be set.
174
- // Treat undefined as production dev mode must be explicitly opted in.
175
- const env = process.env.NODE_ENV;
176
- return env === "development" || env === "test";
198
+ /**
199
+ * Create an auth guard function that checks session and blocks
200
+ * unauthenticated requests. Returns the login HTML for page routes
201
+ * or a 401 JSON response for API routes.
202
+ *
203
+ * Reads loginHtml and publicPaths from _authGuardConfig on every request
204
+ * so that a custom plugin can update them after the default has already
205
+ * installed this middleware (the production race condition fix).
206
+ */
207
+ function createAuthGuardFn() {
208
+ return async (event) => {
209
+ const config = _authGuardConfig;
210
+ if (!config)
211
+ return;
212
+ const { loginHtml, publicPaths } = config;
213
+ const url = event.node?.req?.url ?? event.path ?? "/";
214
+ const p = url.split("?")[0];
215
+ // Skip auth routes (all /_agent-native/auth/* and /_agent-native/google/*)
216
+ if (p.startsWith("/_agent-native/auth/") ||
217
+ p.startsWith("/_agent-native/google/")) {
218
+ return;
219
+ }
220
+ // Skip static assets (Vite chunks, fonts, images, etc.)
221
+ if (p.startsWith("/assets/") ||
222
+ p.startsWith("/_build/") ||
223
+ p.endsWith(".js") ||
224
+ p.endsWith(".css") ||
225
+ p.endsWith(".map") ||
226
+ p.endsWith(".ico") ||
227
+ p.endsWith(".png") ||
228
+ p.endsWith(".svg") ||
229
+ p.endsWith(".woff2") ||
230
+ p.endsWith(".woff")) {
231
+ return;
232
+ }
233
+ if (isPublicPath(url, publicPaths))
234
+ return;
235
+ const session = await getSession(event);
236
+ if (session)
237
+ return;
238
+ if (p.startsWith("/api/") || p.startsWith("/_agent-native/")) {
239
+ setResponseStatus(event, 401);
240
+ return { error: "Unauthorized" };
241
+ }
242
+ return new Response(loginHtml, {
243
+ status: 200,
244
+ headers: { "Content-Type": "text/html; charset=utf-8" },
245
+ });
246
+ };
247
+ }
248
+ /**
249
+ * Map a Better Auth session to our AuthSession type.
250
+ */
251
+ function mapBetterAuthSession(baSession) {
252
+ return {
253
+ email: baSession.user.email,
254
+ userId: baSession.user.id,
255
+ token: baSession.session?.token,
256
+ orgId: baSession.session?.activeOrganizationId ?? undefined,
257
+ };
177
258
  }
178
- // ---------------------------------------------------------------------------
179
- // getSession — the auth contract
180
- // ---------------------------------------------------------------------------
181
- let customGetSession = null;
182
- let authDisabledMode = false;
183
- const DEV_SESSION = { email: "local@localhost" };
184
259
  /**
185
260
  * Get the current auth session for a request.
186
261
  *
187
- * - In dev mode: checks for a session cookie first (e.g. from Google OAuth),
188
- * so the real email is used when sharing a DB with production.
189
- * Falls back to { email: "local@localhost" } if no session cookie.
190
- * - In production with built-in auth: returns session if cookie is valid
191
- * - With custom auth (BYOA): delegates to the custom getSession
262
+ * Resolution chain:
263
+ * 1. AUTH_MODE=local local@localhost (explicit escape hatch)
264
+ * 2. AUTH_DISABLED=true local@localhost (infrastructure auth)
265
+ * 3. ACCESS_TOKEN check legacy cookie-based token sessions
266
+ * 4. BYOA custom getSession delegate to template callback
267
+ * 5. Better Auth → check session via Better Auth API (cookie or Bearer)
268
+ * 6. Legacy cookie → check an_session cookie in legacy sessions table
269
+ * 7. Mobile _session query param → promote to cookie
192
270
  */
193
271
  export async function getSession(event) {
194
- if (isDevMode() || authDisabledMode) {
195
- // Check for a real session cookie (created by Google OAuth callback)
196
- // so dev and prod share the same identity on the same DB
272
+ // 1. AUTH_MODE=local explicit local-only mode
273
+ if (isLocalMode() || authDisabledMode) {
274
+ // Check for a real session cookie first (e.g. from Google OAuth)
197
275
  try {
198
276
  const cookie = getCookie(event, COOKIE_NAME);
199
277
  if (cookie) {
@@ -203,17 +281,59 @@ export async function getSession(event) {
203
281
  }
204
282
  }
205
283
  catch {
206
- // DB not ready yet — fall back to dev session
284
+ // DB not ready yet
285
+ }
286
+ // Also try Better Auth session (for users who created an account then went local)
287
+ try {
288
+ const ba = getBetterAuthSync();
289
+ if (ba) {
290
+ const baSession = await ba.api.getSession({
291
+ headers: event.headers,
292
+ });
293
+ if (baSession?.user?.email) {
294
+ return mapBetterAuthSession(baSession);
295
+ }
296
+ }
207
297
  }
208
- return DEV_SESSION;
298
+ catch {
299
+ // Better Auth not initialized yet
300
+ }
301
+ return LOCAL_SESSION;
209
302
  }
303
+ // 2. ACCESS_TOKEN check (programmatic/agent access)
304
+ const accessTokens = getAccessTokens();
305
+ if (accessTokens.length > 0) {
306
+ const cookie = getCookie(event, COOKIE_NAME);
307
+ if (cookie) {
308
+ const email = await getSessionEmail(cookie);
309
+ if (email)
310
+ return { email, token: cookie };
311
+ }
312
+ }
313
+ // 3. BYOA custom getSession
210
314
  if (customGetSession) {
211
315
  const session = await customGetSession(event);
212
316
  if (session)
213
317
  return session;
214
- // Fall through to _session query param check (mobile WebView bridge)
318
+ // Fall through to mobile _session check
215
319
  }
216
320
  else {
321
+ // 4. Better Auth session (cookie or Bearer token)
322
+ try {
323
+ const ba = getBetterAuthSync();
324
+ if (ba) {
325
+ const baSession = await ba.api.getSession({
326
+ headers: event.headers,
327
+ });
328
+ if (baSession?.user?.email) {
329
+ return mapBetterAuthSession(baSession);
330
+ }
331
+ }
332
+ }
333
+ catch {
334
+ // Better Auth not ready
335
+ }
336
+ // 5. Legacy cookie fallback (for sessions created before migration)
217
337
  const cookie = getCookie(event, COOKIE_NAME);
218
338
  if (cookie) {
219
339
  const email = await getSessionEmail(cookie);
@@ -221,141 +341,35 @@ export async function getSession(event) {
221
341
  return { email, token: cookie };
222
342
  }
223
343
  }
224
- // Mobile WebViews have a separate cookie jar from Safari, so after OAuth
225
- // completes in Safari the WebView won't have the session cookie. The mobile
226
- // app passes the token as a query parameter; if it's valid we promote it to
227
- // an httpOnly cookie so subsequent requests work normally.
228
- // This MUST run even with custom auth providers (e.g. createGoogleAuthPlugin).
344
+ // 6. Mobile WebView bridge _session query param
229
345
  const qToken = getQuery(event)?._session;
230
346
  if (qToken) {
231
347
  const email = await getSessionEmail(qToken);
232
348
  if (email) {
233
349
  setCookie(event, COOKIE_NAME, qToken, {
234
350
  httpOnly: true,
235
- secure: process.env.NODE_ENV === "production",
351
+ secure: !isDevEnvironment(),
236
352
  sameSite: "lax",
237
353
  path: "/",
238
354
  maxAge: sessionMaxAge,
239
355
  });
356
+ setResponseHeader(event, "Referrer-Policy", "no-referrer");
240
357
  return { email, token: qToken };
241
358
  }
242
359
  }
243
360
  return null;
244
361
  }
245
362
  // ---------------------------------------------------------------------------
246
- // Constant-time token comparison
247
- // ---------------------------------------------------------------------------
248
- function safeTokenMatch(input, tokens) {
249
- const inputBuf = Buffer.from(input);
250
- for (const token of tokens) {
251
- const tokenBuf = Buffer.from(token);
252
- if (inputBuf.length === tokenBuf.length &&
253
- crypto.timingSafeEqual(inputBuf, tokenBuf)) {
254
- return true;
255
- }
256
- }
257
- return false;
258
- }
259
- // ---------------------------------------------------------------------------
260
- // Password hashing — Web Crypto PBKDF2 (works on Node.js + CF Workers)
261
- // ---------------------------------------------------------------------------
262
- const PBKDF2_ITERATIONS = 100_000;
263
- function toHex(buf) {
264
- return Array.from(buf)
265
- .map((b) => b.toString(16).padStart(2, "0"))
266
- .join("");
267
- }
268
- function fromHex(hex) {
269
- const bytes = new Uint8Array(hex.length / 2);
270
- for (let i = 0; i < hex.length; i += 2) {
271
- bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
272
- }
273
- return bytes;
274
- }
275
- async function hashPassword(password) {
276
- const salt = crypto.getRandomValues(new Uint8Array(16));
277
- const encoded = new TextEncoder().encode(password);
278
- const keyMaterial = await globalThis.crypto.subtle.importKey("raw", encoded.buffer, "PBKDF2", false, ["deriveBits"]);
279
- const derived = await globalThis.crypto.subtle.deriveBits({
280
- name: "PBKDF2",
281
- salt: salt.buffer,
282
- iterations: PBKDF2_ITERATIONS,
283
- hash: "SHA-256",
284
- }, keyMaterial, 256);
285
- return `${PBKDF2_ITERATIONS}:${toHex(salt)}:${toHex(new Uint8Array(derived))}`;
286
- }
287
- async function verifyPassword(password, stored) {
288
- const [iterStr, saltHex, hashHex] = stored.split(":");
289
- const iterations = parseInt(iterStr, 10);
290
- const salt = fromHex(saltHex);
291
- const expectedHash = fromHex(hashHex);
292
- const encoded = new TextEncoder().encode(password);
293
- const keyMaterial = await globalThis.crypto.subtle.importKey("raw", encoded.buffer, "PBKDF2", false, ["deriveBits"]);
294
- const derived = new Uint8Array(await globalThis.crypto.subtle.deriveBits({
295
- name: "PBKDF2",
296
- salt: salt.buffer,
297
- iterations,
298
- hash: "SHA-256",
299
- }, keyMaterial, 256));
300
- if (derived.length !== expectedHash.length)
301
- return false;
302
- // Constant-time comparison
303
- let diff = 0;
304
- for (let i = 0; i < derived.length; i++) {
305
- diff |= derived[i] ^ expectedHash[i];
306
- }
307
- return diff === 0;
308
- }
309
- // ---------------------------------------------------------------------------
310
- // Users table — email/password accounts
363
+ // Public path matching
311
364
  // ---------------------------------------------------------------------------
312
- let _usersTableReady = false;
313
- async function ensureUsersTable() {
314
- if (_usersTableReady)
315
- return;
316
- const client = getDbExec();
317
- await client.execute(`
318
- CREATE TABLE IF NOT EXISTS users (
319
- email TEXT PRIMARY KEY,
320
- password_hash TEXT NOT NULL,
321
- created_at ${intType()} NOT NULL
322
- )
323
- `);
324
- _usersTableReady = true;
325
- }
326
- async function createUser(email, password) {
327
- await ensureUsersTable();
328
- const client = getDbExec();
329
- // Check if user already exists
330
- const { rows } = await client.execute({
331
- sql: `SELECT email FROM users WHERE email = ?`,
332
- args: [email],
333
- });
334
- if (rows.length > 0) {
335
- return { ok: false, error: "An account with this email already exists" };
336
- }
337
- const passwordHash = await hashPassword(password);
338
- await client.execute({
339
- sql: `INSERT INTO users (email, password_hash, created_at) VALUES (?, ?, ?)`,
340
- args: [email, passwordHash, Date.now()],
341
- });
342
- return { ok: true };
343
- }
344
- async function authenticateUser(email, password) {
345
- await ensureUsersTable();
346
- const client = getDbExec();
347
- const { rows } = await client.execute({
348
- sql: `SELECT password_hash FROM users WHERE email = ?`,
349
- args: [email],
350
- });
351
- if (rows.length === 0)
352
- return false;
353
- return verifyPassword(password, rows[0].password_hash);
365
+ function isPublicPath(url, publicPaths) {
366
+ const p = url.split("?")[0];
367
+ return publicPaths.some((pp) => p === pp || p.startsWith(pp + "/"));
354
368
  }
355
369
  // ---------------------------------------------------------------------------
356
- // Login page HTML
370
+ // Login page HTML (ACCESS_TOKEN mode)
357
371
  // ---------------------------------------------------------------------------
358
- const LOGIN_HTML = `<!DOCTYPE html>
372
+ const TOKEN_LOGIN_HTML = `<!DOCTYPE html>
359
373
  <html lang="en">
360
374
  <head>
361
375
  <meta charset="UTF-8">
@@ -391,7 +405,6 @@ const LOGIN_HTML = `<!DOCTYPE html>
391
405
  color: #e5e5e5;
392
406
  font-size: 0.9375rem;
393
407
  outline: none;
394
- transition: border-color 0.15s;
395
408
  }
396
409
  input:focus { border-color: rgba(255,255,255,0.3); }
397
410
  button {
@@ -405,7 +418,6 @@ const LOGIN_HTML = `<!DOCTYPE html>
405
418
  font-size: 0.9375rem;
406
419
  font-weight: 500;
407
420
  cursor: pointer;
408
- transition: opacity 0.15s;
409
421
  }
410
422
  button:hover { opacity: 0.85; }
411
423
  .error { margin-top: 0.75rem; font-size: 0.8125rem; color: #f87171; display: none; }
@@ -441,241 +453,127 @@ const LOGIN_HTML = `<!DOCTYPE html>
441
453
  </body>
442
454
  </html>`;
443
455
  // ---------------------------------------------------------------------------
444
- // Email/password auth HTML combined login + register page
456
+ // setAuthModeLocal write AUTH_MODE=local to .env for the escape hatch
445
457
  // ---------------------------------------------------------------------------
446
- const EMAIL_AUTH_HTML = `<!DOCTYPE html>
447
- <html lang="en">
448
- <head>
449
- <meta charset="UTF-8">
450
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
451
- <title>Sign in</title>
452
- <style>
453
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
454
- body {
455
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
456
- background: #0a0a0a;
457
- color: #e5e5e5;
458
- display: flex;
459
- align-items: center;
460
- justify-content: center;
461
- min-height: 100vh;
462
- }
463
- .card {
464
- width: 100%;
465
- max-width: 380px;
466
- padding: 2rem;
467
- background: #141414;
468
- border: 1px solid rgba(255,255,255,0.08);
469
- border-radius: 12px;
470
- }
471
- .tabs {
472
- display: inline-flex;
473
- width: 100%;
474
- padding: 4px;
475
- margin-bottom: 1.5rem;
476
- background: rgba(255,255,255,0.06);
477
- border-radius: 8px;
478
- }
479
- .tab {
480
- flex: 1;
481
- padding: 0.5rem 0.75rem;
482
- background: none;
483
- border: none;
484
- color: #888;
485
- font-size: 0.8125rem;
486
- font-weight: 500;
487
- cursor: pointer;
488
- border-radius: 6px;
489
- }
490
- .tab.active {
491
- background: #1e1e1e;
492
- color: #fff;
493
- box-shadow: 0 1px 2px rgba(0,0,0,0.3);
494
- }
495
- .tab:hover:not(.active) { color: #bbb; }
496
- .form { display: none; }
497
- .form.active { display: block; }
498
- label { display: block; font-size: 0.8125rem; color: #888; margin-bottom: 0.375rem; }
499
- input {
500
- width: 100%;
501
- padding: 0.5rem 0.75rem;
502
- background: transparent;
503
- border: 1px solid rgba(255,255,255,0.12);
504
- border-radius: 6px;
505
- color: #e5e5e5;
506
- font-size: 0.875rem;
507
- outline: none;
508
- margin-bottom: 0.875rem;
509
- }
510
- input:focus { border-color: rgba(255,255,255,0.3); box-shadow: 0 0 0 1px rgba(255,255,255,0.1); }
511
- input::placeholder { color: #555; }
512
- button[type="submit"] {
513
- width: 100%;
514
- margin-top: 0.25rem;
515
- padding: 0.5rem;
516
- background: #fff;
517
- color: #000;
518
- border: none;
519
- border-radius: 6px;
520
- font-size: 0.875rem;
521
- font-weight: 500;
522
- cursor: pointer;
523
- }
524
- button[type="submit"]:hover { background: #e5e5e5; }
525
- button[type="submit"]:disabled { opacity: 0.5; cursor: not-allowed; }
526
- .msg { margin-top: 0.75rem; font-size: 0.8125rem; display: none; }
527
- .msg.error { color: #f87171; }
528
- .msg.success { color: #4ade80; }
529
- .msg.show { display: block; }
530
- </style>
531
- </head>
532
- <body>
533
- <div class="card">
534
- <div class="tabs">
535
- <button class="tab active" data-tab="login">Sign in</button>
536
- <button class="tab" data-tab="register">Create account</button>
537
- </div>
538
- <form id="login-form" class="form active">
539
- <label for="l-email">Email</label>
540
- <input id="l-email" type="email" autocomplete="email" autofocus placeholder="you@example.com" required />
541
- <label for="l-pass">Password</label>
542
- <input id="l-pass" type="password" autocomplete="current-password" placeholder="Enter password" required />
543
- <button type="submit">Sign in</button>
544
- <p class="msg error" id="l-err"></p>
545
- </form>
546
- <form id="register-form" class="form">
547
- <label for="r-email">Email</label>
548
- <input id="r-email" type="email" autocomplete="email" placeholder="you@example.com" required />
549
- <label for="r-pass">Password</label>
550
- <input id="r-pass" type="password" autocomplete="new-password" placeholder="At least 8 characters" required minlength="8" />
551
- <label for="r-pass2">Confirm password</label>
552
- <input id="r-pass2" type="password" autocomplete="new-password" placeholder="Confirm password" required minlength="8" />
553
- <button type="submit">Create account</button>
554
- <p class="msg" id="r-msg"></p>
555
- </form>
556
- </div>
557
- <script>
558
- const tabs = document.querySelectorAll('.tab');
559
- const forms = document.querySelectorAll('.form');
560
- tabs.forEach(t => t.addEventListener('click', () => {
561
- tabs.forEach(x => x.classList.remove('active'));
562
- forms.forEach(x => x.classList.remove('active'));
563
- t.classList.add('active');
564
- document.getElementById(t.dataset.tab + '-form').classList.add('active');
565
- }));
566
-
567
- document.getElementById('login-form').addEventListener('submit', async (e) => {
568
- e.preventDefault();
569
- const err = document.getElementById('l-err');
570
- err.classList.remove('show');
571
- const res = await fetch('/_agent-native/auth/login', {
572
- method: 'POST',
573
- headers: { 'Content-Type': 'application/json' },
574
- body: JSON.stringify({
575
- email: document.getElementById('l-email').value,
576
- password: document.getElementById('l-pass').value,
577
- }),
578
- });
579
- if (res.ok) {
580
- window.location.reload();
581
- } else {
582
- const data = await res.json().catch(() => ({}));
583
- err.textContent = data.error || 'Invalid email or password';
584
- err.classList.add('show');
458
+ async function setAuthModeLocal() {
459
+ try {
460
+ const fs = await getFs();
461
+ const envPath = path.resolve(process.cwd(), ".env");
462
+ let content = "";
463
+ try {
464
+ content = fs.readFileSync(envPath, "utf-8");
465
+ }
466
+ catch {
467
+ // .env doesn't exist yet
468
+ }
469
+ if (content.includes("AUTH_MODE=")) {
470
+ content = content.replace(/AUTH_MODE=.*/g, "AUTH_MODE=local");
471
+ }
472
+ else {
473
+ content = content.trimEnd() + "\nAUTH_MODE=local\n";
474
+ }
475
+ fs.writeFileSync(envPath, content, "utf-8");
476
+ process.env.AUTH_MODE = "local";
477
+ return true;
585
478
  }
586
- });
587
-
588
- document.getElementById('register-form').addEventListener('submit', async (e) => {
589
- e.preventDefault();
590
- const msg = document.getElementById('r-msg');
591
- msg.classList.remove('show', 'error', 'success');
592
- const pass = document.getElementById('r-pass').value;
593
- const pass2 = document.getElementById('r-pass2').value;
594
- if (pass !== pass2) {
595
- msg.textContent = 'Passwords do not match';
596
- msg.classList.add('show', 'error');
597
- return;
479
+ catch {
480
+ return false;
598
481
  }
599
- const res = await fetch('/_agent-native/auth/register', {
600
- method: 'POST',
601
- headers: { 'Content-Type': 'application/json' },
602
- body: JSON.stringify({
603
- email: document.getElementById('r-email').value,
604
- password: pass,
605
- }),
606
- });
607
- const data = await res.json().catch(() => ({}));
608
- if (res.ok) {
609
- msg.textContent = 'Account created signing you in...';
610
- msg.classList.add('show', 'success');
611
- // Auto-login after registration
612
- const loginRes = await fetch('/_agent-native/auth/login', {
613
- method: 'POST',
614
- headers: { 'Content-Type': 'application/json' },
615
- body: JSON.stringify({
616
- email: document.getElementById('r-email').value,
617
- password: pass,
618
- }),
619
- });
620
- if (loginRes.ok) {
621
- window.location.reload();
622
- }
623
- } else {
624
- msg.textContent = data.error || 'Registration failed';
625
- msg.classList.add('show', 'error');
482
+ }
483
+ async function removeAuthModeLocal() {
484
+ try {
485
+ const fs = await getFs();
486
+ const envPath = path.resolve(process.cwd(), ".env");
487
+ let content = "";
488
+ try {
489
+ content = fs.readFileSync(envPath, "utf-8");
490
+ }
491
+ catch {
492
+ return true; // No .env file means nothing to remove
493
+ }
494
+ // Remove AUTH_MODE=local line entirely
495
+ content = content
496
+ .split("\n")
497
+ .filter((line) => !line.match(/^\s*AUTH_MODE\s*=/))
498
+ .join("\n");
499
+ fs.writeFileSync(envPath, content, "utf-8");
500
+ delete process.env.AUTH_MODE;
501
+ return true;
626
502
  }
627
- });
628
- </script>
629
- </body>
630
- </html>`;
503
+ catch {
504
+ return false;
505
+ }
506
+ }
631
507
  // ---------------------------------------------------------------------------
632
- // mountEmailAuthRoutesemail/password registration + login
508
+ // mountBetterAuthRoutesBetter Auth powered auth with backward-compat routes
633
509
  // ---------------------------------------------------------------------------
634
- function mountEmailAuthRoutes(app, publicPaths = []) {
635
- // Also support ACCESS_TOKEN login for backward compat (API callers, scripts)
510
+ async function mountBetterAuthRoutes(app, options) {
511
+ const publicPaths = [...(options.publicPaths ?? [])];
512
+ // The A2A agent card is part of an open protocol — other agents must be
513
+ // able to discover it without auth. Same for favicons and similar probes.
514
+ for (const pp of ["/.well-known", "/favicon.ico", "/favicon.png"]) {
515
+ if (!publicPaths.includes(pp))
516
+ publicPaths.push(pp);
517
+ }
518
+ // Auto-add Google OAuth routes when credentials are configured
519
+ if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
520
+ for (const gp of [
521
+ "/_agent-native/google/callback",
522
+ "/_agent-native/google/auth-url",
523
+ ]) {
524
+ if (!publicPaths.includes(gp))
525
+ publicPaths.push(gp);
526
+ }
527
+ }
636
528
  const accessTokens = getAccessTokens();
637
- // POST /_agent-native/auth/register
638
- app.use("/_agent-native/auth/register", defineEventHandler(async (event) => {
529
+ // Initialize Better Auth
530
+ const auth = await getBetterAuth(options.betterAuth);
531
+ // Mount Better Auth catch-all handler at /_agent-native/auth/ba/*
532
+ app.use("/_agent-native/auth/ba", defineEventHandler(async (event) => {
533
+ const response = await auth.handler(toWebRequest(event));
534
+ return response;
535
+ }));
536
+ // POST /_agent-native/auth/local-mode — switch to local mode (onboarding escape hatch)
537
+ // Only available in dev — production requires real accounts for usage tracking.
538
+ app.use("/_agent-native/auth/local-mode", defineEventHandler(async (event) => {
639
539
  if (getMethod(event) !== "POST") {
640
540
  setResponseStatus(event, 405);
641
541
  return { error: "Method not allowed" };
642
542
  }
643
- const ip = getClientIp(event);
644
- const limited = checkRateLimit(event, `register:${ip}`);
645
- if (limited)
646
- return limited;
647
- const body = await readBody(event);
648
- const email = body?.email?.trim?.()?.toLowerCase?.();
649
- const password = body?.password;
650
- if (!email || typeof email !== "string" || !email.includes("@")) {
651
- setResponseStatus(event, 400);
652
- return { error: "Valid email is required" };
543
+ if (!isDevEnvironment()) {
544
+ setResponseStatus(event, 403);
545
+ return {
546
+ error: "Local mode is not available in production. Create an account to continue.",
547
+ };
653
548
  }
654
- if (!password || typeof password !== "string" || password.length < 8) {
655
- setResponseStatus(event, 400);
656
- return { error: "Password must be at least 8 characters" };
549
+ const ok = await setAuthModeLocal();
550
+ if (!ok) {
551
+ setResponseStatus(event, 500);
552
+ return { error: "Failed to set AUTH_MODE=local in .env" };
657
553
  }
658
- const result = await createUser(email, password);
659
- if (!result.ok) {
660
- setResponseStatus(event, 409);
661
- return { error: result.error };
554
+ return { ok: true };
555
+ }));
556
+ // POST /_agent-native/auth/exit-local-mode — switch back to real auth
557
+ app.use("/_agent-native/auth/exit-local-mode", defineEventHandler(async (event) => {
558
+ if (getMethod(event) !== "POST") {
559
+ setResponseStatus(event, 405);
560
+ return { error: "Method not allowed" };
561
+ }
562
+ const ok = await removeAuthModeLocal();
563
+ if (!ok) {
564
+ setResponseStatus(event, 500);
565
+ return { error: "Failed to remove AUTH_MODE from .env" };
662
566
  }
663
- resetRateLimit(`register:${ip}`);
664
567
  return { ok: true };
665
568
  }));
666
- // POST /_agent-native/auth/login — email/password or legacy ACCESS_TOKEN
569
+ // Backward-compat: POST /_agent-native/auth/login
667
570
  app.use("/_agent-native/auth/login", defineEventHandler(async (event) => {
668
571
  if (getMethod(event) !== "POST") {
669
572
  setResponseStatus(event, 405);
670
573
  return { error: "Method not allowed" };
671
574
  }
672
- const ip = getClientIp(event);
673
- const rateLimitKey = `login:${ip}`;
674
- const limited = checkRateLimit(event, rateLimitKey);
675
- if (limited)
676
- return limited;
677
575
  const body = await readBody(event);
678
- // Legacy: ACCESS_TOKEN login (for API callers, scripts)
576
+ // Legacy ACCESS_TOKEN login
679
577
  if (body?.token &&
680
578
  typeof body.token === "string" &&
681
579
  accessTokens.length > 0) {
@@ -687,44 +585,81 @@ function mountEmailAuthRoutes(app, publicPaths = []) {
687
585
  await addSession(sessionToken, "user");
688
586
  setCookie(event, COOKIE_NAME, sessionToken, {
689
587
  httpOnly: true,
690
- secure: process.env.NODE_ENV === "production",
588
+ secure: !isDevEnvironment(),
691
589
  sameSite: "lax",
692
590
  path: "/",
693
591
  maxAge: sessionMaxAge,
694
592
  });
695
- resetRateLimit(rateLimitKey);
696
593
  return { ok: true };
697
594
  }
698
- // Email/password login
595
+ // Email/password login via Better Auth
699
596
  const email = body?.email?.trim?.()?.toLowerCase?.();
700
597
  const password = body?.password;
701
598
  if (!email || !password) {
702
599
  setResponseStatus(event, 400);
703
600
  return { error: "Email and password are required" };
704
601
  }
705
- const valid = await authenticateUser(email, password);
706
- if (!valid) {
602
+ try {
603
+ const result = await auth.api.signInEmail({
604
+ body: { email, password },
605
+ });
606
+ if (result?.token) {
607
+ setCookie(event, COOKIE_NAME, result.token, {
608
+ httpOnly: true,
609
+ secure: !isDevEnvironment(),
610
+ sameSite: "lax",
611
+ path: "/",
612
+ maxAge: sessionMaxAge,
613
+ });
614
+ await addSession(result.token, email);
615
+ }
616
+ return { ok: true };
617
+ }
618
+ catch (e) {
707
619
  setResponseStatus(event, 401);
708
- return { error: "Invalid email or password" };
620
+ return { error: e?.message || "Invalid email or password" };
709
621
  }
710
- const sessionToken = crypto.randomBytes(32).toString("hex");
711
- await addSession(sessionToken, email);
712
- setCookie(event, COOKIE_NAME, sessionToken, {
713
- httpOnly: true,
714
- secure: process.env.NODE_ENV === "production",
715
- sameSite: "lax",
716
- path: "/",
717
- maxAge: sessionMaxAge,
718
- });
719
- resetRateLimit(rateLimitKey);
720
- return { ok: true };
721
622
  }));
722
- // POST /_agent-native/auth/logout
623
+ // Backward-compat: POST /_agent-native/auth/register
624
+ app.use("/_agent-native/auth/register", defineEventHandler(async (event) => {
625
+ if (getMethod(event) !== "POST") {
626
+ setResponseStatus(event, 405);
627
+ return { error: "Method not allowed" };
628
+ }
629
+ const body = await readBody(event);
630
+ const email = body?.email?.trim?.()?.toLowerCase?.();
631
+ const password = body?.password;
632
+ if (!email || typeof email !== "string" || !email.includes("@")) {
633
+ setResponseStatus(event, 400);
634
+ return { error: "Valid email is required" };
635
+ }
636
+ if (!password || typeof password !== "string" || password.length < 8) {
637
+ setResponseStatus(event, 400);
638
+ return { error: "Password must be at least 8 characters" };
639
+ }
640
+ try {
641
+ await auth.api.signUpEmail({
642
+ body: { email, password, name: email.split("@")[0] },
643
+ });
644
+ return { ok: true };
645
+ }
646
+ catch (e) {
647
+ setResponseStatus(event, 409);
648
+ return { error: e?.message || "Registration failed" };
649
+ }
650
+ }));
651
+ // Backward-compat: POST /_agent-native/auth/logout
723
652
  app.use("/_agent-native/auth/logout", defineEventHandler(async (event) => {
724
653
  const cookie = getCookie(event, COOKIE_NAME);
725
654
  if (cookie)
726
655
  await removeSession(cookie);
727
656
  deleteCookie(event, COOKIE_NAME, { path: "/" });
657
+ try {
658
+ await auth.api.signOut({ headers: event.headers });
659
+ }
660
+ catch {
661
+ // Ignore if no Better Auth session
662
+ }
728
663
  return { ok: true };
729
664
  }));
730
665
  // GET /_agent-native/auth/session
@@ -736,60 +671,45 @@ function mountEmailAuthRoutes(app, publicPaths = []) {
736
671
  const session = await getSession(event);
737
672
  return session ?? { error: "Not authenticated" };
738
673
  }));
739
- // Auth guard
740
- const loginHtml = EMAIL_AUTH_HTML;
741
- app.use(defineEventHandler(async (event) => {
742
- const url = event.node?.req?.url ?? event.path ?? "/";
743
- const p = url.split("?")[0];
744
- if (p === "/_agent-native/auth/login" ||
745
- p === "/_agent-native/auth/logout" ||
746
- p === "/_agent-native/auth/session" ||
747
- p === "/_agent-native/auth/register") {
748
- return;
674
+ // POST /_agent-native/auth/migrate-local-data — move local-mode data to
675
+ // the currently signed-in account. Called by the UI after a user upgrades
676
+ // from local mode to a real account so they don't lose their data.
677
+ app.use("/_agent-native/auth/migrate-local-data", defineEventHandler(async (event) => {
678
+ if (getMethod(event) !== "POST") {
679
+ setResponseStatus(event, 405);
680
+ return { error: "Method not allowed" };
749
681
  }
750
- if (isPublicPath(url, publicPaths))
751
- return;
752
682
  const session = await getSession(event);
753
- if (session)
754
- return;
755
- if (p.startsWith("/api/") || p.startsWith("/_agent-native/")) {
683
+ if (!session?.email || session.email === "local@localhost") {
756
684
  setResponseStatus(event, 401);
757
- return { error: "Unauthorized" };
685
+ return { error: "Not authenticated as a real account" };
686
+ }
687
+ try {
688
+ const result = await migrateLocalUserData(session.email);
689
+ return { ok: true, ...result };
690
+ }
691
+ catch (e) {
692
+ setResponseStatus(event, 500);
693
+ return { error: e?.message || "Migration failed" };
758
694
  }
759
- setResponseStatus(event, 200);
760
- setResponseHeader(event, "Content-Type", "text/html");
761
- return loginHtml;
762
695
  }));
696
+ // Auth guard — stored both in framework middleware registry AND in
697
+ // _authGuardFn so the server middleware can enforce it on ALL routes.
698
+ const loginHtml = options.loginHtml ?? getOnboardingHtml({ googleOnly: options.googleOnly });
699
+ _authGuardConfig = { loginHtml, publicPaths };
700
+ const guardFn = createAuthGuardFn();
701
+ _authGuardFn = guardFn;
702
+ app.use(defineEventHandler(guardFn));
763
703
  }
764
704
  // ---------------------------------------------------------------------------
765
- // mountAuthMiddlewaremounts login/logout/session routes + auth guard
705
+ // mountTokenOnlyRoutesACCESS_TOKEN-only auth (no Better Auth)
766
706
  // ---------------------------------------------------------------------------
767
- /**
768
- * Mount auth middleware + login/logout/session routes onto an H3 app.
769
- *
770
- * @deprecated Use `autoMountAuth(app, options?)` instead for automatic
771
- * dev/prod behavior. This function is kept for backwards compatibility
772
- * when you need explicit control over the access token.
773
- */
774
- export function mountAuthMiddleware(app, accessToken) {
775
- mountAuthRoutes(app, [accessToken]);
776
- }
777
- function isPublicPath(url, publicPaths) {
778
- const p = url.split("?")[0];
779
- return publicPaths.some((pp) => p === pp || p.startsWith(pp + "/"));
780
- }
781
- function mountAuthRoutes(app, accessTokens, publicPaths = []) {
782
- // POST /_agent-native/auth/login
707
+ function mountTokenOnlyRoutes(app, accessTokens, publicPaths = []) {
783
708
  app.use("/_agent-native/auth/login", defineEventHandler(async (event) => {
784
709
  if (getMethod(event) !== "POST") {
785
710
  setResponseStatus(event, 405);
786
711
  return { error: "Method not allowed" };
787
712
  }
788
- const ip = getClientIp(event);
789
- const rateLimitKey = `login:${ip}`;
790
- const limited = checkRateLimit(event, rateLimitKey);
791
- if (limited)
792
- return limited;
793
713
  const body = await readBody(event);
794
714
  if (!body?.token ||
795
715
  typeof body.token !== "string" ||
@@ -801,15 +721,13 @@ function mountAuthRoutes(app, accessTokens, publicPaths = []) {
801
721
  await addSession(sessionToken, "user");
802
722
  setCookie(event, COOKIE_NAME, sessionToken, {
803
723
  httpOnly: true,
804
- secure: process.env.NODE_ENV === "production",
724
+ secure: !isDevEnvironment(),
805
725
  sameSite: "lax",
806
726
  path: "/",
807
727
  maxAge: sessionMaxAge,
808
728
  });
809
- resetRateLimit(rateLimitKey);
810
729
  return { ok: true };
811
730
  }));
812
- // POST /_agent-native/auth/logout
813
731
  app.use("/_agent-native/auth/logout", defineEventHandler(async (event) => {
814
732
  const cookie = getCookie(event, COOKIE_NAME);
815
733
  if (cookie)
@@ -817,7 +735,6 @@ function mountAuthRoutes(app, accessTokens, publicPaths = []) {
817
735
  deleteCookie(event, COOKIE_NAME, { path: "/" });
818
736
  return { ok: true };
819
737
  }));
820
- // GET /_agent-native/auth/session — client session check
821
738
  app.use("/_agent-native/auth/session", defineEventHandler(async (event) => {
822
739
  if (getMethod(event) !== "GET") {
823
740
  setResponseStatus(event, 405);
@@ -826,68 +743,86 @@ function mountAuthRoutes(app, accessTokens, publicPaths = []) {
826
743
  const session = await getSession(event);
827
744
  return session ?? { error: "Not authenticated" };
828
745
  }));
829
- // Auth guard runs before all other handlers
830
- app.use(defineEventHandler(async (event) => {
831
- const url = event.node?.req?.url ?? event.path ?? "/";
832
- const p = url.split("?")[0];
833
- // Skip auth routes
834
- if (p === "/_agent-native/auth/login" ||
835
- p === "/_agent-native/auth/logout" ||
836
- p === "/_agent-native/auth/session") {
837
- return;
838
- }
839
- // Skip public paths
840
- if (isPublicPath(url, publicPaths)) {
841
- return;
746
+ _authGuardConfig = { loginHtml: TOKEN_LOGIN_HTML, publicPaths };
747
+ const guardFn = createAuthGuardFn();
748
+ _authGuardFn = guardFn;
749
+ app.use(defineEventHandler(guardFn));
750
+ }
751
+ // ---------------------------------------------------------------------------
752
+ // mountLocalModeRoutes stub routes for AUTH_MODE=local
753
+ // ---------------------------------------------------------------------------
754
+ function mountLocalModeRoutes(app) {
755
+ app.use("/_agent-native/auth/session", defineEventHandler(async (event) => {
756
+ if (getMethod(event) !== "GET") {
757
+ setResponseStatus(event, 405);
758
+ return { error: "Method not allowed" };
842
759
  }
843
- // Use getSession() so BYOA custom auth is respected
844
- const session = await getSession(event);
845
- if (session) {
846
- return; // Authenticated
760
+ return await getSession(event);
761
+ }));
762
+ app.use("/_agent-native/auth/login", defineEventHandler(() => ({ ok: true })));
763
+ app.use("/_agent-native/auth/logout", defineEventHandler(() => ({ ok: true })));
764
+ // Allow exiting local mode to switch to real auth
765
+ app.use("/_agent-native/auth/exit-local-mode", defineEventHandler(async (event) => {
766
+ if (getMethod(event) !== "POST") {
767
+ setResponseStatus(event, 405);
768
+ return { error: "Method not allowed" };
847
769
  }
848
- // Unauthenticated
849
- if (p.startsWith("/api/") || p.startsWith("/_agent-native/")) {
850
- setResponseStatus(event, 401);
851
- return { error: "Unauthorized" };
770
+ const ok = await removeAuthModeLocal();
771
+ if (!ok) {
772
+ setResponseStatus(event, 500);
773
+ return { error: "Failed to remove AUTH_MODE from .env" };
852
774
  }
853
- setResponseStatus(event, 200);
854
- setResponseHeader(event, "Content-Type", "text/html");
855
- return LOGIN_HTML;
775
+ return { ok: true };
856
776
  }));
857
777
  }
858
778
  // ---------------------------------------------------------------------------
859
779
  // autoMountAuth — the recommended entry point
860
780
  // ---------------------------------------------------------------------------
861
781
  /**
862
- * Automatically configure auth based on the environment:
863
- *
864
- * - **Dev mode** (`NODE_ENV !== "production"`): Auth is skipped entirely.
865
- * `getSession()` returns `{ email: "local@localhost" }` for all requests.
866
- *
867
- * - **Production with ACCESS_TOKEN/ACCESS_TOKENS set**: Auth middleware is
868
- * mounted. Unauthenticated requests see a login page. One env var is all
869
- * you need.
870
- *
871
- * - **Production without tokens and AUTH_DISABLED !== "true"**: Refuses to
872
- * start. Logs a clear error explaining what to do.
782
+ * Automatically configure auth based on environment and configuration:
873
783
  *
874
- * - **Production with AUTH_DISABLED=true**: Auth is skipped (for apps behind
875
- * infrastructure-level auth like Cloudflare Access or a VPN).
784
+ * - **AUTH_MODE=local**: Auth bypassed. `getSession()` returns `{ email: "local@localhost" }`.
785
+ * This is the explicit escape hatch for solo local development.
786
+ * - **BYOA (custom getSession)**: Template-provided auth callback handles everything.
787
+ * - **AUTH_DISABLED=true**: Auth bypassed (for infrastructure-level auth like Cloudflare Access).
788
+ * - **ACCESS_TOKEN/ACCESS_TOKENS**: Simple token-based auth.
789
+ * - **Default**: Better Auth with email/password, social providers, organizations, and JWT.
790
+ * Users see an onboarding page to create an account on first visit.
876
791
  *
877
792
  * Returns true if auth was mounted, false if skipped.
878
793
  */
879
- export function autoMountAuth(app, options = {}) {
880
- // In Nitro 3.0 dev mode, the H3 app may not be available yet.
881
- // In dev mode auth is bypassed anyway, so we can safely skip.
794
+ export async function autoMountAuth(app, options = {}) {
795
+ // If auth is already mounted (e.g., default plugin ran before custom plugin),
796
+ // don't re-mount routes but DO update the live config if custom options
797
+ // like googleOnly or loginHtml were provided. This fixes the production race
798
+ // where the default plugin (no googleOnly) mounts first, and the template's
799
+ // custom auth plugin runs later. Because createAuthGuardFn() reads from
800
+ // _authGuardConfig on every request, updating it here takes effect immediately.
801
+ if (_authGuardFn) {
802
+ if (_authGuardConfig) {
803
+ if (options.googleOnly || options.loginHtml) {
804
+ _authGuardConfig.loginHtml =
805
+ options.loginHtml ??
806
+ getOnboardingHtml({ googleOnly: options.googleOnly });
807
+ }
808
+ if (options.publicPaths) {
809
+ _authGuardConfig.publicPaths = [
810
+ ...(_authGuardConfig.publicPaths ?? []),
811
+ ...options.publicPaths,
812
+ ];
813
+ }
814
+ }
815
+ return true;
816
+ }
882
817
  if (!app) {
883
- if (isDevMode()) {
818
+ if (isLocalMode() || isDevEnvironment()) {
884
819
  authDisabledMode = false;
885
820
  customGetSession = null;
886
821
  return false;
887
822
  }
888
823
  throw new Error("autoMountAuth: H3 app is required. In Nitro plugins, pass nitroApp.h3App.");
889
824
  }
890
- // Reset globals to avoid stale state from prior calls
825
+ // Reset globals
891
826
  customGetSession = null;
892
827
  authDisabledMode = false;
893
828
  sessionMaxAge = options.maxAge ?? DEFAULT_MAX_AGE;
@@ -895,24 +830,16 @@ export function autoMountAuth(app, options = {}) {
895
830
  if (options.getSession) {
896
831
  customGetSession = options.getSession;
897
832
  }
898
- // Dev mode skip auth entirely
899
- if (isDevMode()) {
900
- // Mount a session endpoint that checks for a real session first
901
- app.use("/_agent-native/auth/session", defineEventHandler(async (event) => {
902
- if (getMethod(event) !== "GET") {
903
- setResponseStatus(event, 405);
904
- return { error: "Method not allowed" };
905
- }
906
- return await getSession(event);
907
- }));
908
- // Mount no-op login/logout so client code doesn't break
909
- app.use("/_agent-native/auth/login", defineEventHandler(() => ({ ok: true })));
910
- app.use("/_agent-native/auth/logout", defineEventHandler(() => ({ ok: true })));
833
+ // AUTH_MODE=localexplicit local-only mode (escape hatch)
834
+ if (isLocalMode()) {
835
+ mountLocalModeRoutes(app);
836
+ // Still init Better Auth in background so users can create accounts later
837
+ getBetterAuth(options.betterAuth).catch(() => { });
838
+ console.log("[agent-native] Auth mode: local (no auth required).");
911
839
  return false;
912
840
  }
913
- // BYOA with custom getSession — skip token check, mount session/guard routes
841
+ // BYOA custom getSession provider
914
842
  if (customGetSession) {
915
- // Mount session endpoint
916
843
  app.use("/_agent-native/auth/session", defineEventHandler(async (event) => {
917
844
  if (getMethod(event) !== "GET") {
918
845
  setResponseStatus(event, 405);
@@ -929,65 +856,56 @@ export function autoMountAuth(app, options = {}) {
929
856
  deleteCookie(event, COOKIE_NAME, { path: "/" });
930
857
  return { ok: true };
931
858
  }));
932
- // Mount auth guard that delegates to custom getSession
933
- const byoaLoginHtml = options.loginHtml ?? LOGIN_HTML;
934
- app.use(defineEventHandler(async (event) => {
935
- // Use H3's getRequestURL for cross-platform compat (Node + Workers)
936
- const url = event.node?.req?.url ?? event.path ?? "/";
937
- const p = url.split("?")[0];
938
- if (p === "/_agent-native/auth/login" ||
939
- p === "/_agent-native/auth/logout" ||
940
- p === "/_agent-native/auth/session") {
941
- return;
942
- }
943
- // Skip public paths
944
- if (isPublicPath(url, publicPaths)) {
945
- return;
946
- }
947
- const session = await getSession(event);
948
- if (session)
949
- return;
950
- if (p.startsWith("/api/") || p.startsWith("/_agent-native/")) {
951
- setResponseStatus(event, 401);
952
- return { error: "Unauthorized" };
953
- }
954
- setResponseStatus(event, 200);
955
- setResponseHeader(event, "Content-Type", "text/html");
956
- return byoaLoginHtml;
957
- }));
859
+ const byoaLoginHtml = options.loginHtml ?? TOKEN_LOGIN_HTML;
860
+ _authGuardConfig = { loginHtml: byoaLoginHtml, publicPaths };
861
+ const guardFn = createAuthGuardFn();
862
+ _authGuardFn = guardFn;
863
+ app.use(defineEventHandler(guardFn));
958
864
  console.log("[agent-native] Auth enabled — custom getSession provider.");
959
865
  return true;
960
866
  }
961
- // Productioncheck for tokens
867
+ // AUTH_DISABLEDskip auth (infrastructure-level auth)
868
+ if (process.env.AUTH_DISABLED === "true") {
869
+ authDisabledMode = true;
870
+ console.warn("[agent-native] AUTH_DISABLED=true — running without auth. " +
871
+ "Ensure this app is behind infrastructure-level auth (Cloudflare Access, VPN, etc.).");
872
+ mountLocalModeRoutes(app);
873
+ return false;
874
+ }
875
+ // ACCESS_TOKEN-only mode
962
876
  const tokens = getAccessTokens();
963
- if (tokens.length === 0) {
964
- // No tokens set — check if auth is explicitly disabled
965
- if (process.env.AUTH_DISABLED === "true") {
966
- authDisabledMode = true;
967
- console.warn("[agent-native] AUTH_DISABLED=true — running in production without auth. " +
968
- "Ensure this app is behind infrastructure-level auth (Cloudflare Access, VPN, etc.).");
969
- // Mount session endpoint
970
- app.use("/_agent-native/auth/session", defineEventHandler(async (event) => {
971
- if (getMethod(event) !== "GET") {
972
- setResponseStatus(event, 405);
973
- return { error: "Method not allowed" };
974
- }
975
- return await getSession(event);
976
- }));
977
- app.use("/_agent-native/auth/login", defineEventHandler(() => ({ ok: true })));
978
- app.use("/_agent-native/auth/logout", defineEventHandler(() => ({ ok: true })));
979
- return false;
980
- }
981
- // No access tokens set — enable email/password authentication
982
- pruneExpiredSessions().catch(() => { });
983
- mountEmailAuthRoutes(app, publicPaths);
984
- console.log("[agent-native] Auth enabled — email/password authentication.");
877
+ if (tokens.length > 0) {
878
+ mountTokenOnlyRoutes(app, tokens, publicPaths);
879
+ console.log(`[agent-native] Auth enabled — ${tokens.length} access token(s) configured.`);
985
880
  return true;
986
881
  }
987
- // Production with tokens — mount auth
988
- pruneExpiredSessions().catch(() => { });
989
- mountAuthRoutes(app, tokens, publicPaths);
990
- console.log(`[agent-native] Auth enabled — ${tokens.length} access token(s) configured.`);
882
+ // Default: Better Auth (account-first)
883
+ try {
884
+ await mountBetterAuthRoutes(app, options);
885
+ console.log("[agent-native] Auth enabled — Better Auth (accounts + organizations).");
886
+ }
887
+ catch (err) {
888
+ console.error("[agent-native] Failed to initialize Better Auth:", err);
889
+ // CRITICAL: Even if Better Auth fails, register the auth guard so
890
+ // unauthenticated users can't access the app. They'll see the login
891
+ // page but won't be able to sign in until the DB is available.
892
+ const loginHtml = options.loginHtml ??
893
+ getOnboardingHtml({ googleOnly: options.googleOnly });
894
+ _authGuardConfig = { loginHtml, publicPaths };
895
+ const guardFn = createAuthGuardFn();
896
+ _authGuardFn = guardFn;
897
+ app.use(defineEventHandler(guardFn));
898
+ console.log("[agent-native] Auth guard registered despite init failure — app is locked.");
899
+ }
991
900
  return true;
992
901
  }
902
+ // ---------------------------------------------------------------------------
903
+ // Deprecated — kept for backward compat
904
+ // ---------------------------------------------------------------------------
905
+ /**
906
+ * @deprecated Use `autoMountAuth(app, options?)` instead.
907
+ */
908
+ export function mountAuthMiddleware(app, accessToken) {
909
+ mountTokenOnlyRoutes(app, [accessToken]);
910
+ }
993
911
  //# sourceMappingURL=auth.js.map