@agent-native/core 0.114.0 → 0.114.2

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 (223) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +15 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/cli/create.ts +23 -0
  5. package/corpus/core/src/cli/skills.ts +24 -0
  6. package/corpus/core/src/client/build-compatibility.ts +77 -0
  7. package/corpus/core/src/client/route-chunk-recovery/index.ts +1 -0
  8. package/corpus/core/src/client/use-action.ts +32 -1
  9. package/corpus/core/src/deploy/build.ts +4 -1
  10. package/corpus/core/src/org/context.ts +56 -30
  11. package/corpus/core/src/server/action-routes.ts +52 -2
  12. package/corpus/core/src/server/auth-plugin.ts +9 -4
  13. package/corpus/core/src/server/better-auth-instance.ts +5 -1
  14. package/corpus/core/src/shared/mcp-embed-headers.ts +1 -1
  15. package/corpus/core/src/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  16. package/corpus/core/src/templates/default/AGENTS.md +4 -1
  17. package/corpus/core/src/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  18. package/corpus/core/src/templates/headless/AGENTS.md +5 -1
  19. package/corpus/core/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +26 -0
  20. package/corpus/core/src/templates/workspace-core/AGENTS.md +3 -1
  21. package/corpus/core/src/templates/workspace-root/AGENTS.md +3 -1
  22. package/corpus/core/src/vite/client.ts +17 -0
  23. package/corpus/templates/analytics/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  24. package/corpus/templates/analytics/AGENTS.md +5 -0
  25. package/corpus/templates/assets/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  26. package/corpus/templates/assets/AGENTS.md +5 -0
  27. package/corpus/templates/brain/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  28. package/corpus/templates/brain/AGENTS.md +5 -0
  29. package/corpus/templates/calendar/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  30. package/corpus/templates/calendar/AGENTS.md +5 -0
  31. package/corpus/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  32. package/corpus/templates/chat/AGENTS.md +4 -1
  33. package/corpus/templates/clips/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  34. package/corpus/templates/clips/AGENTS.md +5 -0
  35. package/corpus/templates/content/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  36. package/corpus/templates/content/AGENTS.md +7 -0
  37. package/corpus/templates/content/actions/_content-database-personal-view.ts +49 -5
  38. package/corpus/templates/content/actions/_content-document-access.ts +21 -0
  39. package/corpus/templates/content/actions/_content-favorites.ts +91 -0
  40. package/corpus/templates/content/actions/_content-files.ts +79 -23
  41. package/corpus/templates/content/actions/_content-sidebar-state.ts +24 -0
  42. package/corpus/templates/content/actions/_content-space-access.ts +15 -17
  43. package/corpus/templates/content/actions/_content-space-catalog-guards.ts +20 -0
  44. package/corpus/templates/content/actions/_content-spaces.ts +364 -167
  45. package/corpus/templates/content/actions/_database-source-utils.ts +8 -0
  46. package/corpus/templates/content/actions/_database-utils.ts +249 -15
  47. package/corpus/templates/content/actions/_delete-content-space.ts +84 -0
  48. package/corpus/templates/content/actions/_files-system-properties.ts +499 -0
  49. package/corpus/templates/content/actions/_local-file-documents.ts +0 -1
  50. package/corpus/templates/content/actions/_property-utils.ts +18 -9
  51. package/corpus/templates/content/actions/bind-content-database-source-field.ts +3 -0
  52. package/corpus/templates/content/actions/configure-document-property.ts +3 -0
  53. package/corpus/templates/content/actions/create-content-database.ts +2 -2
  54. package/corpus/templates/content/actions/create-content-space.ts +34 -0
  55. package/corpus/templates/content/actions/create-document.ts +4 -1
  56. package/corpus/templates/content/actions/delete-content-space.ts +19 -0
  57. package/corpus/templates/content/actions/delete-database-items.ts +28 -1
  58. package/corpus/templates/content/actions/delete-document-property.ts +3 -0
  59. package/corpus/templates/content/actions/delete-document.ts +39 -2
  60. package/corpus/templates/content/actions/duplicate-database-item.ts +6 -0
  61. package/corpus/templates/content/actions/duplicate-database-items.ts +6 -0
  62. package/corpus/templates/content/actions/duplicate-document-property.ts +3 -0
  63. package/corpus/templates/content/actions/get-content-database.ts +11 -2
  64. package/corpus/templates/content/actions/get-content-sidebar-state.ts +23 -0
  65. package/corpus/templates/content/actions/get-document.ts +32 -7
  66. package/corpus/templates/content/actions/import-content-source.ts +33 -1
  67. package/corpus/templates/content/actions/list-content-spaces.ts +34 -2
  68. package/corpus/templates/content/actions/list-documents.ts +39 -7
  69. package/corpus/templates/content/actions/reorder-document-property.ts +9 -0
  70. package/corpus/templates/content/actions/set-document-property.ts +41 -23
  71. package/corpus/templates/content/actions/share-local-file-document.ts +15 -0
  72. package/corpus/templates/content/actions/submit-content-database-form.ts +7 -0
  73. package/corpus/templates/content/actions/sync-local-folder-source.ts +14 -0
  74. package/corpus/templates/content/actions/update-content-database-view.ts +1 -0
  75. package/corpus/templates/content/actions/update-content-sidebar-state.ts +27 -0
  76. package/corpus/templates/content/actions/update-document.ts +158 -66
  77. package/corpus/templates/content/app/components/EmptyState.tsx +4 -57
  78. package/corpus/templates/content/app/components/editor/CommentsSidebar.tsx +8 -1
  79. package/corpus/templates/content/app/components/editor/DocumentEditor.tsx +519 -178
  80. package/corpus/templates/content/app/components/editor/DocumentInfoPanel.tsx +39 -0
  81. package/corpus/templates/content/app/components/editor/DocumentProperties.tsx +1 -1
  82. package/corpus/templates/content/app/components/editor/DocumentToolbar.tsx +266 -7
  83. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +430 -152
  84. package/corpus/templates/content/app/components/editor/database/sidebar.tsx +467 -66
  85. package/corpus/templates/content/app/components/editor/database/view-config.ts +9 -3
  86. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +720 -196
  87. package/corpus/templates/content/app/components/sidebar/DocumentTreeItem.tsx +173 -1
  88. package/corpus/templates/content/app/components/sidebar/document-sidebar-sections.ts +1 -1
  89. package/corpus/templates/content/app/components/sidebar/select-content-space.ts +91 -16
  90. package/corpus/templates/content/app/entry.client.tsx +5 -1
  91. package/corpus/templates/content/app/hooks/use-content-database.ts +84 -3
  92. package/corpus/templates/content/app/hooks/use-content-spaces.ts +60 -2
  93. package/corpus/templates/content/app/hooks/use-create-page.ts +30 -0
  94. package/corpus/templates/content/app/hooks/use-documents.ts +270 -19
  95. package/corpus/templates/content/app/i18n-data.ts +243 -20
  96. package/corpus/templates/content/app/lib/local-folder-picker-safety.ts +54 -0
  97. package/corpus/templates/content/app/lib/local-folder-picker-support.ts +18 -0
  98. package/corpus/templates/content/app/routes/_app.favorites.tsx +30 -0
  99. package/corpus/templates/content/app/routes/_app.local-files.tsx +18 -6
  100. package/corpus/templates/content/changelog/2026-07-17-workspace-files-now-stay-in-a-loading-state-until-automatic-.md +6 -0
  101. package/corpus/templates/content/changelog/2026-07-17-workspace-switching-now-opens-the-selected-files-database-pr.md +6 -0
  102. package/corpus/templates/content/changelog/2026-07-17-workspaces-now-expand-above-their-own-files-list-without-dup.md +6 -0
  103. package/corpus/templates/content/changelog/2026-07-18-create-named-workspaces-each-with-its-own-private-files-data.md +6 -0
  104. package/corpus/templates/content/changelog/2026-07-18-favorites-align-with-workspace-and-file-rows-in-the-sidebar.md +6 -0
  105. package/corpus/templates/content/changelog/2026-07-18-local-folder-selection-no-longer-invokes-the-unsafe-native-p.md +6 -0
  106. package/corpus/templates/content/changelog/2026-07-18-made-content-workspaces-independently-expandable-restored-or.md +6 -0
  107. package/corpus/templates/content/changelog/2026-07-18-page-details-now-live-in-a-shared-info-and-comments-rail-dat.md +6 -0
  108. package/corpus/templates/content/changelog/2026-07-18-workspace-database-views-now-control-sidebar-workspace-navig.md +6 -0
  109. package/corpus/templates/content/changelog/2026-07-18-workspace-navigation-now-aligns-favorites-with-workspace-pag.md +6 -0
  110. package/corpus/templates/content/changelog/2026-07-19-favorites-now-open-as-a-table-and-compact-breadcrumbs-make-w.md +6 -0
  111. package/corpus/templates/content/changelog/2026-07-19-files-databases-now-start-unfiltered-sidebar-rows-exactly-fo.md +6 -0
  112. package/corpus/templates/content/changelog/2026-07-19-sidebar-page-trees-now-open-only-when-expanded-remember-thei.md +6 -0
  113. package/corpus/templates/content/changelog/2026-07-19-workspace-file-databases-now-use-the-workspace-name-open-as-.md +6 -0
  114. package/corpus/templates/content/changelog/2026-07-19-workspace-navigation-now-stays-stable-on-hover-uses-folder-i.md +6 -0
  115. package/corpus/templates/content/changelog/2026-07-19-workspace-rows-now-use-folder-icons-and-deleting-a-user-crea.md +6 -0
  116. package/corpus/templates/content/changelog/2026-07-19-workspaces-can-be-created-without-leaving-the-workspaces-dat.md +6 -0
  117. package/corpus/templates/content/e2e/global-setup.ts +3 -2
  118. package/corpus/templates/content/parity/matrix.md +28 -28
  119. package/corpus/templates/content/parity/matrix.ts +8 -2
  120. package/corpus/templates/content/server/db/index.ts +1 -0
  121. package/corpus/templates/content/server/db/schema.ts +10 -0
  122. package/corpus/templates/content/server/lib/documents.ts +12 -7
  123. package/corpus/templates/content/server/plugins/db.ts +17 -0
  124. package/corpus/templates/content/shared/api.ts +9 -0
  125. package/corpus/templates/content/shared/database-form.ts +11 -2
  126. package/corpus/templates/content/vite.config.ts +1 -0
  127. package/corpus/templates/design/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  128. package/corpus/templates/design/AGENTS.md +5 -0
  129. package/corpus/templates/dispatch/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  130. package/corpus/templates/dispatch/AGENTS.md +5 -0
  131. package/corpus/templates/forms/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  132. package/corpus/templates/forms/AGENTS.md +5 -0
  133. package/corpus/templates/macros/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  134. package/corpus/templates/macros/AGENTS.md +5 -0
  135. package/corpus/templates/mail/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  136. package/corpus/templates/mail/AGENTS.md +5 -0
  137. package/corpus/templates/plan/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  138. package/corpus/templates/plan/AGENTS.md +5 -0
  139. package/corpus/templates/slides/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  140. package/corpus/templates/slides/AGENTS.md +5 -0
  141. package/corpus/templates/tasks/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  142. package/corpus/templates/tasks/AGENTS.md +5 -0
  143. package/dist/cli/create.d.ts.map +1 -1
  144. package/dist/cli/create.js +21 -0
  145. package/dist/cli/create.js.map +1 -1
  146. package/dist/cli/skills.d.ts.map +1 -1
  147. package/dist/cli/skills.js +19 -0
  148. package/dist/cli/skills.js.map +1 -1
  149. package/dist/client/build-compatibility.d.ts +11 -0
  150. package/dist/client/build-compatibility.d.ts.map +1 -0
  151. package/dist/client/build-compatibility.js +56 -0
  152. package/dist/client/build-compatibility.js.map +1 -0
  153. package/dist/client/route-chunk-recovery/index.d.ts +1 -0
  154. package/dist/client/route-chunk-recovery/index.d.ts.map +1 -1
  155. package/dist/client/route-chunk-recovery/index.js +1 -0
  156. package/dist/client/route-chunk-recovery/index.js.map +1 -1
  157. package/dist/client/use-action.d.ts.map +1 -1
  158. package/dist/client/use-action.js +19 -1
  159. package/dist/client/use-action.js.map +1 -1
  160. package/dist/collab/routes.d.ts +1 -1
  161. package/dist/deploy/build.js +2 -1
  162. package/dist/deploy/build.js.map +1 -1
  163. package/dist/notifications/routes.d.ts +1 -1
  164. package/dist/observability/routes.d.ts +3 -3
  165. package/dist/org/context.d.ts +4 -2
  166. package/dist/org/context.d.ts.map +1 -1
  167. package/dist/org/context.js +44 -22
  168. package/dist/org/context.js.map +1 -1
  169. package/dist/progress/routes.d.ts +1 -1
  170. package/dist/provider-api/actions/custom-provider-registration.d.ts +10 -10
  171. package/dist/provider-api/actions/provider-api.d.ts +12 -12
  172. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  173. package/dist/resources/handlers.d.ts +1 -1
  174. package/dist/server/action-routes.d.ts.map +1 -1
  175. package/dist/server/action-routes.js +32 -2
  176. package/dist/server/action-routes.js.map +1 -1
  177. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  178. package/dist/server/auth-plugin.d.ts.map +1 -1
  179. package/dist/server/auth-plugin.js +9 -5
  180. package/dist/server/auth-plugin.js.map +1 -1
  181. package/dist/server/better-auth-instance.d.ts.map +1 -1
  182. package/dist/server/better-auth-instance.js +4 -1
  183. package/dist/server/better-auth-instance.js.map +1 -1
  184. package/dist/server/transcribe-voice.d.ts +1 -1
  185. package/dist/shared/mcp-embed-headers.d.ts +1 -1
  186. package/dist/shared/mcp-embed-headers.d.ts.map +1 -1
  187. package/dist/shared/mcp-embed-headers.js +1 -1
  188. package/dist/shared/mcp-embed-headers.js.map +1 -1
  189. package/dist/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  190. package/dist/templates/chat/AGENTS.md +4 -1
  191. package/dist/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  192. package/dist/templates/default/AGENTS.md +4 -1
  193. package/dist/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  194. package/dist/templates/headless/AGENTS.md +5 -1
  195. package/dist/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +26 -0
  196. package/dist/templates/workspace-core/AGENTS.md +3 -1
  197. package/dist/templates/workspace-root/AGENTS.md +3 -1
  198. package/dist/vite/client.d.ts +6 -0
  199. package/dist/vite/client.d.ts.map +1 -1
  200. package/dist/vite/client.js +8 -0
  201. package/dist/vite/client.js.map +1 -1
  202. package/package.json +1 -1
  203. package/src/cli/create.ts +23 -0
  204. package/src/cli/skills.ts +24 -0
  205. package/src/client/build-compatibility.ts +77 -0
  206. package/src/client/route-chunk-recovery/index.ts +1 -0
  207. package/src/client/use-action.ts +32 -1
  208. package/src/deploy/build.ts +4 -1
  209. package/src/org/context.ts +56 -30
  210. package/src/server/action-routes.ts +52 -2
  211. package/src/server/auth-plugin.ts +9 -4
  212. package/src/server/better-auth-instance.ts +5 -1
  213. package/src/shared/mcp-embed-headers.ts +1 -1
  214. package/src/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  215. package/src/templates/chat/AGENTS.md +4 -1
  216. package/src/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  217. package/src/templates/default/AGENTS.md +4 -1
  218. package/src/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +133 -0
  219. package/src/templates/headless/AGENTS.md +5 -1
  220. package/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +26 -0
  221. package/src/templates/workspace-core/AGENTS.md +3 -1
  222. package/src/templates/workspace-root/AGENTS.md +3 -1
  223. package/src/vite/client.ts +17 -0
@@ -1 +1 @@
1
- {"version":3,"file":"better-auth-instance.js","sourceRoot":"","sources":["../../src/server/better-auth-instance.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,UAAU,EAA0B,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EACL,OAAO,EACP,IAAI,IAAI,MAAM,EACd,SAAS,IAAI,WAAW,EACxB,OAAO,IAAI,SAAS,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,WAAW,EACX,IAAI,IAAI,UAAU,EAClB,OAAO,IAAI,aAAa,GACzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EACL,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,aAAa,EACb,WAAW,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I,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACtC,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;QACpC,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC;QAC/D,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;QACxE,OAAO,cAAc,CAAC,EAAE,EAAE;YACxB,QAAQ,EAAE,QAAQ;YAClB,MAAM,EAAE,gBAAgB;SACzB,CAAC,CAAC;IACL,CAAC;IAED,wEAAwE;IACxE,2DAA2D;IAC3D,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,oBAAoB,EAAE,EAAE,CAAC,CAAC;IACxE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,wBAAwB,CAAC,CAAC;IAC3D,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC,CAAC;IACzD,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;IACxE,OAAO,cAAc,CAAC,EAAE,EAAE;QACxB,QAAQ,EAAE,QAAQ;QAClB,MAAM,EAAE,gBAAgB;KACzB,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Internal Better Auth instance — lazily created, not exported to templates.\n *\n * Templates interact with auth via the existing `getSession()`, `autoMountAuth()`,\n * `createAuthPlugin()`, and `createGoogleAuthPlugin()` APIs. Better Auth is an\n * implementation detail behind those interfaces.\n */\n\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { betterAuth, type BetterAuthOptions } from \"better-auth\";\nimport { bearer } from \"better-auth/plugins/bearer\";\nimport { jwt } from \"better-auth/plugins/jwt\";\nimport {\n pgTable,\n text as pgText,\n timestamp as pgTimestamp,\n boolean as pgBoolean,\n} from \"drizzle-orm/pg-core\";\nimport {\n sqliteTable,\n text as sqliteText,\n integer as sqliteInteger,\n} from \"drizzle-orm/sqlite-core\";\n\nimport { TEMPLATES } from \"../cli/templates-meta.js\";\nimport { getDbExec, isPostgres } from \"../db/client.js\";\nimport {\n getDialect,\n getDatabaseUrl,\n getDatabaseAuthToken,\n closePgliteClients,\n getPgliteClient,\n isPgliteUrl,\n loadPgliteDrizzle,\n pgPoolOptions,\n neonPoolMax,\n attachNeonPoolErrorLogger,\n} from \"../db/client.js\";\nimport { ensureTableExists } from \"../db/ddl-guard.js\";\nimport { saveOAuthTokens } from \"../oauth-tokens/store.js\";\nimport { acceptPendingInvitationsForEmail } from \"../org/accept-pending.js\";\nimport { autoJoinDomainMatchingOrgs } from \"../org/auto-join-domain.js\";\nimport { flushTracking, identify, track } from \"../tracking/index.js\";\nimport { getAppProductionUrl } from \"./app-url.js\";\nimport { signupAttributionFromCookieHeader } from \"./attribution.js\";\nimport { resolveAuthCookieNamespace } from \"./cookie-namespace.js\";\nimport { getWorkspaceA2ADerivedSecret } from \"./derived-secret.js\";\nimport {\n renderResetPasswordEmail,\n renderVerifySignupEmail,\n} from \"./email-templates.js\";\nimport { sendEmail, isEmailConfigured } from \"./email.js\";\nimport { resolveGoogleSignInCredentials } from \"./google-oauth-credentials.js\";\n\nasync function flushSignupTracking(): Promise<void> {\n try {\n await Promise.race([\n flushTracking(),\n new Promise<void>((resolve) => setTimeout(resolve, 1500)),\n ]);\n } catch {\n // Signup should never fail because analytics delivery did.\n }\n}\n\nexport async function hasBetterAuthUserEmail(email: string): Promise<boolean> {\n const adapter = await getBetterAuthInternalAdapter().catch(() => undefined);\n if (!adapter) return false;\n const existing = await adapter\n .findUserByEmail(email, { includeAccounts: false })\n .catch(() => null);\n return !!existing?.user?.email;\n}\n\nexport async function trackSignupEvent({\n authProvider,\n authUserId,\n email,\n name,\n attribution,\n}: {\n authProvider: string;\n authUserId?: string;\n email: string;\n name?: string | null;\n /**\n * First-touch referral attribution derived from the visitor's `an_ft`\n * cookie (see `server/attribution.ts`). Snake_case keys such as\n * `referral_source`, `referrer_user`, and the UTM passthrough are merged\n * into the `signup` event so we can measure where new users came from.\n * `undefined` values are dropped; a missing object is a clean no-op.\n */\n attribution?: Record<string, string | undefined>;\n}): Promise<void> {\n identify(email, {\n email,\n name: name ?? undefined,\n authUserId,\n });\n const cleanAttribution: Record<string, string> = {};\n if (attribution) {\n for (const [key, value] of Object.entries(attribution)) {\n if (typeof value === \"string\" && value.length > 0) {\n cleanAttribution[key] = value;\n }\n }\n }\n track(\n \"signup\",\n {\n ...resolveSignupTrackingProperties(),\n auth_provider: authProvider,\n ...(authUserId ? { auth_user_id: authUserId } : {}),\n ...cleanAttribution,\n },\n { userId: email },\n );\n await flushSignupTracking();\n}\n\n// ---------------------------------------------------------------------------\n// Persistent auth secret\n// ---------------------------------------------------------------------------\n\nlet inMemoryDevAuthSecret: string | undefined;\n\n/**\n * Resolve the Better Auth signing secret.\n *\n * Resolution order:\n * 1. `BETTER_AUTH_SECRET` env var — explicit, recommended for prod.\n * 2. Hosted workspace deploys can derive a per-purpose secret from the\n * already-required `A2A_SECRET` root. This keeps fresh workspace branches\n * bootable without reusing the raw A2A key as a cookie-signing key.\n * 3. Existing `.env.local` values in the template cwd — read-only\n * compatibility for projects that already configured this secret.\n * 4. Generate a per-process in-memory random 32-byte hex in development.\n *\n * Why this matters: before this helper existed, missing `BETTER_AUTH_SECRET`\n * fell through to `GOOGLE_CLIENT_SECRET` / `ACCESS_TOKEN` / a hardcoded\n * string. If a template happened to have none of those, each dev-server\n * boot would re-fall back to the hardcoded value (still stable) — but\n * rotating Google credentials, toggling `ACCESS_TOKEN`, or churning the\n * fallback chain would invalidate every signed cookie and force everyone\n * to sign in again. We still read explicit env configuration, but never\n * auto-write a generated secret into env files.\n */\nfunction resolveAuthSecret(): string {\n if (process.env.BETTER_AUTH_SECRET) return process.env.BETTER_AUTH_SECRET;\n const workspaceDerivedSecret = getWorkspaceA2ADerivedSecret(\"better-auth\");\n if (workspaceDerivedSecret) return workspaceDerivedSecret;\n\n // In production, beyond the workspace A2A-derived fallback above, never\n // auto-generate or use legacy fallbacks. A generated secret invalidates every\n // signed session cookie on the next cold start (serverless filesystems\n // aren't persistent), and the legacy hardcoded fallback is identical across\n // every deploy that hits it — both are serious enough to fail the boot loudly\n // so the deployer notices.\n if (process.env.NODE_ENV === \"production\") {\n const sample = crypto.randomBytes(32).toString(\"hex\");\n throw new Error(\n \"[agent-native] BETTER_AUTH_SECRET is not set. This is required in production \" +\n \"so signed session cookies stay valid across deploys. Set it as a deploy \" +\n \"environment variable (any 32-byte hex string), e.g.:\\n\\n\" +\n ` BETTER_AUTH_SECRET=${sample}\\n\\n` +\n \"Generate your own with `openssl rand -hex 32`. If you already have a \" +\n \"running deploy and need to preserve existing sessions, set it to your \" +\n \"previously-deployed BETTER_AUTH_SECRET value first, then rotate to a \" +\n \"fresh one. Hosted workspace deploys may also \" +\n \"set A2A_SECRET; agent-native derives a per-purpose Better Auth secret \" +\n \"from that workspace root secret.\",\n );\n }\n\n // SECURITY (audit 09 LOW-2): the previous fallback chain\n // (`GOOGLE_CLIENT_SECRET || ACCESS_TOKEN || hardcoded`) reused\n // cross-purpose secrets and a public hardcoded literal as the cookie\n // HMAC. Dropped entirely — better to mint an ephemeral secret than to\n // re-use a Google client secret or a known string.\n const existing = readEnvLocalSecret(\n path.resolve(process.cwd(), \".env.local\"),\n );\n if (existing) return existing;\n\n if (!inMemoryDevAuthSecret) {\n inMemoryDevAuthSecret = crypto.randomBytes(32).toString(\"hex\");\n console.warn(\n \"[agent-native] BETTER_AUTH_SECRET is not configured. Using an ephemeral \" +\n \"in-memory development secret. Sessions will reset every time this \" +\n \"process restarts. Set BETTER_AUTH_SECRET in your environment to keep \" +\n \"sessions valid across restarts.\",\n );\n }\n return inMemoryDevAuthSecret;\n}\n\nfunction readEnvLocalSecret(envLocalPath: string): string | undefined {\n try {\n const content = fs.readFileSync(envLocalPath, \"utf8\");\n // Match `BETTER_AUTH_SECRET=...` on its own line. Tolerate optional\n // quotes and leading `export `. Stop at the first newline or quote.\n const m = content.match(\n /^(?:export\\s+)?BETTER_AUTH_SECRET\\s*=\\s*\"?([^\"\\r\\n]+)\"?\\s*$/m,\n );\n return m?.[1]?.trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeTrackingSlug(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n if (!trimmed) return undefined;\n const unscoped = trimmed.startsWith(\"@\")\n ? (trimmed.split(\"/\").pop() ?? trimmed)\n : trimmed;\n const slug = unscoped\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || undefined;\n}\n\nfunction knownTemplateSlug(value: string | undefined): string | undefined {\n const slug = normalizeTrackingSlug(value);\n if (!slug) return undefined;\n const withoutPrefix = slug.startsWith(\"agent-native-\")\n ? slug.slice(\"agent-native-\".length)\n : slug;\n return TEMPLATES.some((template) => template.name === withoutPrefix)\n ? withoutPrefix\n : undefined;\n}\n\nfunction readPackageName(): string | undefined {\n try {\n const pkgPath = path.join(process.cwd(), \"package.json\");\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf8\")) as {\n name?: string;\n };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\nfunction appSlugFromUrl(value: string | undefined): string | undefined {\n if (!value?.trim()) return undefined;\n try {\n const raw = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)\n ? value\n : `https://${value}`;\n const hostname = new URL(raw).hostname.toLowerCase();\n if (hostname.endsWith(\".agent-native.com\")) {\n return normalizeTrackingSlug(\n hostname.slice(0, -\".agent-native.com\".length),\n );\n }\n return normalizeTrackingSlug(hostname.split(\".\")[0]);\n } catch {\n return undefined;\n }\n}\n\n/** @internal */\nexport function resolveSignupTrackingIdentity(): {\n app?: string;\n template?: string;\n} {\n const explicitApp =\n normalizeTrackingSlug(process.env.AGENT_NATIVE_APP) ||\n normalizeTrackingSlug(process.env.VITE_AGENT_NATIVE_APP);\n const packageApp =\n normalizeTrackingSlug(process.env.npm_package_name) ||\n normalizeTrackingSlug(readPackageName());\n const urlApp =\n appSlugFromUrl(process.env.APP_URL) ||\n appSlugFromUrl(process.env.BETTER_AUTH_URL) ||\n appSlugFromUrl(process.env.URL) ||\n appSlugFromUrl(process.env.DEPLOY_URL) ||\n appSlugFromUrl(process.env.VERCEL_PROJECT_PRODUCTION_URL) ||\n appSlugFromUrl(process.env.VERCEL_URL);\n const app =\n explicitApp ||\n urlApp ||\n packageApp ||\n normalizeTrackingSlug(process.env.APP_NAME);\n\n const template =\n knownTemplateSlug(process.env.AGENT_NATIVE_TEMPLATE) ||\n knownTemplateSlug(process.env.VITE_AGENT_NATIVE_TEMPLATE) ||\n knownTemplateSlug(process.env.APP_TEMPLATE) ||\n knownTemplateSlug(process.env.VITE_APP_TEMPLATE) ||\n knownTemplateSlug(app) ||\n knownTemplateSlug(packageApp) ||\n knownTemplateSlug(urlApp);\n\n return {\n ...(app ? { app } : {}),\n ...(template ? { template } : {}),\n };\n}\n\n/** @internal */\nexport function resolveSignupTrackingProperties(): Record<string, string> {\n const identity = resolveSignupTrackingIdentity();\n return {\n ...identity,\n ...(identity.app ? { agent_native_app: identity.app } : {}),\n ...(identity.template ? { agent_native_template: identity.template } : {}),\n };\n}\n\nexport function shouldSkipEmailVerification(): boolean {\n const value = process.env.AUTH_SKIP_EMAIL_VERIFICATION;\n if (value == null) {\n return (\n process.env.NODE_ENV === \"development\" || process.env.NODE_ENV === \"test\"\n );\n }\n const normalized = value.trim().toLowerCase();\n return normalized !== \"\" && normalized !== \"0\" && normalized !== \"false\";\n}\n\n/** Read-only accessor for the resolved auth secret. */\nexport function getAuthSecret(): string {\n return resolveAuthSecret();\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** The shape we need from a Better Auth instance (internal — not exported to templates). */\nexport interface BetterAuthInstance {\n handler: (request: Request) => Promise<Response>;\n api: {\n getSession: (opts: { headers: Headers }) => Promise<{\n user: { id: string; email: string; name: string };\n session: {\n id: string;\n token: string;\n expiresAt: Date;\n };\n } | null>;\n signInEmail: (opts: {\n body: { email: string; password: string };\n }) => Promise<{ token?: string; user?: any } | null>;\n signUpEmail: (opts: {\n body: {\n email: string;\n password: string;\n name: string;\n callbackURL?: string;\n };\n headers?: Headers;\n }) => Promise<any>;\n signOut: (opts: { headers: Headers }) => Promise<any>;\n };\n}\n\nexport interface BetterAuthConfig {\n /** Base path for Better Auth routes. Default: \"/_agent-native/auth/ba\" */\n basePath?: string;\n /** Additional social providers beyond what env vars auto-detect */\n socialProviders?: BetterAuthOptions[\"socialProviders\"];\n /** Additional Better Auth plugins */\n plugins?: BetterAuthOptions[\"plugins\"];\n /**\n * Additional Google OAuth scopes (Gmail, Calendar, etc.) to request\n * up front during the primary \"Sign in with Google\" flow, beyond the\n * default identity scopes (`openid`, `email`, `profile`).\n *\n * When set, the Google social provider also opts into:\n * - `accessType: \"offline\"` — so a refresh token is issued\n * - `prompt: \"consent\"` — so the refresh token is reissued every sign-in\n *\n * Tokens are mirrored into `oauth_tokens` via a databaseHooks.account\n * hook so existing template code that reads from `oauth_tokens` (mail's\n * Gmail client, calendar's events fetcher) works without any separate\n * \"Connect Google\" page.\n */\n googleScopes?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Lazy instance\n// ---------------------------------------------------------------------------\n\nlet _auth: BetterAuthInstance | undefined;\nlet _initPromise: Promise<BetterAuthInstance> | undefined;\n// Track the Neon serverless Pool we open for Better Auth so closeBetterAuth()\n// can release it. The Pool keeps WebSocket connections open; leaking them on\n// hot-reload or process restart exhausts Neon's connection slot budget.\nlet _neonAuthPool: any;\n\nconst pgAuthSchema = {\n user: pgTable(\"user\", {\n id: pgText(\"id\").primaryKey(),\n name: pgText(\"name\").notNull(),\n email: pgText(\"email\").notNull().unique(),\n emailVerified: pgBoolean(\"email_verified\").notNull().default(false),\n image: pgText(\"image\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n session: pgTable(\"session\", {\n id: pgText(\"id\").primaryKey(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n token: pgText(\"token\").notNull().unique(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n ipAddress: pgText(\"ip_address\"),\n userAgent: pgText(\"user_agent\"),\n userId: pgText(\"user_id\").notNull(),\n activeOrganizationId: pgText(\"active_organization_id\"),\n }),\n account: pgTable(\"account\", {\n id: pgText(\"id\").primaryKey(),\n accountId: pgText(\"account_id\").notNull(),\n providerId: pgText(\"provider_id\").notNull(),\n userId: pgText(\"user_id\").notNull(),\n accessToken: pgText(\"access_token\"),\n refreshToken: pgText(\"refresh_token\"),\n idToken: pgText(\"id_token\"),\n accessTokenExpiresAt: pgTimestamp(\"access_token_expires_at\", {\n withTimezone: true,\n }),\n refreshTokenExpiresAt: pgTimestamp(\"refresh_token_expires_at\", {\n withTimezone: true,\n }),\n scope: pgText(\"scope\"),\n password: pgText(\"password\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n verification: pgTable(\"verification\", {\n id: pgText(\"id\").primaryKey(),\n identifier: pgText(\"identifier\").notNull(),\n value: pgText(\"value\").notNull(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n organization: pgTable(\"organization\", {\n id: pgText(\"id\").primaryKey(),\n name: pgText(\"name\").notNull(),\n slug: pgText(\"slug\").notNull().unique(),\n logo: pgText(\"logo\"),\n metadata: pgText(\"metadata\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n member: pgTable(\"member\", {\n id: pgText(\"id\").primaryKey(),\n organizationId: pgText(\"organization_id\").notNull(),\n userId: pgText(\"user_id\").notNull(),\n role: pgText(\"role\").notNull().default(\"member\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n invitation: pgTable(\"invitation\", {\n id: pgText(\"id\").primaryKey(),\n organizationId: pgText(\"organization_id\").notNull(),\n email: pgText(\"email\").notNull(),\n role: pgText(\"role\"),\n status: pgText(\"status\").notNull().default(\"pending\"),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n inviterId: pgText(\"inviter_id\").notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n jwks: pgTable(\"jwks\", {\n id: pgText(\"id\").primaryKey(),\n publicKey: pgText(\"public_key\").notNull(),\n privateKey: pgText(\"private_key\").notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }),\n }),\n};\n\nconst sqliteAuthSchema = {\n user: sqliteTable(\"user\", {\n id: sqliteText(\"id\").primaryKey(),\n name: sqliteText(\"name\").notNull(),\n email: sqliteText(\"email\").notNull().unique(),\n emailVerified: sqliteInteger(\"email_verified\", { mode: \"boolean\" })\n .notNull()\n .default(false),\n image: sqliteText(\"image\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n session: sqliteTable(\"session\", {\n id: sqliteText(\"id\").primaryKey(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n token: sqliteText(\"token\").notNull().unique(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n ipAddress: sqliteText(\"ip_address\"),\n userAgent: sqliteText(\"user_agent\"),\n userId: sqliteText(\"user_id\").notNull(),\n activeOrganizationId: sqliteText(\"active_organization_id\"),\n }),\n account: sqliteTable(\"account\", {\n id: sqliteText(\"id\").primaryKey(),\n accountId: sqliteText(\"account_id\").notNull(),\n providerId: sqliteText(\"provider_id\").notNull(),\n userId: sqliteText(\"user_id\").notNull(),\n accessToken: sqliteText(\"access_token\"),\n refreshToken: sqliteText(\"refresh_token\"),\n idToken: sqliteText(\"id_token\"),\n accessTokenExpiresAt: sqliteInteger(\"access_token_expires_at\", {\n mode: \"timestamp_ms\",\n }),\n refreshTokenExpiresAt: sqliteInteger(\"refresh_token_expires_at\", {\n mode: \"timestamp_ms\",\n }),\n scope: sqliteText(\"scope\"),\n password: sqliteText(\"password\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n verification: sqliteTable(\"verification\", {\n id: sqliteText(\"id\").primaryKey(),\n identifier: sqliteText(\"identifier\").notNull(),\n value: sqliteText(\"value\").notNull(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n organization: sqliteTable(\"organization\", {\n id: sqliteText(\"id\").primaryKey(),\n name: sqliteText(\"name\").notNull(),\n slug: sqliteText(\"slug\").notNull().unique(),\n logo: sqliteText(\"logo\"),\n metadata: sqliteText(\"metadata\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n member: sqliteTable(\"member\", {\n id: sqliteText(\"id\").primaryKey(),\n organizationId: sqliteText(\"organization_id\").notNull(),\n userId: sqliteText(\"user_id\").notNull(),\n role: sqliteText(\"role\").notNull().default(\"member\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n invitation: sqliteTable(\"invitation\", {\n id: sqliteText(\"id\").primaryKey(),\n organizationId: sqliteText(\"organization_id\").notNull(),\n email: sqliteText(\"email\").notNull(),\n role: sqliteText(\"role\"),\n status: sqliteText(\"status\").notNull().default(\"pending\"),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n inviterId: sqliteText(\"inviter_id\").notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n jwks: sqliteTable(\"jwks\", {\n id: sqliteText(\"id\").primaryKey(),\n publicKey: sqliteText(\"public_key\").notNull(),\n privateKey: sqliteText(\"private_key\").notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }),\n }),\n};\n\n/**\n * Mirror a Better Auth `account` row for Google into the `oauth_tokens`\n * table that template code (mail's Gmail client, calendar's events fetcher)\n * reads from. Called from the `databaseHooks.account.create.after` and\n * `.update.after` hooks so tokens captured during the primary \"Sign in\n * with Google\" flow flow straight to the apps that need them — no\n * separate \"Connect Google\" page required.\n *\n * Resolves `account.userId` to the user's email by querying the `user`\n * table (Better Auth always quotes \"user\" because it's a reserved word\n * in Postgres; SQLite accepts the quotes too).\n *\n * The hook is fire-and-forget from the caller's perspective — every\n * failure is caught upstream so a flake in `oauth_tokens` never blocks\n * sign-in. We still no-op on missing fields here as a defense in depth.\n */\nasync function mirrorGoogleAccountToOAuthTokens(account: {\n providerId?: string;\n userId?: string;\n accountId?: string;\n accessToken?: string | null;\n refreshToken?: string | null;\n accessTokenExpiresAt?: Date | string | number | null;\n scope?: string | null;\n idToken?: string | null;\n}): Promise<void> {\n if (!account || account.providerId !== \"google\") return;\n if (!account.userId) return;\n\n const accessToken = account.accessToken ?? undefined;\n if (!accessToken) {\n // Better Auth sometimes upserts an account row before tokens are\n // attached (e.g. linking flows). Nothing to mirror yet — the next\n // update hook will run once the access token lands.\n return;\n }\n\n // Resolve user email from userId.\n const db = getDbExec();\n let email: string | undefined;\n try {\n const { rows } = await db.execute({\n sql: 'SELECT email FROM \"user\" WHERE id = ?',\n args: [account.userId],\n });\n email = (rows[0]?.email as string | undefined) ?? undefined;\n } catch (err) {\n console.error(\n \"[auth] mirror Google tokens: failed to resolve user email from userId\",\n err,\n );\n return;\n }\n if (!email) return;\n\n // Normalise expiry to epoch ms (Google's \"expiry_date\" convention used\n // throughout the templates).\n let expiryDate: number | undefined;\n const raw = account.accessTokenExpiresAt;\n if (raw instanceof Date) {\n expiryDate = raw.getTime();\n } else if (typeof raw === \"number\") {\n expiryDate = raw;\n } else if (typeof raw === \"string\") {\n const ms = Date.parse(raw);\n expiryDate = Number.isFinite(ms) ? ms : undefined;\n }\n\n const tokens: Record<string, unknown> = {\n access_token: accessToken,\n token_type: \"Bearer\",\n };\n if (account.refreshToken) tokens.refresh_token = account.refreshToken;\n if (expiryDate) tokens.expiry_date = expiryDate;\n if (account.scope) tokens.scope = account.scope;\n if (account.idToken) tokens.id_token = account.idToken;\n\n await saveOAuthTokens(\"google\", email, tokens, email);\n}\n\nasync function ensureBetterAuthTables(): Promise<void> {\n const db = getDbExec();\n\n // PG guard: probe information_schema first (no lock) for each table; run\n // DDL only when missing, bounded by a transaction-scoped lock_timeout.\n // Probe names are UNQUOTED (what information_schema.tables.table_name stores);\n // createSql keeps the QUOTED \"user\"/\"session\"/… form required by Postgres.\n if (isPostgres()) {\n const pgTables: Array<[name: string, createSql: string]> = [\n [\n \"user\",\n `CREATE TABLE IF NOT EXISTS \"user\" (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, email_verified BOOLEAN NOT NULL DEFAULT FALSE, image TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"session\",\n `CREATE TABLE IF NOT EXISTS \"session\" (id TEXT PRIMARY KEY, expires_at TIMESTAMPTZ NOT NULL, token TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, ip_address TEXT, user_agent TEXT, user_id TEXT NOT NULL, active_organization_id TEXT)`,\n ],\n [\n \"account\",\n `CREATE TABLE IF NOT EXISTS \"account\" (id TEXT PRIMARY KEY, account_id TEXT NOT NULL, provider_id TEXT NOT NULL, user_id TEXT NOT NULL, access_token TEXT, refresh_token TEXT, id_token TEXT, access_token_expires_at TIMESTAMPTZ, refresh_token_expires_at TIMESTAMPTZ, scope TEXT, password TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"verification\",\n `CREATE TABLE IF NOT EXISTS \"verification\" (id TEXT PRIMARY KEY, identifier TEXT NOT NULL, value TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"organization\",\n `CREATE TABLE IF NOT EXISTS \"organization\" (id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT NOT NULL UNIQUE, logo TEXT, metadata TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"member\",\n `CREATE TABLE IF NOT EXISTS \"member\" (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"invitation\",\n `CREATE TABLE IF NOT EXISTS \"invitation\" (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, email TEXT NOT NULL, role TEXT, status TEXT NOT NULL DEFAULT 'pending', expires_at TIMESTAMPTZ NOT NULL, inviter_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"jwks\",\n `CREATE TABLE IF NOT EXISTS \"jwks\" (id TEXT PRIMARY KEY, public_key TEXT NOT NULL, private_key TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ)`,\n ],\n ];\n for (const [name, sql] of pgTables) await ensureTableExists(name, sql);\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n const sqliteStatements = [\n `CREATE TABLE IF NOT EXISTS user (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, email_verified INTEGER NOT NULL DEFAULT 0, image TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS session (id TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, token TEXT NOT NULL UNIQUE, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, ip_address TEXT, user_agent TEXT, user_id TEXT NOT NULL, active_organization_id TEXT)`,\n `CREATE TABLE IF NOT EXISTS account (id TEXT PRIMARY KEY, account_id TEXT NOT NULL, provider_id TEXT NOT NULL, user_id TEXT NOT NULL, access_token TEXT, refresh_token TEXT, id_token TEXT, access_token_expires_at INTEGER, refresh_token_expires_at INTEGER, scope TEXT, password TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS verification (id TEXT PRIMARY KEY, identifier TEXT NOT NULL, value TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS organization (id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT NOT NULL UNIQUE, logo TEXT, metadata TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS member (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS invitation (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, email TEXT NOT NULL, role TEXT, status TEXT NOT NULL DEFAULT 'pending', expires_at INTEGER NOT NULL, inviter_id TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS jwks (id TEXT PRIMARY KEY, public_key TEXT NOT NULL, private_key TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER)`,\n ];\n for (const sql of sqliteStatements) await db.execute(sql);\n}\n\n/**\n * Get or create the Better Auth instance.\n * Lazily initialized on first call — the database must be reachable by then.\n */\nexport async function getBetterAuth(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInstance> {\n if (_auth) return _auth;\n if (_initPromise) return _initPromise;\n\n _initPromise = createBetterAuthInstance(config);\n _auth = await _initPromise;\n return _auth;\n}\n\n/**\n * Synchronous getter — returns the instance if already initialized, else undefined.\n * Use this in hot paths where you know init has already happened.\n */\nexport function getBetterAuthSync(): BetterAuthInstance | undefined {\n return _auth;\n}\n\n/**\n * The subset of Better Auth's internal adapter we use for federated-SSO\n * JIT account linking. Better Auth owns these writes (id + timestamp +\n * schema handling), so callers never hand-roll SQL against `user`/`account`.\n * Read-only lookups + strictly-additive `linkAccount`/`createUser` only — no\n * update/delete of existing identity rows.\n */\nexport interface BetterAuthInternalAdapter {\n findUserByEmail: (\n email: string,\n options?: { includeAccounts: boolean },\n ) => Promise<{\n user: { id: string; email: string; name?: string };\n accounts: Array<{ providerId: string; accountId: string }>;\n } | null>;\n linkAccount: (account: {\n userId: string;\n providerId: string;\n accountId: string;\n }) => Promise<unknown>;\n createUser: (user: {\n email: string;\n name: string;\n emailVerified?: boolean;\n }) => Promise<{ id: string }>;\n}\n\n/**\n * Resolve Better Auth's internal adapter via the live instance's\n * `$context`. The framework's narrowed `BetterAuthInstance` interface omits\n * `$context`, but the underlying object created by `betterAuth(...)` always\n * exposes it (see Better Auth's `Auth` type) — so this is a safe, typed\n * accessor for the federated-SSO client. Returns `undefined` if the context\n * shape is unexpected (older/newer Better Auth) so callers can fall back.\n */\nexport async function getBetterAuthInternalAdapter(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInternalAdapter | undefined> {\n const auth = (await getBetterAuth(config)) as unknown as {\n $context?: Promise<{ internalAdapter?: BetterAuthInternalAdapter }>;\n };\n try {\n const ctx = await auth.$context;\n const ia = ctx?.internalAdapter;\n if (\n ia &&\n typeof ia.findUserByEmail === \"function\" &&\n typeof ia.linkAccount === \"function\" &&\n typeof ia.createUser === \"function\"\n ) {\n return ia;\n }\n } catch {\n // Context resolution failed — caller falls back to the signup path.\n }\n return undefined;\n}\n\n/** Reset for testing */\nexport async function resetBetterAuth(): Promise<void> {\n _auth = undefined;\n _initPromise = undefined;\n if (_neonAuthPool) {\n try {\n await _neonAuthPool.end();\n } catch {\n // Pool may have already closed (process exiting, etc.) — don't block reset.\n }\n _neonAuthPool = undefined;\n }\n await closePgliteClients();\n}\n\n// ---------------------------------------------------------------------------\n// Instance creation\n// ---------------------------------------------------------------------------\n\nasync function createBetterAuthInstance(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInstance> {\n const dialect = getDialect();\n const basePath = config?.basePath ?? \"/_agent-native/auth/ba\";\n await ensureBetterAuthTables();\n\n // Build social providers from env vars\n const socialProviders: BetterAuthOptions[\"socialProviders\"] = {\n ...config?.socialProviders,\n };\n\n const extraScopes = config?.googleScopes ?? [];\n const googleCredentials =\n extraScopes.length > 0\n ? process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET\n ? {\n clientId: process.env.GOOGLE_CLIENT_ID,\n clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n }\n : null\n : resolveGoogleSignInCredentials();\n if (googleCredentials) {\n // When the template requests broader scopes (Gmail, Calendar, etc.)\n // ask for them on the primary sign-in flow so a separate \"Connect\n // Google\" round-trip isn't needed. `accessType: \"offline\"` plus\n // `prompt: \"consent\"` ensures we always receive a refresh token back —\n // Google only re-issues a refresh token on consent, so re-signing in\n // (e.g. after switching machines) would otherwise leave us with an\n // access token that can't be refreshed.\n const baseScopes = [\"openid\", \"email\", \"profile\"];\n const mergedScopes = Array.from(new Set([...baseScopes, ...extraScopes]));\n socialProviders.google = {\n clientId: googleCredentials.clientId,\n clientSecret: googleCredentials.clientSecret,\n ...(extraScopes.length > 0\n ? {\n scope: mergedScopes,\n accessType: \"offline\" as const,\n prompt: \"consent\" as const,\n }\n : {}),\n };\n }\n\n if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {\n socialProviders.github = {\n clientId: process.env.GITHUB_CLIENT_ID,\n clientSecret: process.env.GITHUB_CLIENT_SECRET,\n };\n }\n\n // Build database config\n const database = await buildDatabaseConfig(dialect);\n\n const secret = resolveAuthSecret();\n\n const appUrl = getAppProductionUrl();\n const cookieNamespace = resolveAuthCookieNamespace();\n const requireEmailVerification =\n (await isEmailConfigured()) && !shouldSkipEmailVerification();\n\n const shouldMirrorGoogleAccountTokens =\n (config?.googleScopes?.length ?? 0) > 0;\n\n const auth = betterAuth({\n basePath,\n baseURL: appUrl,\n database,\n secret,\n emailAndPassword: {\n enabled: true,\n minPasswordLength: 8,\n // Only require email verification when an email provider is configured.\n // Without a provider, verification emails can't be sent, so requiring\n // verification would lock users out of signup entirely. Local dev/test\n // skip verification by default so +qa accounts can be created quickly;\n // hosted QA deployments can opt out with AUTH_SKIP_EMAIL_VERIFICATION=1.\n requireEmailVerification,\n sendResetPassword: async ({ user, token }) => {\n // APP_BASE_PATH lets this app mount under a prefix (e.g. /mail). The\n // reset link must include that prefix so the page resolves correctly.\n const appBasePath = (\n process.env.VITE_APP_BASE_PATH ||\n process.env.APP_BASE_PATH ||\n \"\"\n ).replace(/\\/$/, \"\");\n const resetUrl = `${appUrl}${appBasePath}/_agent-native/auth/reset?token=${encodeURIComponent(token)}`;\n const { subject, html, text } = renderResetPasswordEmail({\n email: user.email,\n resetUrl,\n });\n await sendEmail({ to: user.email, subject, html, text });\n },\n },\n emailVerification: {\n // Fire verification email right after signup, before the user has a\n // session — pairs with requireEmailVerification above. Only enabled\n // when an email provider is configured.\n sendOnSignUp: requireEmailVerification,\n // Auto-create a session once the user clicks the link. Without this,\n // verified users would have to go back and sign in manually, which is\n // a confusing dead-end on the verify screen.\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n // APP_BASE_PATH lets this app mount under a prefix (e.g. /mail). The\n // verification link must include that prefix so the page resolves correctly.\n const verifyBasePath = (\n process.env.VITE_APP_BASE_PATH ||\n process.env.APP_BASE_PATH ||\n \"\"\n ).replace(/\\/$/, \"\");\n const verifyUrl = verifyBasePath\n ? url.replace(/(\\/\\/[^/]+)(\\/)/, `$1${verifyBasePath}$2`)\n : url;\n const { subject, html, text } = renderVerifySignupEmail({\n email: user.email,\n verifyUrl,\n });\n await sendEmail({ to: user.email, subject, html, text });\n },\n },\n socialProviders,\n account: {\n // Merge accounts when a user signs in with a social provider using an\n // email that already has a local email/password account (or vice versa).\n // Only providers listed in `trustedProviders` auto-link — these are the\n // ones that verify emails at the identity layer. Never add a provider\n // here that lets users claim an unverified email; that would be an\n // account-takeover vector.\n accountLinking: {\n enabled: true,\n trustedProviders: [\"google\", \"github\"],\n },\n },\n databaseHooks: {\n user: {\n create: {\n after: async (\n user: {\n id?: string;\n email?: string;\n name?: string | null;\n },\n // Better Auth (1.6.x) passes the endpoint context as the 2nd arg.\n // It carries the originating request's headers (and on OAuth\n // signups the callback request's headers), which is where the\n // browser's `an_ft` first-touch cookie rides in.\n context?: {\n headers?: Headers | null;\n request?: { headers?: Headers | null } | null;\n } | null,\n ) => {\n // When a newly-created user's email has pending org invitations\n // (common when someone is invited *before* they've signed up),\n // auto-accept them so the user lands in the org on their very\n // first page load instead of a blank-slate workspace.\n const email = user?.email;\n if (!email) return;\n // Derive first-touch referral attribution from the request's\n // cookie header. Never let attribution parsing throw or block\n // signup — on any error fall back to `direct`.\n let attribution: Record<string, string> | undefined;\n try {\n const cookieHeader =\n context?.headers?.get(\"cookie\") ??\n context?.request?.headers?.get(\"cookie\") ??\n null;\n attribution = signupAttributionFromCookieHeader(cookieHeader);\n } catch (err) {\n console.error(\"[auth] failed to derive signup attribution\", err);\n attribution = undefined;\n }\n await trackSignupEvent({\n authProvider: \"better-auth\",\n authUserId: user.id,\n email,\n name: user.name,\n attribution,\n });\n try {\n await acceptPendingInvitationsForEmail(email);\n } catch (err) {\n // Never block signup on invite bookkeeping — log and continue.\n console.error(\n \"[auth] failed to auto-accept pending invitations\",\n err,\n );\n }\n try {\n // Auto-join orgs whose `allowed_domain` matches this email\n // domain. Lets a fresh `@builder.io` (or any org-domain)\n // signup land inside the company org on first page load\n // without going through the picker. No-ops when no match.\n await autoJoinDomainMatchingOrgs(email);\n } catch (err) {\n console.error(\n \"[auth] failed to auto-join domain-matching orgs\",\n err,\n );\n }\n },\n },\n },\n account: {\n // Mirror Google account tokens into `oauth_tokens` so existing\n // template code (mail's Gmail client, calendar's events fetcher)\n // can pick up Gmail/Calendar credentials from the primary sign-in\n // flow — no separate \"Set up Google\" page required.\n //\n // Better Auth fires `create` for first-time social sign-in and\n // `update` whenever a session re-issues tokens (e.g., the user\n // re-signs in to refresh the token). Both branches do the same\n // mirroring work; failures never block sign-in.\n create: {\n after: async (account: any) => {\n if (!shouldMirrorGoogleAccountTokens) return;\n await mirrorGoogleAccountToOAuthTokens(account).catch((err) => {\n console.error(\n \"[auth] failed to mirror Google account tokens to oauth_tokens (create)\",\n err,\n );\n });\n },\n },\n update: {\n after: async (account: any) => {\n if (!shouldMirrorGoogleAccountTokens) return;\n await mirrorGoogleAccountToOAuthTokens(account).catch((err) => {\n console.error(\n \"[auth] failed to mirror Google account tokens to oauth_tokens (update)\",\n err,\n );\n });\n },\n },\n },\n },\n session: {\n expiresIn: 60 * 60 * 24 * 30, // 30 days\n updateAge: 60 * 60 * 24, // refresh daily\n cookieCache: {\n enabled: true,\n maxAge: 5 * 60, // 5 min cache\n },\n },\n advanced: {\n cookiePrefix: cookieNamespace.betterAuthCookiePrefix,\n // Emit `SameSite=None; Secure` when the app is served over HTTPS so\n // session cookies are delivered inside third-party iframes (e.g. the\n // Builder.io editor). Plain-HTTP dev keeps the default (Lax) because\n // `SameSite=None` requires Secure.\n ...(appUrl.startsWith(\"https://\")\n ? {\n defaultCookieAttributes: {\n sameSite: \"none\" as const,\n secure: true,\n partitioned: true,\n },\n }\n : {}),\n // When an effective shared cookie domain is set, share Better Auth's\n // session cookie across that domain. First-party `*.agent-native.com`\n // apps intentionally do not use this path because their auth DBs are\n // separate; Dispatch identity federation handles cross-app sign-in.\n ...(cookieNamespace.betterAuthCookieDomain\n ? {\n crossSubDomainCookies: {\n enabled: true,\n domain: cookieNamespace.betterAuthCookieDomain,\n },\n }\n : {}),\n },\n plugins: [\n // JWT: issue tokens for A2A calls, JWKS endpoint for verification\n jwt({\n jwt: {\n issuer: appUrl,\n expirationTime: \"15m\",\n },\n }),\n // Bearer: accept Bearer tokens on API requests\n bearer(),\n ...(config?.plugins ?? []),\n ],\n });\n\n return auth as unknown as BetterAuthInstance;\n}\n\nasync function buildDatabaseConfig(\n dialect: string,\n): Promise<BetterAuthOptions[\"database\"]> {\n if (dialect === \"postgres\") {\n const url = getDatabaseUrl();\n const {\n buildResilientNeonPool,\n buildResilientPostgresJsClient,\n isNeonUrl,\n } = await import(\"../db/create-get-db.js\");\n\n if (isPgliteUrl(url)) {\n const { drizzle } = await loadPgliteDrizzle();\n const client = await getPgliteClient(url);\n const db = drizzle({ client, schema: pgAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // Neon via @neondatabase/serverless (WebSockets over HTTPS). postgres-js\n // opens a raw TCP connection on port 5432 which frequently times out on\n // Netlify Functions / Vercel / CF Workers when Neon's pooler is cold.\n if (isNeonUrl(url)) {\n const { Pool } = await import(\"@neondatabase/serverless\");\n // Cap the auth pool the same way as the app pool. Better Auth runs a\n // session lookup on essentially every authenticated request, so an\n // un-capped pool here is a primary contributor to \"Max client\n // connections reached\" across concurrent serverless instances.\n _neonAuthPool = new Pool({\n connectionString: url,\n max: neonPoolMax(),\n });\n attachNeonPoolErrorLogger(_neonAuthPool, \"db/neon-auth\");\n const { drizzle } = await import(\"drizzle-orm/neon-serverless\");\n const db = drizzle(buildResilientNeonPool(_neonAuthPool), {\n schema: pgAuthSchema,\n });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // Non-Neon Postgres (Supabase, self-hosted, etc.) → postgres-js.\n // pgPoolOptions caps this pool to a small size on serverless. Better Auth\n // runs a session lookup on essentially every authenticated request, so an\n // un-capped pool here is a primary contributor to \"Max client connections\n // reached\" across concurrent serverless instances.\n const { default: postgres } = await import(\"postgres\");\n const sql = postgres(url, pgPoolOptions(url));\n const { drizzle } = await import(\"drizzle-orm/postgres-js\");\n const db = drizzle(buildResilientPostgresJsClient(sql), {\n schema: pgAuthSchema,\n });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // SQLite / libsql\n const url = getDatabaseUrl(\"file:./data/app.db\");\n\n if (url.startsWith(\"file:\") || !url.includes(\"://\")) {\n // Local SQLite via better-sqlite3\n const { default: Database } = await import(\"better-sqlite3\");\n const filePath = url.replace(/^file:/, \"\");\n const sqlite = new Database(filePath);\n sqlite.pragma(\"journal_mode = WAL\");\n const { drizzle } = await import(\"drizzle-orm/better-sqlite3\");\n const db = drizzle(sqlite, { schema: sqliteAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"sqlite\",\n schema: sqliteAuthSchema,\n });\n }\n\n // Remote libsql (Turso). Use the web client to avoid serverless bundles\n // depending on libsql's platform-specific native packages.\n const { createClient } = await import(\"@libsql/client/web\");\n const client = createClient({ url, authToken: getDatabaseAuthToken() });\n const { drizzle } = await import(\"drizzle-orm/libsql/web\");\n const db = drizzle(client, { schema: sqliteAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"sqlite\",\n schema: sqliteAuthSchema,\n });\n}\n"]}
1
+ {"version":3,"file":"better-auth-instance.js","sourceRoot":"","sources":["../../src/server/better-auth-instance.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,UAAU,EAA0B,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EACL,OAAO,EACP,IAAI,IAAI,MAAM,EACd,SAAS,IAAI,WAAW,EACxB,OAAO,IAAI,SAAS,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,WAA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gB,EAAE,CAAC,CAAC;IACzD,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;IACxE,OAAO,cAAc,CAAC,EAAE,EAAE;QACxB,QAAQ,EAAE,QAAQ;QAClB,MAAM,EAAE,gBAAgB;KACzB,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Internal Better Auth instance — lazily created, not exported to templates.\n *\n * Templates interact with auth via the existing `getSession()`, `autoMountAuth()`,\n * `createAuthPlugin()`, and `createGoogleAuthPlugin()` APIs. Better Auth is an\n * implementation detail behind those interfaces.\n */\n\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { betterAuth, type BetterAuthOptions } from \"better-auth\";\nimport { bearer } from \"better-auth/plugins/bearer\";\nimport { jwt } from \"better-auth/plugins/jwt\";\nimport {\n pgTable,\n text as pgText,\n timestamp as pgTimestamp,\n boolean as pgBoolean,\n} from \"drizzle-orm/pg-core\";\nimport {\n sqliteTable,\n text as sqliteText,\n integer as sqliteInteger,\n} from \"drizzle-orm/sqlite-core\";\n\nimport { TEMPLATES } from \"../cli/templates-meta.js\";\nimport { getDbExec, isPostgres } from \"../db/client.js\";\nimport {\n getDialect,\n getDatabaseUrl,\n getDatabaseAuthToken,\n closePgliteClients,\n getPgliteClient,\n isPgliteUrl,\n loadPgliteDrizzle,\n pgPoolOptions,\n neonPoolMax,\n attachNeonPoolErrorLogger,\n} from \"../db/client.js\";\nimport { ensureTableExists } from \"../db/ddl-guard.js\";\nimport { saveOAuthTokens } from \"../oauth-tokens/store.js\";\nimport { acceptPendingInvitationsForEmail } from \"../org/accept-pending.js\";\nimport { autoJoinDomainMatchingOrgs } from \"../org/auto-join-domain.js\";\nimport { flushTracking, identify, track } from \"../tracking/index.js\";\nimport { getAppProductionUrl } from \"./app-url.js\";\nimport { signupAttributionFromCookieHeader } from \"./attribution.js\";\nimport { resolveAuthCookieNamespace } from \"./cookie-namespace.js\";\nimport { getWorkspaceA2ADerivedSecret } from \"./derived-secret.js\";\nimport {\n renderResetPasswordEmail,\n renderVerifySignupEmail,\n} from \"./email-templates.js\";\nimport { sendEmail, isEmailConfigured } from \"./email.js\";\nimport { resolveGoogleSignInCredentials } from \"./google-oauth-credentials.js\";\n\nasync function flushSignupTracking(): Promise<void> {\n try {\n await Promise.race([\n flushTracking(),\n new Promise<void>((resolve) => setTimeout(resolve, 1500)),\n ]);\n } catch {\n // Signup should never fail because analytics delivery did.\n }\n}\n\nexport async function hasBetterAuthUserEmail(email: string): Promise<boolean> {\n const adapter = await getBetterAuthInternalAdapter().catch(() => undefined);\n if (!adapter) return false;\n const existing = await adapter\n .findUserByEmail(email, { includeAccounts: false })\n .catch(() => null);\n return !!existing?.user?.email;\n}\n\nexport async function trackSignupEvent({\n authProvider,\n authUserId,\n email,\n name,\n attribution,\n}: {\n authProvider: string;\n authUserId?: string;\n email: string;\n name?: string | null;\n /**\n * First-touch referral attribution derived from the visitor's `an_ft`\n * cookie (see `server/attribution.ts`). Snake_case keys such as\n * `referral_source`, `referrer_user`, and the UTM passthrough are merged\n * into the `signup` event so we can measure where new users came from.\n * `undefined` values are dropped; a missing object is a clean no-op.\n */\n attribution?: Record<string, string | undefined>;\n}): Promise<void> {\n identify(email, {\n email,\n name: name ?? undefined,\n authUserId,\n });\n const cleanAttribution: Record<string, string> = {};\n if (attribution) {\n for (const [key, value] of Object.entries(attribution)) {\n if (typeof value === \"string\" && value.length > 0) {\n cleanAttribution[key] = value;\n }\n }\n }\n track(\n \"signup\",\n {\n ...resolveSignupTrackingProperties(),\n auth_provider: authProvider,\n ...(authUserId ? { auth_user_id: authUserId } : {}),\n ...cleanAttribution,\n },\n { userId: email },\n );\n await flushSignupTracking();\n}\n\n// ---------------------------------------------------------------------------\n// Persistent auth secret\n// ---------------------------------------------------------------------------\n\nlet inMemoryDevAuthSecret: string | undefined;\n\n/**\n * Resolve the Better Auth signing secret.\n *\n * Resolution order:\n * 1. `BETTER_AUTH_SECRET` env var — explicit, recommended for prod.\n * 2. Hosted workspace deploys can derive a per-purpose secret from the\n * already-required `A2A_SECRET` root. This keeps fresh workspace branches\n * bootable without reusing the raw A2A key as a cookie-signing key.\n * 3. Existing `.env.local` values in the template cwd — read-only\n * compatibility for projects that already configured this secret.\n * 4. Generate a per-process in-memory random 32-byte hex in development.\n *\n * Why this matters: before this helper existed, missing `BETTER_AUTH_SECRET`\n * fell through to `GOOGLE_CLIENT_SECRET` / `ACCESS_TOKEN` / a hardcoded\n * string. If a template happened to have none of those, each dev-server\n * boot would re-fall back to the hardcoded value (still stable) — but\n * rotating Google credentials, toggling `ACCESS_TOKEN`, or churning the\n * fallback chain would invalidate every signed cookie and force everyone\n * to sign in again. We still read explicit env configuration, but never\n * auto-write a generated secret into env files.\n */\nfunction resolveAuthSecret(): string {\n if (process.env.BETTER_AUTH_SECRET) return process.env.BETTER_AUTH_SECRET;\n const workspaceDerivedSecret = getWorkspaceA2ADerivedSecret(\"better-auth\");\n if (workspaceDerivedSecret) return workspaceDerivedSecret;\n\n // In production, beyond the workspace A2A-derived fallback above, never\n // auto-generate or use legacy fallbacks. A generated secret invalidates every\n // signed session cookie on the next cold start (serverless filesystems\n // aren't persistent), and the legacy hardcoded fallback is identical across\n // every deploy that hits it — both are serious enough to fail the boot loudly\n // so the deployer notices.\n if (process.env.NODE_ENV === \"production\") {\n const sample = crypto.randomBytes(32).toString(\"hex\");\n throw new Error(\n \"[agent-native] BETTER_AUTH_SECRET is not set. This is required in production \" +\n \"so signed session cookies stay valid across deploys. Set it as a deploy \" +\n \"environment variable (any 32-byte hex string), e.g.:\\n\\n\" +\n ` BETTER_AUTH_SECRET=${sample}\\n\\n` +\n \"Generate your own with `openssl rand -hex 32`. If you already have a \" +\n \"running deploy and need to preserve existing sessions, set it to your \" +\n \"previously-deployed BETTER_AUTH_SECRET value first, then rotate to a \" +\n \"fresh one. Hosted workspace deploys may also \" +\n \"set A2A_SECRET; agent-native derives a per-purpose Better Auth secret \" +\n \"from that workspace root secret.\",\n );\n }\n\n // SECURITY (audit 09 LOW-2): the previous fallback chain\n // (`GOOGLE_CLIENT_SECRET || ACCESS_TOKEN || hardcoded`) reused\n // cross-purpose secrets and a public hardcoded literal as the cookie\n // HMAC. Dropped entirely — better to mint an ephemeral secret than to\n // re-use a Google client secret or a known string.\n const existing = readEnvLocalSecret(\n path.resolve(process.cwd(), \".env.local\"),\n );\n if (existing) return existing;\n\n if (!inMemoryDevAuthSecret) {\n inMemoryDevAuthSecret = crypto.randomBytes(32).toString(\"hex\");\n console.warn(\n \"[agent-native] BETTER_AUTH_SECRET is not configured. Using an ephemeral \" +\n \"in-memory development secret. Sessions will reset every time this \" +\n \"process restarts. Set BETTER_AUTH_SECRET in your environment to keep \" +\n \"sessions valid across restarts.\",\n );\n }\n return inMemoryDevAuthSecret;\n}\n\nfunction readEnvLocalSecret(envLocalPath: string): string | undefined {\n try {\n const content = fs.readFileSync(envLocalPath, \"utf8\");\n // Match `BETTER_AUTH_SECRET=...` on its own line. Tolerate optional\n // quotes and leading `export `. Stop at the first newline or quote.\n const m = content.match(\n /^(?:export\\s+)?BETTER_AUTH_SECRET\\s*=\\s*\"?([^\"\\r\\n]+)\"?\\s*$/m,\n );\n return m?.[1]?.trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeTrackingSlug(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n if (!trimmed) return undefined;\n const unscoped = trimmed.startsWith(\"@\")\n ? (trimmed.split(\"/\").pop() ?? trimmed)\n : trimmed;\n const slug = unscoped\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug || undefined;\n}\n\nfunction knownTemplateSlug(value: string | undefined): string | undefined {\n const slug = normalizeTrackingSlug(value);\n if (!slug) return undefined;\n const withoutPrefix = slug.startsWith(\"agent-native-\")\n ? slug.slice(\"agent-native-\".length)\n : slug;\n return TEMPLATES.some((template) => template.name === withoutPrefix)\n ? withoutPrefix\n : undefined;\n}\n\nfunction readPackageName(): string | undefined {\n try {\n const pkgPath = path.join(process.cwd(), \"package.json\");\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf8\")) as {\n name?: string;\n };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\nfunction appSlugFromUrl(value: string | undefined): string | undefined {\n if (!value?.trim()) return undefined;\n try {\n const raw = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)\n ? value\n : `https://${value}`;\n const hostname = new URL(raw).hostname.toLowerCase();\n if (hostname.endsWith(\".agent-native.com\")) {\n return normalizeTrackingSlug(\n hostname.slice(0, -\".agent-native.com\".length),\n );\n }\n return normalizeTrackingSlug(hostname.split(\".\")[0]);\n } catch {\n return undefined;\n }\n}\n\n/** @internal */\nexport function resolveSignupTrackingIdentity(): {\n app?: string;\n template?: string;\n} {\n const explicitApp =\n normalizeTrackingSlug(process.env.AGENT_NATIVE_APP) ||\n normalizeTrackingSlug(process.env.VITE_AGENT_NATIVE_APP);\n const packageApp =\n normalizeTrackingSlug(process.env.npm_package_name) ||\n normalizeTrackingSlug(readPackageName());\n const urlApp =\n appSlugFromUrl(process.env.APP_URL) ||\n appSlugFromUrl(process.env.BETTER_AUTH_URL) ||\n appSlugFromUrl(process.env.URL) ||\n appSlugFromUrl(process.env.DEPLOY_URL) ||\n appSlugFromUrl(process.env.VERCEL_PROJECT_PRODUCTION_URL) ||\n appSlugFromUrl(process.env.VERCEL_URL);\n const app =\n explicitApp ||\n urlApp ||\n packageApp ||\n normalizeTrackingSlug(process.env.APP_NAME);\n\n const template =\n knownTemplateSlug(process.env.AGENT_NATIVE_TEMPLATE) ||\n knownTemplateSlug(process.env.VITE_AGENT_NATIVE_TEMPLATE) ||\n knownTemplateSlug(process.env.APP_TEMPLATE) ||\n knownTemplateSlug(process.env.VITE_APP_TEMPLATE) ||\n knownTemplateSlug(app) ||\n knownTemplateSlug(packageApp) ||\n knownTemplateSlug(urlApp);\n\n return {\n ...(app ? { app } : {}),\n ...(template ? { template } : {}),\n };\n}\n\n/** @internal */\nexport function resolveSignupTrackingProperties(): Record<string, string> {\n const identity = resolveSignupTrackingIdentity();\n return {\n ...identity,\n ...(identity.app ? { agent_native_app: identity.app } : {}),\n ...(identity.template ? { agent_native_template: identity.template } : {}),\n };\n}\n\nexport function shouldSkipEmailVerification(): boolean {\n const value = process.env.AUTH_SKIP_EMAIL_VERIFICATION;\n if (value == null) {\n const deployContext =\n process.env.AGENT_NATIVE_BUILD_DEPLOY_CONTEXT || process.env.CONTEXT;\n return (\n process.env.NODE_ENV === \"development\" ||\n process.env.NODE_ENV === \"test\" ||\n deployContext === \"deploy-preview\"\n );\n }\n const normalized = value.trim().toLowerCase();\n return normalized !== \"\" && normalized !== \"0\" && normalized !== \"false\";\n}\n\n/** Read-only accessor for the resolved auth secret. */\nexport function getAuthSecret(): string {\n return resolveAuthSecret();\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** The shape we need from a Better Auth instance (internal — not exported to templates). */\nexport interface BetterAuthInstance {\n handler: (request: Request) => Promise<Response>;\n api: {\n getSession: (opts: { headers: Headers }) => Promise<{\n user: { id: string; email: string; name: string };\n session: {\n id: string;\n token: string;\n expiresAt: Date;\n };\n } | null>;\n signInEmail: (opts: {\n body: { email: string; password: string };\n }) => Promise<{ token?: string; user?: any } | null>;\n signUpEmail: (opts: {\n body: {\n email: string;\n password: string;\n name: string;\n callbackURL?: string;\n };\n headers?: Headers;\n }) => Promise<any>;\n signOut: (opts: { headers: Headers }) => Promise<any>;\n };\n}\n\nexport interface BetterAuthConfig {\n /** Base path for Better Auth routes. Default: \"/_agent-native/auth/ba\" */\n basePath?: string;\n /** Additional social providers beyond what env vars auto-detect */\n socialProviders?: BetterAuthOptions[\"socialProviders\"];\n /** Additional Better Auth plugins */\n plugins?: BetterAuthOptions[\"plugins\"];\n /**\n * Additional Google OAuth scopes (Gmail, Calendar, etc.) to request\n * up front during the primary \"Sign in with Google\" flow, beyond the\n * default identity scopes (`openid`, `email`, `profile`).\n *\n * When set, the Google social provider also opts into:\n * - `accessType: \"offline\"` — so a refresh token is issued\n * - `prompt: \"consent\"` — so the refresh token is reissued every sign-in\n *\n * Tokens are mirrored into `oauth_tokens` via a databaseHooks.account\n * hook so existing template code that reads from `oauth_tokens` (mail's\n * Gmail client, calendar's events fetcher) works without any separate\n * \"Connect Google\" page.\n */\n googleScopes?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Lazy instance\n// ---------------------------------------------------------------------------\n\nlet _auth: BetterAuthInstance | undefined;\nlet _initPromise: Promise<BetterAuthInstance> | undefined;\n// Track the Neon serverless Pool we open for Better Auth so closeBetterAuth()\n// can release it. The Pool keeps WebSocket connections open; leaking them on\n// hot-reload or process restart exhausts Neon's connection slot budget.\nlet _neonAuthPool: any;\n\nconst pgAuthSchema = {\n user: pgTable(\"user\", {\n id: pgText(\"id\").primaryKey(),\n name: pgText(\"name\").notNull(),\n email: pgText(\"email\").notNull().unique(),\n emailVerified: pgBoolean(\"email_verified\").notNull().default(false),\n image: pgText(\"image\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n session: pgTable(\"session\", {\n id: pgText(\"id\").primaryKey(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n token: pgText(\"token\").notNull().unique(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n ipAddress: pgText(\"ip_address\"),\n userAgent: pgText(\"user_agent\"),\n userId: pgText(\"user_id\").notNull(),\n activeOrganizationId: pgText(\"active_organization_id\"),\n }),\n account: pgTable(\"account\", {\n id: pgText(\"id\").primaryKey(),\n accountId: pgText(\"account_id\").notNull(),\n providerId: pgText(\"provider_id\").notNull(),\n userId: pgText(\"user_id\").notNull(),\n accessToken: pgText(\"access_token\"),\n refreshToken: pgText(\"refresh_token\"),\n idToken: pgText(\"id_token\"),\n accessTokenExpiresAt: pgTimestamp(\"access_token_expires_at\", {\n withTimezone: true,\n }),\n refreshTokenExpiresAt: pgTimestamp(\"refresh_token_expires_at\", {\n withTimezone: true,\n }),\n scope: pgText(\"scope\"),\n password: pgText(\"password\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n verification: pgTable(\"verification\", {\n id: pgText(\"id\").primaryKey(),\n identifier: pgText(\"identifier\").notNull(),\n value: pgText(\"value\").notNull(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n organization: pgTable(\"organization\", {\n id: pgText(\"id\").primaryKey(),\n name: pgText(\"name\").notNull(),\n slug: pgText(\"slug\").notNull().unique(),\n logo: pgText(\"logo\"),\n metadata: pgText(\"metadata\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n member: pgTable(\"member\", {\n id: pgText(\"id\").primaryKey(),\n organizationId: pgText(\"organization_id\").notNull(),\n userId: pgText(\"user_id\").notNull(),\n role: pgText(\"role\").notNull().default(\"member\"),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n invitation: pgTable(\"invitation\", {\n id: pgText(\"id\").primaryKey(),\n organizationId: pgText(\"organization_id\").notNull(),\n email: pgText(\"email\").notNull(),\n role: pgText(\"role\"),\n status: pgText(\"status\").notNull().default(\"pending\"),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }).notNull(),\n inviterId: pgText(\"inviter_id\").notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n updatedAt: pgTimestamp(\"updated_at\", { withTimezone: true }).notNull(),\n }),\n jwks: pgTable(\"jwks\", {\n id: pgText(\"id\").primaryKey(),\n publicKey: pgText(\"public_key\").notNull(),\n privateKey: pgText(\"private_key\").notNull(),\n createdAt: pgTimestamp(\"created_at\", { withTimezone: true }).notNull(),\n expiresAt: pgTimestamp(\"expires_at\", { withTimezone: true }),\n }),\n};\n\nconst sqliteAuthSchema = {\n user: sqliteTable(\"user\", {\n id: sqliteText(\"id\").primaryKey(),\n name: sqliteText(\"name\").notNull(),\n email: sqliteText(\"email\").notNull().unique(),\n emailVerified: sqliteInteger(\"email_verified\", { mode: \"boolean\" })\n .notNull()\n .default(false),\n image: sqliteText(\"image\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n session: sqliteTable(\"session\", {\n id: sqliteText(\"id\").primaryKey(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n token: sqliteText(\"token\").notNull().unique(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n ipAddress: sqliteText(\"ip_address\"),\n userAgent: sqliteText(\"user_agent\"),\n userId: sqliteText(\"user_id\").notNull(),\n activeOrganizationId: sqliteText(\"active_organization_id\"),\n }),\n account: sqliteTable(\"account\", {\n id: sqliteText(\"id\").primaryKey(),\n accountId: sqliteText(\"account_id\").notNull(),\n providerId: sqliteText(\"provider_id\").notNull(),\n userId: sqliteText(\"user_id\").notNull(),\n accessToken: sqliteText(\"access_token\"),\n refreshToken: sqliteText(\"refresh_token\"),\n idToken: sqliteText(\"id_token\"),\n accessTokenExpiresAt: sqliteInteger(\"access_token_expires_at\", {\n mode: \"timestamp_ms\",\n }),\n refreshTokenExpiresAt: sqliteInteger(\"refresh_token_expires_at\", {\n mode: \"timestamp_ms\",\n }),\n scope: sqliteText(\"scope\"),\n password: sqliteText(\"password\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n verification: sqliteTable(\"verification\", {\n id: sqliteText(\"id\").primaryKey(),\n identifier: sqliteText(\"identifier\").notNull(),\n value: sqliteText(\"value\").notNull(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n organization: sqliteTable(\"organization\", {\n id: sqliteText(\"id\").primaryKey(),\n name: sqliteText(\"name\").notNull(),\n slug: sqliteText(\"slug\").notNull().unique(),\n logo: sqliteText(\"logo\"),\n metadata: sqliteText(\"metadata\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n member: sqliteTable(\"member\", {\n id: sqliteText(\"id\").primaryKey(),\n organizationId: sqliteText(\"organization_id\").notNull(),\n userId: sqliteText(\"user_id\").notNull(),\n role: sqliteText(\"role\").notNull().default(\"member\"),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n invitation: sqliteTable(\"invitation\", {\n id: sqliteText(\"id\").primaryKey(),\n organizationId: sqliteText(\"organization_id\").notNull(),\n email: sqliteText(\"email\").notNull(),\n role: sqliteText(\"role\"),\n status: sqliteText(\"status\").notNull().default(\"pending\"),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n inviterId: sqliteText(\"inviter_id\").notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n updatedAt: sqliteInteger(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n }),\n jwks: sqliteTable(\"jwks\", {\n id: sqliteText(\"id\").primaryKey(),\n publicKey: sqliteText(\"public_key\").notNull(),\n privateKey: sqliteText(\"private_key\").notNull(),\n createdAt: sqliteInteger(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n expiresAt: sqliteInteger(\"expires_at\", { mode: \"timestamp_ms\" }),\n }),\n};\n\n/**\n * Mirror a Better Auth `account` row for Google into the `oauth_tokens`\n * table that template code (mail's Gmail client, calendar's events fetcher)\n * reads from. Called from the `databaseHooks.account.create.after` and\n * `.update.after` hooks so tokens captured during the primary \"Sign in\n * with Google\" flow flow straight to the apps that need them — no\n * separate \"Connect Google\" page required.\n *\n * Resolves `account.userId` to the user's email by querying the `user`\n * table (Better Auth always quotes \"user\" because it's a reserved word\n * in Postgres; SQLite accepts the quotes too).\n *\n * The hook is fire-and-forget from the caller's perspective — every\n * failure is caught upstream so a flake in `oauth_tokens` never blocks\n * sign-in. We still no-op on missing fields here as a defense in depth.\n */\nasync function mirrorGoogleAccountToOAuthTokens(account: {\n providerId?: string;\n userId?: string;\n accountId?: string;\n accessToken?: string | null;\n refreshToken?: string | null;\n accessTokenExpiresAt?: Date | string | number | null;\n scope?: string | null;\n idToken?: string | null;\n}): Promise<void> {\n if (!account || account.providerId !== \"google\") return;\n if (!account.userId) return;\n\n const accessToken = account.accessToken ?? undefined;\n if (!accessToken) {\n // Better Auth sometimes upserts an account row before tokens are\n // attached (e.g. linking flows). Nothing to mirror yet — the next\n // update hook will run once the access token lands.\n return;\n }\n\n // Resolve user email from userId.\n const db = getDbExec();\n let email: string | undefined;\n try {\n const { rows } = await db.execute({\n sql: 'SELECT email FROM \"user\" WHERE id = ?',\n args: [account.userId],\n });\n email = (rows[0]?.email as string | undefined) ?? undefined;\n } catch (err) {\n console.error(\n \"[auth] mirror Google tokens: failed to resolve user email from userId\",\n err,\n );\n return;\n }\n if (!email) return;\n\n // Normalise expiry to epoch ms (Google's \"expiry_date\" convention used\n // throughout the templates).\n let expiryDate: number | undefined;\n const raw = account.accessTokenExpiresAt;\n if (raw instanceof Date) {\n expiryDate = raw.getTime();\n } else if (typeof raw === \"number\") {\n expiryDate = raw;\n } else if (typeof raw === \"string\") {\n const ms = Date.parse(raw);\n expiryDate = Number.isFinite(ms) ? ms : undefined;\n }\n\n const tokens: Record<string, unknown> = {\n access_token: accessToken,\n token_type: \"Bearer\",\n };\n if (account.refreshToken) tokens.refresh_token = account.refreshToken;\n if (expiryDate) tokens.expiry_date = expiryDate;\n if (account.scope) tokens.scope = account.scope;\n if (account.idToken) tokens.id_token = account.idToken;\n\n await saveOAuthTokens(\"google\", email, tokens, email);\n}\n\nasync function ensureBetterAuthTables(): Promise<void> {\n const db = getDbExec();\n\n // PG guard: probe information_schema first (no lock) for each table; run\n // DDL only when missing, bounded by a transaction-scoped lock_timeout.\n // Probe names are UNQUOTED (what information_schema.tables.table_name stores);\n // createSql keeps the QUOTED \"user\"/\"session\"/… form required by Postgres.\n if (isPostgres()) {\n const pgTables: Array<[name: string, createSql: string]> = [\n [\n \"user\",\n `CREATE TABLE IF NOT EXISTS \"user\" (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, email_verified BOOLEAN NOT NULL DEFAULT FALSE, image TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"session\",\n `CREATE TABLE IF NOT EXISTS \"session\" (id TEXT PRIMARY KEY, expires_at TIMESTAMPTZ NOT NULL, token TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, ip_address TEXT, user_agent TEXT, user_id TEXT NOT NULL, active_organization_id TEXT)`,\n ],\n [\n \"account\",\n `CREATE TABLE IF NOT EXISTS \"account\" (id TEXT PRIMARY KEY, account_id TEXT NOT NULL, provider_id TEXT NOT NULL, user_id TEXT NOT NULL, access_token TEXT, refresh_token TEXT, id_token TEXT, access_token_expires_at TIMESTAMPTZ, refresh_token_expires_at TIMESTAMPTZ, scope TEXT, password TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"verification\",\n `CREATE TABLE IF NOT EXISTS \"verification\" (id TEXT PRIMARY KEY, identifier TEXT NOT NULL, value TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"organization\",\n `CREATE TABLE IF NOT EXISTS \"organization\" (id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT NOT NULL UNIQUE, logo TEXT, metadata TEXT, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"member\",\n `CREATE TABLE IF NOT EXISTS \"member\" (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"invitation\",\n `CREATE TABLE IF NOT EXISTS \"invitation\" (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, email TEXT NOT NULL, role TEXT, status TEXT NOT NULL DEFAULT 'pending', expires_at TIMESTAMPTZ NOT NULL, inviter_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL)`,\n ],\n [\n \"jwks\",\n `CREATE TABLE IF NOT EXISTS \"jwks\" (id TEXT PRIMARY KEY, public_key TEXT NOT NULL, private_key TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ)`,\n ],\n ];\n for (const [name, sql] of pgTables) await ensureTableExists(name, sql);\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n const sqliteStatements = [\n `CREATE TABLE IF NOT EXISTS user (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, email_verified INTEGER NOT NULL DEFAULT 0, image TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS session (id TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, token TEXT NOT NULL UNIQUE, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, ip_address TEXT, user_agent TEXT, user_id TEXT NOT NULL, active_organization_id TEXT)`,\n `CREATE TABLE IF NOT EXISTS account (id TEXT PRIMARY KEY, account_id TEXT NOT NULL, provider_id TEXT NOT NULL, user_id TEXT NOT NULL, access_token TEXT, refresh_token TEXT, id_token TEXT, access_token_expires_at INTEGER, refresh_token_expires_at INTEGER, scope TEXT, password TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS verification (id TEXT PRIMARY KEY, identifier TEXT NOT NULL, value TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS organization (id TEXT PRIMARY KEY, name TEXT NOT NULL, slug TEXT NOT NULL UNIQUE, logo TEXT, metadata TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS member (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS invitation (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, email TEXT NOT NULL, role TEXT, status TEXT NOT NULL DEFAULT 'pending', expires_at INTEGER NOT NULL, inviter_id TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,\n `CREATE TABLE IF NOT EXISTS jwks (id TEXT PRIMARY KEY, public_key TEXT NOT NULL, private_key TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER)`,\n ];\n for (const sql of sqliteStatements) await db.execute(sql);\n}\n\n/**\n * Get or create the Better Auth instance.\n * Lazily initialized on first call — the database must be reachable by then.\n */\nexport async function getBetterAuth(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInstance> {\n if (_auth) return _auth;\n if (_initPromise) return _initPromise;\n\n _initPromise = createBetterAuthInstance(config);\n _auth = await _initPromise;\n return _auth;\n}\n\n/**\n * Synchronous getter — returns the instance if already initialized, else undefined.\n * Use this in hot paths where you know init has already happened.\n */\nexport function getBetterAuthSync(): BetterAuthInstance | undefined {\n return _auth;\n}\n\n/**\n * The subset of Better Auth's internal adapter we use for federated-SSO\n * JIT account linking. Better Auth owns these writes (id + timestamp +\n * schema handling), so callers never hand-roll SQL against `user`/`account`.\n * Read-only lookups + strictly-additive `linkAccount`/`createUser` only — no\n * update/delete of existing identity rows.\n */\nexport interface BetterAuthInternalAdapter {\n findUserByEmail: (\n email: string,\n options?: { includeAccounts: boolean },\n ) => Promise<{\n user: { id: string; email: string; name?: string };\n accounts: Array<{ providerId: string; accountId: string }>;\n } | null>;\n linkAccount: (account: {\n userId: string;\n providerId: string;\n accountId: string;\n }) => Promise<unknown>;\n createUser: (user: {\n email: string;\n name: string;\n emailVerified?: boolean;\n }) => Promise<{ id: string }>;\n}\n\n/**\n * Resolve Better Auth's internal adapter via the live instance's\n * `$context`. The framework's narrowed `BetterAuthInstance` interface omits\n * `$context`, but the underlying object created by `betterAuth(...)` always\n * exposes it (see Better Auth's `Auth` type) — so this is a safe, typed\n * accessor for the federated-SSO client. Returns `undefined` if the context\n * shape is unexpected (older/newer Better Auth) so callers can fall back.\n */\nexport async function getBetterAuthInternalAdapter(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInternalAdapter | undefined> {\n const auth = (await getBetterAuth(config)) as unknown as {\n $context?: Promise<{ internalAdapter?: BetterAuthInternalAdapter }>;\n };\n try {\n const ctx = await auth.$context;\n const ia = ctx?.internalAdapter;\n if (\n ia &&\n typeof ia.findUserByEmail === \"function\" &&\n typeof ia.linkAccount === \"function\" &&\n typeof ia.createUser === \"function\"\n ) {\n return ia;\n }\n } catch {\n // Context resolution failed — caller falls back to the signup path.\n }\n return undefined;\n}\n\n/** Reset for testing */\nexport async function resetBetterAuth(): Promise<void> {\n _auth = undefined;\n _initPromise = undefined;\n if (_neonAuthPool) {\n try {\n await _neonAuthPool.end();\n } catch {\n // Pool may have already closed (process exiting, etc.) — don't block reset.\n }\n _neonAuthPool = undefined;\n }\n await closePgliteClients();\n}\n\n// ---------------------------------------------------------------------------\n// Instance creation\n// ---------------------------------------------------------------------------\n\nasync function createBetterAuthInstance(\n config?: BetterAuthConfig,\n): Promise<BetterAuthInstance> {\n const dialect = getDialect();\n const basePath = config?.basePath ?? \"/_agent-native/auth/ba\";\n await ensureBetterAuthTables();\n\n // Build social providers from env vars\n const socialProviders: BetterAuthOptions[\"socialProviders\"] = {\n ...config?.socialProviders,\n };\n\n const extraScopes = config?.googleScopes ?? [];\n const googleCredentials =\n extraScopes.length > 0\n ? process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET\n ? {\n clientId: process.env.GOOGLE_CLIENT_ID,\n clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n }\n : null\n : resolveGoogleSignInCredentials();\n if (googleCredentials) {\n // When the template requests broader scopes (Gmail, Calendar, etc.)\n // ask for them on the primary sign-in flow so a separate \"Connect\n // Google\" round-trip isn't needed. `accessType: \"offline\"` plus\n // `prompt: \"consent\"` ensures we always receive a refresh token back —\n // Google only re-issues a refresh token on consent, so re-signing in\n // (e.g. after switching machines) would otherwise leave us with an\n // access token that can't be refreshed.\n const baseScopes = [\"openid\", \"email\", \"profile\"];\n const mergedScopes = Array.from(new Set([...baseScopes, ...extraScopes]));\n socialProviders.google = {\n clientId: googleCredentials.clientId,\n clientSecret: googleCredentials.clientSecret,\n ...(extraScopes.length > 0\n ? {\n scope: mergedScopes,\n accessType: \"offline\" as const,\n prompt: \"consent\" as const,\n }\n : {}),\n };\n }\n\n if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {\n socialProviders.github = {\n clientId: process.env.GITHUB_CLIENT_ID,\n clientSecret: process.env.GITHUB_CLIENT_SECRET,\n };\n }\n\n // Build database config\n const database = await buildDatabaseConfig(dialect);\n\n const secret = resolveAuthSecret();\n\n const appUrl = getAppProductionUrl();\n const cookieNamespace = resolveAuthCookieNamespace();\n const requireEmailVerification =\n (await isEmailConfigured()) && !shouldSkipEmailVerification();\n\n const shouldMirrorGoogleAccountTokens =\n (config?.googleScopes?.length ?? 0) > 0;\n\n const auth = betterAuth({\n basePath,\n baseURL: appUrl,\n database,\n secret,\n emailAndPassword: {\n enabled: true,\n minPasswordLength: 8,\n // Only require email verification when an email provider is configured.\n // Without a provider, verification emails can't be sent, so requiring\n // verification would lock users out of signup entirely. Local dev/test\n // skip verification by default so +qa accounts can be created quickly;\n // hosted QA deployments can opt out with AUTH_SKIP_EMAIL_VERIFICATION=1.\n requireEmailVerification,\n sendResetPassword: async ({ user, token }) => {\n // APP_BASE_PATH lets this app mount under a prefix (e.g. /mail). The\n // reset link must include that prefix so the page resolves correctly.\n const appBasePath = (\n process.env.VITE_APP_BASE_PATH ||\n process.env.APP_BASE_PATH ||\n \"\"\n ).replace(/\\/$/, \"\");\n const resetUrl = `${appUrl}${appBasePath}/_agent-native/auth/reset?token=${encodeURIComponent(token)}`;\n const { subject, html, text } = renderResetPasswordEmail({\n email: user.email,\n resetUrl,\n });\n await sendEmail({ to: user.email, subject, html, text });\n },\n },\n emailVerification: {\n // Fire verification email right after signup, before the user has a\n // session — pairs with requireEmailVerification above. Only enabled\n // when an email provider is configured.\n sendOnSignUp: requireEmailVerification,\n // Auto-create a session once the user clicks the link. Without this,\n // verified users would have to go back and sign in manually, which is\n // a confusing dead-end on the verify screen.\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n // APP_BASE_PATH lets this app mount under a prefix (e.g. /mail). The\n // verification link must include that prefix so the page resolves correctly.\n const verifyBasePath = (\n process.env.VITE_APP_BASE_PATH ||\n process.env.APP_BASE_PATH ||\n \"\"\n ).replace(/\\/$/, \"\");\n const verifyUrl = verifyBasePath\n ? url.replace(/(\\/\\/[^/]+)(\\/)/, `$1${verifyBasePath}$2`)\n : url;\n const { subject, html, text } = renderVerifySignupEmail({\n email: user.email,\n verifyUrl,\n });\n await sendEmail({ to: user.email, subject, html, text });\n },\n },\n socialProviders,\n account: {\n // Merge accounts when a user signs in with a social provider using an\n // email that already has a local email/password account (or vice versa).\n // Only providers listed in `trustedProviders` auto-link — these are the\n // ones that verify emails at the identity layer. Never add a provider\n // here that lets users claim an unverified email; that would be an\n // account-takeover vector.\n accountLinking: {\n enabled: true,\n trustedProviders: [\"google\", \"github\"],\n },\n },\n databaseHooks: {\n user: {\n create: {\n after: async (\n user: {\n id?: string;\n email?: string;\n name?: string | null;\n },\n // Better Auth (1.6.x) passes the endpoint context as the 2nd arg.\n // It carries the originating request's headers (and on OAuth\n // signups the callback request's headers), which is where the\n // browser's `an_ft` first-touch cookie rides in.\n context?: {\n headers?: Headers | null;\n request?: { headers?: Headers | null } | null;\n } | null,\n ) => {\n // When a newly-created user's email has pending org invitations\n // (common when someone is invited *before* they've signed up),\n // auto-accept them so the user lands in the org on their very\n // first page load instead of a blank-slate workspace.\n const email = user?.email;\n if (!email) return;\n // Derive first-touch referral attribution from the request's\n // cookie header. Never let attribution parsing throw or block\n // signup — on any error fall back to `direct`.\n let attribution: Record<string, string> | undefined;\n try {\n const cookieHeader =\n context?.headers?.get(\"cookie\") ??\n context?.request?.headers?.get(\"cookie\") ??\n null;\n attribution = signupAttributionFromCookieHeader(cookieHeader);\n } catch (err) {\n console.error(\"[auth] failed to derive signup attribution\", err);\n attribution = undefined;\n }\n await trackSignupEvent({\n authProvider: \"better-auth\",\n authUserId: user.id,\n email,\n name: user.name,\n attribution,\n });\n try {\n await acceptPendingInvitationsForEmail(email);\n } catch (err) {\n // Never block signup on invite bookkeeping — log and continue.\n console.error(\n \"[auth] failed to auto-accept pending invitations\",\n err,\n );\n }\n try {\n // Auto-join orgs whose `allowed_domain` matches this email\n // domain. Lets a fresh `@builder.io` (or any org-domain)\n // signup land inside the company org on first page load\n // without going through the picker. No-ops when no match.\n await autoJoinDomainMatchingOrgs(email);\n } catch (err) {\n console.error(\n \"[auth] failed to auto-join domain-matching orgs\",\n err,\n );\n }\n },\n },\n },\n account: {\n // Mirror Google account tokens into `oauth_tokens` so existing\n // template code (mail's Gmail client, calendar's events fetcher)\n // can pick up Gmail/Calendar credentials from the primary sign-in\n // flow — no separate \"Set up Google\" page required.\n //\n // Better Auth fires `create` for first-time social sign-in and\n // `update` whenever a session re-issues tokens (e.g., the user\n // re-signs in to refresh the token). Both branches do the same\n // mirroring work; failures never block sign-in.\n create: {\n after: async (account: any) => {\n if (!shouldMirrorGoogleAccountTokens) return;\n await mirrorGoogleAccountToOAuthTokens(account).catch((err) => {\n console.error(\n \"[auth] failed to mirror Google account tokens to oauth_tokens (create)\",\n err,\n );\n });\n },\n },\n update: {\n after: async (account: any) => {\n if (!shouldMirrorGoogleAccountTokens) return;\n await mirrorGoogleAccountToOAuthTokens(account).catch((err) => {\n console.error(\n \"[auth] failed to mirror Google account tokens to oauth_tokens (update)\",\n err,\n );\n });\n },\n },\n },\n },\n session: {\n expiresIn: 60 * 60 * 24 * 30, // 30 days\n updateAge: 60 * 60 * 24, // refresh daily\n cookieCache: {\n enabled: true,\n maxAge: 5 * 60, // 5 min cache\n },\n },\n advanced: {\n cookiePrefix: cookieNamespace.betterAuthCookiePrefix,\n // Emit `SameSite=None; Secure` when the app is served over HTTPS so\n // session cookies are delivered inside third-party iframes (e.g. the\n // Builder.io editor). Plain-HTTP dev keeps the default (Lax) because\n // `SameSite=None` requires Secure.\n ...(appUrl.startsWith(\"https://\")\n ? {\n defaultCookieAttributes: {\n sameSite: \"none\" as const,\n secure: true,\n partitioned: true,\n },\n }\n : {}),\n // When an effective shared cookie domain is set, share Better Auth's\n // session cookie across that domain. First-party `*.agent-native.com`\n // apps intentionally do not use this path because their auth DBs are\n // separate; Dispatch identity federation handles cross-app sign-in.\n ...(cookieNamespace.betterAuthCookieDomain\n ? {\n crossSubDomainCookies: {\n enabled: true,\n domain: cookieNamespace.betterAuthCookieDomain,\n },\n }\n : {}),\n },\n plugins: [\n // JWT: issue tokens for A2A calls, JWKS endpoint for verification\n jwt({\n jwt: {\n issuer: appUrl,\n expirationTime: \"15m\",\n },\n }),\n // Bearer: accept Bearer tokens on API requests\n bearer(),\n ...(config?.plugins ?? []),\n ],\n });\n\n return auth as unknown as BetterAuthInstance;\n}\n\nasync function buildDatabaseConfig(\n dialect: string,\n): Promise<BetterAuthOptions[\"database\"]> {\n if (dialect === \"postgres\") {\n const url = getDatabaseUrl();\n const {\n buildResilientNeonPool,\n buildResilientPostgresJsClient,\n isNeonUrl,\n } = await import(\"../db/create-get-db.js\");\n\n if (isPgliteUrl(url)) {\n const { drizzle } = await loadPgliteDrizzle();\n const client = await getPgliteClient(url);\n const db = drizzle({ client, schema: pgAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // Neon via @neondatabase/serverless (WebSockets over HTTPS). postgres-js\n // opens a raw TCP connection on port 5432 which frequently times out on\n // Netlify Functions / Vercel / CF Workers when Neon's pooler is cold.\n if (isNeonUrl(url)) {\n const { Pool } = await import(\"@neondatabase/serverless\");\n // Cap the auth pool the same way as the app pool. Better Auth runs a\n // session lookup on essentially every authenticated request, so an\n // un-capped pool here is a primary contributor to \"Max client\n // connections reached\" across concurrent serverless instances.\n _neonAuthPool = new Pool({\n connectionString: url,\n max: neonPoolMax(),\n });\n attachNeonPoolErrorLogger(_neonAuthPool, \"db/neon-auth\");\n const { drizzle } = await import(\"drizzle-orm/neon-serverless\");\n const db = drizzle(buildResilientNeonPool(_neonAuthPool), {\n schema: pgAuthSchema,\n });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // Non-Neon Postgres (Supabase, self-hosted, etc.) → postgres-js.\n // pgPoolOptions caps this pool to a small size on serverless. Better Auth\n // runs a session lookup on essentially every authenticated request, so an\n // un-capped pool here is a primary contributor to \"Max client connections\n // reached\" across concurrent serverless instances.\n const { default: postgres } = await import(\"postgres\");\n const sql = postgres(url, pgPoolOptions(url));\n const { drizzle } = await import(\"drizzle-orm/postgres-js\");\n const db = drizzle(buildResilientPostgresJsClient(sql), {\n schema: pgAuthSchema,\n });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"pg\",\n schema: pgAuthSchema,\n });\n }\n\n // SQLite / libsql\n const url = getDatabaseUrl(\"file:./data/app.db\");\n\n if (url.startsWith(\"file:\") || !url.includes(\"://\")) {\n // Local SQLite via better-sqlite3\n const { default: Database } = await import(\"better-sqlite3\");\n const filePath = url.replace(/^file:/, \"\");\n const sqlite = new Database(filePath);\n sqlite.pragma(\"journal_mode = WAL\");\n const { drizzle } = await import(\"drizzle-orm/better-sqlite3\");\n const db = drizzle(sqlite, { schema: sqliteAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"sqlite\",\n schema: sqliteAuthSchema,\n });\n }\n\n // Remote libsql (Turso). Use the web client to avoid serverless bundles\n // depending on libsql's platform-specific native packages.\n const { createClient } = await import(\"@libsql/client/web\");\n const client = createClient({ url, authToken: getDatabaseAuthToken() });\n const { drizzle } = await import(\"drizzle-orm/libsql/web\");\n const db = drizzle(client, { schema: sqliteAuthSchema });\n const { drizzleAdapter } = await import(\"better-auth/adapters/drizzle\");\n return drizzleAdapter(db, {\n provider: \"sqlite\",\n schema: sqliteAuthSchema,\n });\n}\n"]}
@@ -20,7 +20,7 @@ export declare function createTranscribeVoiceHandler(): import("h3").EventHandle
20
20
  error: string;
21
21
  text?: undefined;
22
22
  } | {
23
- text: string;
24
23
  error?: undefined;
24
+ text: string;
25
25
  }>>;
26
26
  //# sourceMappingURL=transcribe-voice.d.ts.map
@@ -1,4 +1,4 @@
1
- export declare const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
1
+ export declare const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
2
2
  export declare const EMBED_TRANSPLANT_HEADER = "x-agent-native-embed-transplant";
3
3
  export declare function isLocalMcpEmbedOrigin(origin: string | null | undefined): boolean;
4
4
  export declare function isClaudeMcpContentOrigin(origin: string | null | undefined): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-embed-headers.d.ts","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,4BAA4B,yLAC+I,CAAC;AACzL,eAAO,MAAM,uBAAuB,oCAAoC,CAAC;AAYzE,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAWT;AAED,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAUT;AAED,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAWT;AAED,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,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ChC,OAAO,CAgBT;AAED,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAiBT;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAUT;AAED,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAChC,OAAO,CAQT;AAED,eAAO,MAAM,8BAA8B;aACzC,6BAA6B,EAAE,GAAG;aAClC,8BAA8B,EAAE,cAAc;CACtC,CAAC;AAoBX,wBAAgB,6BAA6B,CAC3C,QAAQ,CAAC,EAAE,MAAM,GAChB,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,OAAO,8BAA8B,CAAA;CAAE,CAAC,CAapE"}
@@ -1,4 +1,4 @@
1
- export const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
1
+ export const MCP_EMBED_CORS_ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant";
2
2
  export const EMBED_TRANSPLANT_HEADER = "x-agent-native-embed-transplant";
3
3
  const CLAUDE_MCP_CONTENT_HOST_RE = /^[a-f0-9]{32}\.claudemcpcontent\.com$/i;
4
4
  const CHATGPT_MCP_SANDBOX_HOST_RE = /^(?:[^.]+\.)?web-sandbox\.oaiusercontent\.com$/i;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-embed-headers.js","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,4BAA4B,GACv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GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACrC,IAAI,CAAC,IAAI,IAAI,IAAI,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IACrC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QACzB,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3B,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,QAAiB;IAEjB,MAAM,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IACzC,MAAM,KAAK,GAGP,EAAE,CAAC;IACP,KAAK,MAAM,OAAO,IAAI,qBAAqB,EAAE,CAAC;QAC5C,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC7D,IAAI,IAAI,EAAE,CAAC;YACT,KAAK,CAAC,GAAG,IAAI,GAAG,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["export const MCP_EMBED_CORS_ALLOW_HEADERS =\n \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant\";\nexport const EMBED_TRANSPLANT_HEADER = \"x-agent-native-embed-transplant\";\n\nconst CLAUDE_MCP_CONTENT_HOST_RE = /^[a-f0-9]{32}\\.claudemcpcontent\\.com$/i;\nconst CHATGPT_MCP_SANDBOX_HOST_RE =\n /^(?:[^.]+\\.)?web-sandbox\\.oaiusercontent\\.com$/i;\nconst AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX = \".agent-native.com\";\nconst MCP_PRODUCT_HOST_ORIGINS = new Set([\n \"https://chat.openai.com\",\n \"https://chatgpt.com\",\n \"https://claude.ai\",\n]);\n\nexport function isLocalMcpEmbedOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\", \"::1\", \"[::1]\"].includes(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isClaudeMcpContentOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" && CLAUDE_MCP_CONTENT_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isChatGptMcpSandboxOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" &&\n CHATGPT_MCP_SANDBOX_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isMcpProductHostOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n return MCP_PRODUCT_HOST_ORIGINS.has(new URL(origin).origin);\n } catch {\n return false;\n }\n}\n\nexport function isAgentNativeFirstPartyAppOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n const hostname = url.hostname.toLowerCase();\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n !url.port &&\n hostname.endsWith(AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX) &&\n hostname.length > AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX.length\n );\n } catch {\n return false;\n }\n}\n\nexport function isBuilderIoEmbedOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n const hostname = url.hostname.toLowerCase();\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n (hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\"))\n );\n } catch {\n return false;\n }\n}\n\nexport function isMcpEmbedCorsOrigin(\n origin: string | null | undefined,\n): boolean {\n return (\n origin === \"null\" ||\n isLocalMcpEmbedOrigin(origin) ||\n isClaudeMcpContentOrigin(origin) ||\n isChatGptMcpSandboxOrigin(origin) ||\n isMcpProductHostOrigin(origin) ||\n isAgentNativeFirstPartyAppOrigin(origin) ||\n isBuilderIoEmbedOrigin(origin)\n );\n}\n\nexport function shouldAllowMcpEmbedCredentials(\n origin: string | null | undefined,\n): boolean {\n return (\n origin !== \"null\" &&\n !isClaudeMcpContentOrigin(origin) &&\n !isChatGptMcpSandboxOrigin(origin) &&\n !isMcpProductHostOrigin(origin) &&\n !isAgentNativeFirstPartyAppOrigin(origin)\n );\n}\n\nexport const MCP_EMBED_STATIC_ASSET_HEADERS = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Cross-Origin-Resource-Policy\": \"cross-origin\",\n} as const;\n\nconst STATIC_ASSET_PATTERNS = [\n \"/assets/**\",\n \"/favicon.ico\",\n \"/favicon.svg\",\n \"/manifest.json\",\n \"/icon-*.svg\",\n \"/agent-native-*.svg\",\n \"/library-presets/**\",\n];\n\nfunction normalizeBasePath(basePath: string | undefined): string {\n const base = (basePath ?? \"\").trim();\n if (!base || base === \"/\") return \"\";\n return base.startsWith(\"/\")\n ? base.replace(/\\/+$/g, \"\")\n : `/${base.replace(/\\/+$/g, \"\")}`;\n}\n\nexport function mcpEmbedStaticAssetRouteRules(\n basePath?: string,\n): Record<string, { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }> {\n const base = normalizeBasePath(basePath);\n const rules: Record<\n string,\n { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }\n > = {};\n for (const pattern of STATIC_ASSET_PATTERNS) {\n rules[pattern] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n if (base) {\n rules[`${base}${pattern}`] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n }\n }\n return rules;\n}\n"]}
1
+ {"version":3,"file":"mcp-embed-headers.js","sourceRoot":"","sources":["../../src/shared/mcp-embed-headers.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,4BAA4B,GACvC,kPAAkP,CAAC;AACrP,MAAM,CAAC,MAAM,uBAAuB,GAAG,iCAAiC,CAAC;AAEzE,MAAM,0BAA0B,GAAG,wCAAwC,CAAC;AAC5E,MAAM,2BAA2B,GAC/B,iDAAiD,CAAC;AACpD,MAAM,wCAAwC,GAAG,mBAAmB,CAAC;AACrE,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC;IACvC,yBAAyB;IACzB,qBAAqB;IACrB,mBAAmB;CACpB,CAAC,CAAC;AAEH,MAAM,UAAU,qBAAqB,CACnC,MAAiC;IAEjC,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,OAAO,CACL,GAAG,CAAC,QAAQ,KAAK,OAAO;YACxB,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAClE,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,MAAiC;IAEjC,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,OAAO,CACL,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,0BAA0B,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAC3E,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;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AM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,cAAc;IACd,cAAc;IACd,gBAAgB;IAChB,aAAa;IACb,qBAAqB;IACrB,qBAAqB;CACtB,CAAC;AAEF,SAAS,iBAAiB,CAAC,QAA4B;IACrD,MAAM,IAAI,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACrC,IAAI,CAAC,IAAI,IAAI,IAAI,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IACrC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QACzB,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3B,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,QAAiB;IAEjB,MAAM,IAAI,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IACzC,MAAM,KAAK,GAGP,EAAE,CAAC;IACP,KAAK,MAAM,OAAO,IAAI,qBAAqB,EAAE,CAAC;QAC5C,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC7D,IAAI,IAAI,EAAE,CAAC;YACT,KAAK,CAAC,GAAG,IAAI,GAAG,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,8BAA8B,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["export const MCP_EMBED_CORS_ALLOW_HEADERS =\n \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,X-User-Timezone,X-Agent-Native-Embed-Target,X-Agent-Native-Embed-Transplant\";\nexport const EMBED_TRANSPLANT_HEADER = \"x-agent-native-embed-transplant\";\n\nconst CLAUDE_MCP_CONTENT_HOST_RE = /^[a-f0-9]{32}\\.claudemcpcontent\\.com$/i;\nconst CHATGPT_MCP_SANDBOX_HOST_RE =\n /^(?:[^.]+\\.)?web-sandbox\\.oaiusercontent\\.com$/i;\nconst AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX = \".agent-native.com\";\nconst MCP_PRODUCT_HOST_ORIGINS = new Set([\n \"https://chat.openai.com\",\n \"https://chatgpt.com\",\n \"https://claude.ai\",\n]);\n\nexport function isLocalMcpEmbedOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\", \"::1\", \"[::1]\"].includes(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isClaudeMcpContentOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" && CLAUDE_MCP_CONTENT_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isChatGptMcpSandboxOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n return (\n url.protocol === \"https:\" &&\n CHATGPT_MCP_SANDBOX_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n}\n\nexport function isMcpProductHostOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n return MCP_PRODUCT_HOST_ORIGINS.has(new URL(origin).origin);\n } catch {\n return false;\n }\n}\n\nexport function isAgentNativeFirstPartyAppOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n const hostname = url.hostname.toLowerCase();\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n !url.port &&\n hostname.endsWith(AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX) &&\n hostname.length > AGENT_NATIVE_FIRST_PARTY_APP_HOST_SUFFIX.length\n );\n } catch {\n return false;\n }\n}\n\nexport function isBuilderIoEmbedOrigin(\n origin: string | null | undefined,\n): boolean {\n if (!origin) return false;\n try {\n const url = new URL(origin);\n const hostname = url.hostname.toLowerCase();\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n (hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\"))\n );\n } catch {\n return false;\n }\n}\n\nexport function isMcpEmbedCorsOrigin(\n origin: string | null | undefined,\n): boolean {\n return (\n origin === \"null\" ||\n isLocalMcpEmbedOrigin(origin) ||\n isClaudeMcpContentOrigin(origin) ||\n isChatGptMcpSandboxOrigin(origin) ||\n isMcpProductHostOrigin(origin) ||\n isAgentNativeFirstPartyAppOrigin(origin) ||\n isBuilderIoEmbedOrigin(origin)\n );\n}\n\nexport function shouldAllowMcpEmbedCredentials(\n origin: string | null | undefined,\n): boolean {\n return (\n origin !== \"null\" &&\n !isClaudeMcpContentOrigin(origin) &&\n !isChatGptMcpSandboxOrigin(origin) &&\n !isMcpProductHostOrigin(origin) &&\n !isAgentNativeFirstPartyAppOrigin(origin)\n );\n}\n\nexport const MCP_EMBED_STATIC_ASSET_HEADERS = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Cross-Origin-Resource-Policy\": \"cross-origin\",\n} as const;\n\nconst STATIC_ASSET_PATTERNS = [\n \"/assets/**\",\n \"/favicon.ico\",\n \"/favicon.svg\",\n \"/manifest.json\",\n \"/icon-*.svg\",\n \"/agent-native-*.svg\",\n \"/library-presets/**\",\n];\n\nfunction normalizeBasePath(basePath: string | undefined): string {\n const base = (basePath ?? \"\").trim();\n if (!base || base === \"/\") return \"\";\n return base.startsWith(\"/\")\n ? base.replace(/\\/+$/g, \"\")\n : `/${base.replace(/\\/+$/g, \"\")}`;\n}\n\nexport function mcpEmbedStaticAssetRouteRules(\n basePath?: string,\n): Record<string, { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }> {\n const base = normalizeBasePath(basePath);\n const rules: Record<\n string,\n { headers: typeof MCP_EMBED_STATIC_ASSET_HEADERS }\n > = {};\n for (const pattern of STATIC_ASSET_PATTERNS) {\n rules[pattern] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n if (base) {\n rules[`${base}${pattern}`] = { headers: MCP_EMBED_STATIC_ASSET_HEADERS };\n }\n }\n return rules;\n}\n"]}
@@ -0,0 +1,133 @@
1
+ ---
2
+ name: agent-native-toolkit
3
+ description: >-
4
+ Inventory and ownership rules for shared Agent Native workspace UI. Use
5
+ before building app chrome, settings, navigation, sharing, collaboration,
6
+ setup, history, comments, chat rails, agent UX, or repeated workspace behavior.
7
+ scope: dev
8
+ metadata:
9
+ internal: true
10
+ ---
11
+
12
+ # Agent-Native Toolkit
13
+
14
+ Use this skill when deciding whether app chrome, settings, collaboration,
15
+ sharing, navigation, organization, setup, history, comments, or agent UX should
16
+ be built app-locally or moved into reusable framework/toolkit pieces.
17
+
18
+ ## Core Rule
19
+
20
+ Apps own domain models, domain actions, and product-specific workflows. The
21
+ framework and `@agent-native/toolkit` own repeated workspace behavior users
22
+ expect to work the same everywhere.
23
+
24
+ Move behavior into shared toolkit primitives when it is:
25
+
26
+ - workspace-wide, such as settings, nav, search, org membership, or setup
27
+ - agent-visible, such as context, actions, run progress, or proof-of-done
28
+ - governed, such as secrets, permissions, sharing, audit, or billing
29
+ - repeated by two or more apps
30
+ - not tied to one domain model
31
+
32
+ Keep behavior app-local when the abstraction would hide important domain
33
+ language or make a simple app-specific workflow harder to understand.
34
+
35
+ ## Discover Before Building
36
+
37
+ Before creating an app-local version of repeated workspace or agent UI:
38
+
39
+ 1. Check the reusable kits below and the installed package documentation.
40
+ 2. Search installed public components and source with `docs-search` and
41
+ `source-search`.
42
+ 3. Run `agent-native eject --list` to see the version-matched units published
43
+ by the packages installed in this app.
44
+ 4. Read `customizing-agent-native` and configure, compose, or eject the
45
+ smallest unit instead of recreating shared behavior from memory.
46
+
47
+ Use public package exports at runtime. Published source and ejection manifests
48
+ are discovery and ownership-transfer mechanisms, not private runtime APIs.
49
+
50
+ ## Settings Direction
51
+
52
+ Durable settings belong in the Settings app or a registered settings route. The
53
+ agent sidebar should not become a second settings app. It can show contextual
54
+ quick controls and deep links such as:
55
+
56
+ - `/settings/ai`
57
+ - `/settings/connections`
58
+ - `/settings/secrets`
59
+ - `/settings/usage`
60
+ - `/settings/apps/:appId`
61
+
62
+ When adding a new API key, OAuth grant, provider connection, model selector, app
63
+ preference, notification preference, or usage/billing surface, register it as a
64
+ settings tab or app settings panel first. Only add sidebar UI when it is needed
65
+ in the moment of agent use.
66
+
67
+ ## Reusable Kits
68
+
69
+ - **Settings kit**: a searchable settings page with account, workspace, AI
70
+ models, LLM keys, connections, secrets, usage, notifications, changelog, and
71
+ app-specific panels. Search is on by default; register a `SettingsSearchEntry`
72
+ per control so users find settings by name across tabs.
73
+ - **Collaboration kit**: Yjs docs, presence, agent presence, live cursors,
74
+ remote selections, recent edit highlights, real-time sync indicators, and
75
+ undo/redo grouping.
76
+ - **Sharing kit**: private/workspace/org/public-link access, invites, roles,
77
+ expirations, agent-readable links, and resource registration.
78
+ - **Navigation and command kit**: app shell, side nav, breadcrumbs, app switcher,
79
+ command palette entries, recent resources, pinned resources, and global search.
80
+ - **Organization kit**: folders, tags, favorites, archive, trash, ownership,
81
+ membership, and common resource metadata.
82
+ - **Setup and connections kit**: declarative setup requirements, model readiness,
83
+ missing-secret states, OAuth grants, and provider connection health.
84
+ - **Agent UX kit**: sidebar, composer, staged context, mentions, voice, human
85
+ approval, generative UI, progress, and screen-state exposure.
86
+ - **Chat history kit**: presentational chat lists and recent-chat rails belong
87
+ in Toolkit; Core keeps thread persistence, agent execution, transport, and
88
+ page-to-sidebar handoff. Apps inject routing, labels, and domain actions.
89
+ - **Agent page kit**: the full-page `/agent` surface (`AgentTabsPage` from
90
+ `@agent-native/core/client`) with Context, Files, Connections, Jobs, and
91
+ Access tabs plus a Personal/Organization scope toggle. The canonical home
92
+ for context transparency, MCP servers, A2A remote agents, recurring
93
+ jobs/automations, and external-client connect flows. See the `agent-page`
94
+ skill.
95
+ - **History and recovery kit**: audit log, activity feed, version history,
96
+ checkpoints, undo, redo, restore, and proof-of-done.
97
+ - **Comments and review kit**: anchored comments, pins, mentions, review
98
+ requests, resolved threads, agent follow-up tasks, and notifications.
99
+ - **Workflow and observability kit**: notifications, approvals, scheduled work,
100
+ background runs, recurring jobs, traces, evals, feedback, and run timelines.
101
+
102
+ ## Implementation Checklist
103
+
104
+ When adding or refactoring one of these areas:
105
+
106
+ 1. Search existing framework and template code for duplicated UI or actions.
107
+ 2. Decide the shared contract: data shape, action API, React component/hook, and
108
+ app adapter points.
109
+ 3. Keep shared data provider-agnostic and scoped by auth/sharing rules.
110
+ 4. Expose the same capability to the UI and agent through actions or documented
111
+ client helpers.
112
+ 5. Register app-specific labels, routes, resource adapters, and settings panels
113
+ instead of hardcoding app names in core UI.
114
+ 6. Update docs and relevant skills so future apps discover the shared path.
115
+ 7. Keep the component easy to adopt piecemeal: expose props/slots first and
116
+ ship readable source plus a complete ejection unit so apps can take ownership
117
+ of the smallest feature when needed. See `customizing-agent-native` for the
118
+ configure → compose → eject → propose seam ladder.
119
+
120
+ ## Related Skills
121
+
122
+ Read these alongside this skill when the work touches the specific area:
123
+
124
+ - `sharing`
125
+ - `real-time-collab`
126
+ - `real-time-sync`
127
+ - `client-side-routing`
128
+ - `context-awareness`
129
+ - `onboarding`
130
+ - `secrets`
131
+ - `audit-log`
132
+ - `observability`
133
+ - `frontend-design`