@agent-native/core 0.79.16 → 0.79.18
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.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +14 -0
- package/corpus/core/docs/content/file-uploads.md +11 -4
- package/corpus/core/docs/content/locales/ar-SA/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/de-DE/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/es-ES/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/fr-FR/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/hi-IN/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/ja-JP/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/ko-KR/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/pt-BR/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/zh-CN/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/locales/zh-TW/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/multi-app-workspace.md +3 -3
- package/corpus/core/docs/content/template-clips.md +14 -5
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/agent/engine/builder-engine.ts +8 -3
- package/corpus/core/src/cli/mcp.ts +11 -6
- package/corpus/core/src/client/AssistantChat.tsx +6 -2
- package/corpus/core/src/client/chat/markdown-renderer.tsx +1 -0
- package/corpus/core/src/client/index.ts +7 -1
- package/corpus/core/src/client/org/OrgSwitcher.tsx +5 -5
- package/corpus/core/src/client/org/TeamPage.tsx +11 -3
- package/corpus/core/src/client/settings/SettingsTabsPage.tsx +216 -0
- package/corpus/core/src/client/settings/index.ts +5 -0
- package/corpus/core/src/file-upload/index.ts +1 -0
- package/corpus/core/src/file-upload/registry.ts +22 -6
- package/corpus/core/src/file-upload/types.ts +6 -1
- package/corpus/core/src/integrations/adapters/email.ts +26 -18
- package/corpus/core/src/integrations/adapters/slack.ts +8 -7
- package/corpus/core/src/integrations/adapters/telegram.ts +9 -11
- package/corpus/core/src/integrations/adapters/whatsapp.ts +12 -9
- package/corpus/core/src/integrations/plugin.ts +79 -13
- package/corpus/core/src/onboarding/default-steps.ts +6 -3
- package/corpus/core/src/onboarding/types.ts +1 -1
- package/corpus/core/src/org/handlers.ts +1 -1
- package/corpus/core/src/server/agent-chat-plugin.ts +4 -7
- package/corpus/core/src/server/better-auth-instance.ts +19 -62
- package/corpus/core/src/server/core-routes-plugin.ts +93 -180
- package/corpus/core/src/server/create-server.ts +55 -116
- package/corpus/core/src/server/email-actions.ts +3 -6
- package/corpus/core/src/server/email.ts +52 -17
- package/corpus/core/src/server/index.ts +2 -1
- package/corpus/core/src/server/scoped-key-storage.ts +223 -0
- package/corpus/core/src/shared/agent-env.ts +3 -3
- package/corpus/core/src/sharing/actions/share-resource.ts +1 -1
- package/corpus/core/src/styles/agent-native.css +55 -3
- package/corpus/core/src/templates/workspace-root/AGENTS.md +3 -2
- package/corpus/core/src/templates/workspace-root/README.md +1 -1
- package/corpus/core/src/templates/workspace-root/scripts/repair-workspace-org.ts +29 -90
- package/corpus/core/src/terminal/pty-server.ts +3 -38
- package/corpus/core/src/triggers/dispatcher.ts +1 -2
- package/corpus/templates/.retired/issues/package.json +7 -0
- package/corpus/templates/.retired/meeting-notes/package.json +7 -0
- package/corpus/templates/.retired/recruiting/package.json +7 -0
- package/corpus/templates/.retired/scheduling/package.json +7 -0
- package/corpus/templates/.retired/voice/package.json +7 -0
- package/corpus/templates/analytics/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +0 -17
- package/corpus/templates/analytics/app/i18n/zh-TW.ts +7 -1
- package/corpus/templates/analytics/app/i18n-data.ts +71 -2
- package/corpus/templates/analytics/app/pages/Settings.tsx +120 -73
- package/corpus/templates/analytics/app/pages/sessions/SessionsPage.tsx +0 -11
- package/corpus/templates/analytics/app/routes/catalog.tsx +33 -176
- package/corpus/templates/analytics/app/routes/team.tsx +3 -2
- package/corpus/templates/analytics/changelog/2026-06-26-dashboard-templates-are-tucked-into-settings-and-show-simple.md +6 -0
- package/corpus/templates/analytics/changelog/2026-06-26-the-sessions-page-shows-a-single-page-title-instead-of-repea.md +6 -0
- package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +37 -28
- package/corpus/templates/assets/app/routes/settings.tsx +65 -43
- package/corpus/templates/assets/app/routes/team.tsx +2 -10
- package/corpus/templates/brain/app/routes/settings.tsx +390 -358
- package/corpus/templates/brain/app/routes/team.tsx +2 -8
- package/corpus/templates/calendar/actions/db-connect.ts +5 -29
- package/corpus/templates/calendar/app/components/CloudUpgrade.tsx +8 -51
- package/corpus/templates/calendar/app/components/calendar/GoogleConnectBanner.tsx +2 -1
- package/corpus/templates/calendar/app/components/calendar/GoogleSetupWizard.tsx +4 -2
- package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +0 -2
- package/corpus/templates/calendar/app/pages/Settings.tsx +304 -271
- package/corpus/templates/calendar/app/routes/_app.team.tsx +2 -17
- package/corpus/templates/calendar/server/handlers/google-auth.ts +22 -9
- package/corpus/templates/calendar/server/lib/booking-emails.ts +1 -1
- package/corpus/templates/calendar/server/lib/event-guest-notifications.ts +1 -1
- package/corpus/templates/calendar/server/lib/google-calendar.ts +48 -28
- package/corpus/templates/chat/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/chat/app/hooks/use-navigation-state.ts +4 -2
- package/corpus/templates/chat/app/routes/settings.tsx +54 -54
- package/corpus/templates/chat/app/routes/team.tsx +2 -10
- package/corpus/templates/clips/.agents/skills/ai-video-tools/SKILL.md +7 -2
- package/corpus/templates/clips/.agents/skills/recording/SKILL.md +1 -1
- package/corpus/templates/clips/.agents/skills/video-sharing/SKILL.md +7 -0
- package/corpus/templates/clips/AGENTS.md +8 -0
- package/corpus/templates/clips/actions/invite-member.ts +1 -1
- package/corpus/templates/clips/actions/request-transcript.ts +1 -1
- package/corpus/templates/clips/app/components/library/library-layout.tsx +3 -3
- package/corpus/templates/clips/app/components/player/transcript-panel.tsx +2 -0
- package/corpus/templates/clips/app/routes/_app.settings._index.tsx +629 -643
- package/corpus/templates/clips/app/routes/r.$recordingId.tsx +219 -155
- package/corpus/templates/clips/changelog/2026-06-26-long-desktop-recordings-are-checkpointed-so-macos-finalizati.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-26-non-mac-desktop-recordings-wait-for-upload-transcription.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-26-s3-compatible-storage-keys-now-save-securely-from-clips-sett.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-26-shared-clip-links-guide-agents-through-processing-transcripts.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-26-the-clip-details-sidebar-now-collapses-into-a-slide-out-pane.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-26-the-clips-library-now-matches-the-shared-recessed-shell-styl.md +6 -0
- package/corpus/templates/clips/desktop/src/lib/recorder.ts +55 -3
- package/corpus/templates/clips/desktop/src/lib/transcription-capture.ts +217 -5
- package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +1 -0
- package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +176 -5
- package/corpus/templates/clips/server/lib/public-agent-context.ts +31 -0
- package/corpus/templates/clips/server/lib/s3-upload-provider.ts +60 -14
- package/corpus/templates/clips/server/lib/video-storage.ts +37 -9
- package/corpus/templates/clips/server/routes/api/agent-transcript.json.get.ts +5 -0
- package/corpus/templates/content/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/content/app/components/sidebar/NotionButton.tsx +1 -0
- package/corpus/templates/content/app/routes/_app.settings.tsx +54 -55
- package/corpus/templates/content/app/routes/_app.team.tsx +2 -28
- package/corpus/templates/content/server/lib/notion.ts +43 -11
- package/corpus/templates/content/server/routes/api/notion/auth-url.get.ts +2 -2
- package/corpus/templates/content/server/routes/api/notion/status.get.ts +3 -3
- package/corpus/templates/design/app/routes/settings.tsx +60 -38
- package/corpus/templates/design/app/routes/team.tsx +2 -10
- package/corpus/templates/dispatch/app/hooks/use-navigation-state.ts +2 -2
- package/corpus/templates/dispatch/app/routes/settings.tsx +70 -55
- package/corpus/templates/dispatch/app/routes/team.tsx +5 -1
- package/corpus/templates/forms/actions/db-connect.ts +7 -36
- package/corpus/templates/forms/actions/navigate.ts +2 -2
- package/corpus/templates/forms/app/components/CloudUpgrade.tsx +8 -47
- package/corpus/templates/forms/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/forms/app/components/layout/Layout.tsx +42 -25
- package/corpus/templates/forms/app/components/layout/Sidebar.tsx +35 -76
- package/corpus/templates/forms/app/global.css +9 -25
- package/corpus/templates/forms/app/hooks/use-navigation-state.ts +4 -4
- package/corpus/templates/forms/app/i18n/ar-SA.ts +1 -0
- package/corpus/templates/forms/app/i18n/de-DE.ts +1 -0
- package/corpus/templates/forms/app/i18n/en-US.ts +1 -0
- package/corpus/templates/forms/app/i18n/es-ES.ts +1 -0
- package/corpus/templates/forms/app/i18n/fr-FR.ts +1 -0
- package/corpus/templates/forms/app/i18n/hi-IN.ts +1 -0
- package/corpus/templates/forms/app/i18n/ja-JP.ts +1 -0
- package/corpus/templates/forms/app/i18n/ko-KR.ts +1 -0
- package/corpus/templates/forms/app/i18n/pt-BR.ts +1 -0
- package/corpus/templates/forms/app/i18n/zh-CN.ts +1 -0
- package/corpus/templates/forms/app/i18n/zh-TW.ts +1 -0
- package/corpus/templates/forms/app/lib/route-prewarm.ts +9 -8
- package/corpus/templates/forms/app/pages/AskPage.tsx +70 -0
- package/corpus/templates/forms/app/pages/FormsListPage.tsx +74 -81
- package/corpus/templates/forms/app/root.tsx +1 -1
- package/corpus/templates/forms/app/routes/_app.ask.tsx +14 -0
- package/corpus/templates/forms/app/routes/_app.settings.tsx +54 -54
- package/corpus/templates/forms/app/routes/_app.team.tsx +2 -9
- package/corpus/templates/forms/app/routes/_index.tsx +21 -130
- package/corpus/templates/forms/changelog/2026-06-26-ask-forms-opens-as-a-standard-app-tab-with-a-simpler-sidebar.md +6 -0
- package/corpus/templates/forms/changelog/2026-06-26-forms-are-shown-in-a-tighter-row-list-with-a-denser-sidebar.md +6 -0
- package/corpus/templates/forms/shared/navigation.ts +4 -2
- package/corpus/templates/macros/app/routes/settings.tsx +54 -54
- package/corpus/templates/macros/app/routes/team.tsx +2 -10
- package/corpus/templates/mail/actions/helpers.ts +2 -2
- package/corpus/templates/mail/app/components/GoogleConnectBanner.tsx +2 -1
- package/corpus/templates/mail/app/pages/SettingsPage.tsx +5 -5
- package/corpus/templates/mail/app/routes/team.tsx +3 -2
- package/corpus/templates/mail/server/handlers/emails.ts +3 -2
- package/corpus/templates/mail/server/handlers/google-auth.ts +19 -12
- package/corpus/templates/mail/server/lib/automation-engine.ts +3 -2
- package/corpus/templates/mail/server/lib/email-state.ts +2 -3
- package/corpus/templates/mail/server/lib/google-auth.ts +28 -11
- package/corpus/templates/mail/server/lib/jobs.ts +3 -2
- package/corpus/templates/mail/server/onboarding.ts +9 -6
- package/corpus/templates/mail/server/routes/api/attachments.get.ts +3 -3
- package/corpus/templates/plan/actions/request-plan-access.ts +1 -1
- package/corpus/templates/plan/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/plan/app/hooks/use-navigation-state.ts +4 -2
- package/corpus/templates/plan/app/lib/route-prewarm.ts +0 -4
- package/corpus/templates/plan/app/routes/settings.tsx +75 -73
- package/corpus/templates/plan/app/routes/team.tsx +2 -8
- package/corpus/templates/plan/server/lib/comment-notifications.ts +1 -1
- package/corpus/templates/slides/actions/check-image-gen.ts +2 -1
- package/corpus/templates/slides/actions/db-connect.ts +7 -45
- package/corpus/templates/slides/actions/edit-image.ts +6 -3
- package/corpus/templates/slides/actions/generate-image-api.ts +1 -1
- package/corpus/templates/slides/actions/generate-image.ts +2 -2
- package/corpus/templates/slides/actions/generate-slides-ai.ts +5 -3
- package/corpus/templates/slides/actions/image-gen-status.ts +4 -3
- package/corpus/templates/slides/actions/image-search.ts +6 -3
- package/corpus/templates/slides/actions/search-images.ts +6 -3
- package/corpus/templates/slides/app/components/CloudUpgrade.tsx +8 -51
- package/corpus/templates/slides/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/slides/app/components/layout/Sidebar.tsx +0 -2
- package/corpus/templates/slides/app/routes/settings.tsx +54 -54
- package/corpus/templates/slides/app/routes/team.tsx +2 -12
- package/corpus/templates/slides/server/handlers/google-docs-auth.ts +9 -9
- package/corpus/templates/slides/server/handlers/image-gen.ts +5 -1
- package/corpus/templates/slides/server/handlers/image-providers/gemini.ts +9 -1
- package/corpus/templates/slides/server/handlers/image-providers/index.ts +18 -8
- package/corpus/templates/slides/server/handlers/image-providers/openai.ts +10 -4
- package/corpus/templates/slides/server/handlers/image-providers/types.ts +1 -0
- package/corpus/templates/slides/server/lib/google-docs-oauth.ts +59 -34
- package/corpus/templates/slides/server/register-secrets.ts +60 -0
- package/corpus/templates/videos/actions/db-connect.ts +7 -45
- package/corpus/templates/videos/app/components/CloudUpgrade.tsx +8 -51
- package/corpus/templates/videos/app/components/Sidebar.tsx +1 -9
- package/corpus/templates/videos/app/components/layout/Header.tsx +0 -1
- package/corpus/templates/videos/app/components/layout/NavSidebar.tsx +0 -3
- package/corpus/templates/videos/app/routes/settings.tsx +54 -54
- package/corpus/templates/videos/app/routes/team.tsx +2 -8
- package/dist/agent/engine/builder-engine.d.ts.map +1 -1
- package/dist/agent/engine/builder-engine.js +8 -3
- package/dist/agent/engine/builder-engine.js.map +1 -1
- package/dist/cli/mcp.d.ts.map +1 -1
- package/dist/cli/mcp.js +3 -4
- package/dist/cli/mcp.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +6 -2
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/chat/markdown-renderer.d.ts.map +1 -1
- package/dist/client/chat/markdown-renderer.js +1 -0
- package/dist/client/chat/markdown-renderer.js.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/org/OrgSwitcher.d.ts +3 -3
- package/dist/client/org/OrgSwitcher.js +2 -2
- package/dist/client/org/OrgSwitcher.js.map +1 -1
- package/dist/client/org/TeamPage.d.ts +6 -1
- package/dist/client/org/TeamPage.d.ts.map +1 -1
- package/dist/client/org/TeamPage.js +2 -2
- package/dist/client/org/TeamPage.js.map +1 -1
- package/dist/client/settings/SettingsTabsPage.d.ts +27 -0
- package/dist/client/settings/SettingsTabsPage.d.ts.map +1 -0
- package/dist/client/settings/SettingsTabsPage.js +108 -0
- package/dist/client/settings/SettingsTabsPage.js.map +1 -0
- package/dist/client/settings/index.d.ts +1 -0
- package/dist/client/settings/index.d.ts.map +1 -1
- package/dist/client/settings/index.js +1 -0
- package/dist/client/settings/index.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/file-upload/index.d.ts +1 -1
- package/dist/file-upload/index.d.ts.map +1 -1
- package/dist/file-upload/index.js +1 -1
- package/dist/file-upload/index.js.map +1 -1
- package/dist/file-upload/registry.d.ts +1 -0
- package/dist/file-upload/registry.d.ts.map +1 -1
- package/dist/file-upload/registry.js +24 -6
- package/dist/file-upload/registry.js.map +1 -1
- package/dist/file-upload/types.d.ts +6 -1
- package/dist/file-upload/types.d.ts.map +1 -1
- package/dist/file-upload/types.js.map +1 -1
- package/dist/integrations/adapters/email.d.ts.map +1 -1
- package/dist/integrations/adapters/email.js +18 -18
- package/dist/integrations/adapters/email.js.map +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +8 -7
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/integrations/adapters/telegram.d.ts.map +1 -1
- package/dist/integrations/adapters/telegram.js +9 -9
- package/dist/integrations/adapters/telegram.js.map +1 -1
- package/dist/integrations/adapters/whatsapp.d.ts.map +1 -1
- package/dist/integrations/adapters/whatsapp.js +10 -9
- package/dist/integrations/adapters/whatsapp.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +47 -13
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/onboarding/default-steps.d.ts.map +1 -1
- package/dist/onboarding/default-steps.js +6 -5
- package/dist/onboarding/default-steps.js.map +1 -1
- package/dist/onboarding/types.d.ts +1 -1
- package/dist/onboarding/types.d.ts.map +1 -1
- package/dist/onboarding/types.js.map +1 -1
- package/dist/org/handlers.js +1 -1
- package/dist/org/handlers.js.map +1 -1
- package/dist/progress/routes.d.ts +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +4 -6
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/better-auth-instance.d.ts.map +1 -1
- package/dist/server/better-auth-instance.js +17 -56
- package/dist/server/better-auth-instance.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +67 -153
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/create-server.d.ts +3 -9
- package/dist/server/create-server.d.ts.map +1 -1
- package/dist/server/create-server.js +37 -91
- package/dist/server/create-server.js.map +1 -1
- package/dist/server/email-actions.d.ts +2 -3
- package/dist/server/email-actions.d.ts.map +1 -1
- package/dist/server/email-actions.js +3 -6
- package/dist/server/email-actions.js.map +1 -1
- package/dist/server/email.d.ts +3 -3
- package/dist/server/email.d.ts.map +1 -1
- package/dist/server/email.js +40 -19
- package/dist/server/email.js.map +1 -1
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +3 -3
- package/dist/server/index.js.map +1 -1
- package/dist/server/scoped-key-storage.d.ts +22 -0
- package/dist/server/scoped-key-storage.d.ts.map +1 -0
- package/dist/server/scoped-key-storage.js +152 -0
- package/dist/server/scoped-key-storage.js.map +1 -0
- package/dist/shared/agent-env.d.ts +3 -3
- package/dist/shared/agent-env.d.ts.map +1 -1
- package/dist/shared/agent-env.js +3 -3
- package/dist/shared/agent-env.js.map +1 -1
- package/dist/sharing/actions/share-resource.js +1 -1
- package/dist/sharing/actions/share-resource.js.map +1 -1
- package/dist/styles/agent-native.css +55 -3
- package/dist/templates/workspace-root/AGENTS.md +3 -2
- package/dist/templates/workspace-root/README.md +1 -1
- package/dist/templates/workspace-root/scripts/repair-workspace-org.ts +29 -90
- package/dist/terminal/pty-server.d.ts.map +1 -1
- package/dist/terminal/pty-server.js +3 -36
- package/dist/terminal/pty-server.js.map +1 -1
- package/dist/triggers/dispatcher.js +1 -1
- package/dist/triggers/dispatcher.js.map +1 -1
- package/docs/content/file-uploads.md +11 -4
- package/docs/content/locales/ar-SA/multi-app-workspace.md +3 -3
- package/docs/content/locales/de-DE/multi-app-workspace.md +3 -3
- package/docs/content/locales/es-ES/multi-app-workspace.md +3 -3
- package/docs/content/locales/fr-FR/multi-app-workspace.md +3 -3
- package/docs/content/locales/hi-IN/multi-app-workspace.md +3 -3
- package/docs/content/locales/ja-JP/multi-app-workspace.md +3 -3
- package/docs/content/locales/ko-KR/multi-app-workspace.md +3 -3
- package/docs/content/locales/pt-BR/multi-app-workspace.md +3 -3
- package/docs/content/locales/zh-CN/multi-app-workspace.md +3 -3
- package/docs/content/locales/zh-TW/multi-app-workspace.md +3 -3
- package/docs/content/multi-app-workspace.md +3 -3
- package/docs/content/template-clips.md +14 -5
- package/package.json +1 -1
- package/src/templates/workspace-root/AGENTS.md +3 -2
- package/src/templates/workspace-root/README.md +1 -1
- package/src/templates/workspace-root/scripts/repair-workspace-org.ts +29 -90
- package/corpus/core/src/server/env-var-writes.ts +0 -16
- package/corpus/templates/analytics/app/pages/Team.tsx +0 -9
- package/corpus/templates/calendar/app/pages/Team.tsx +0 -12
- package/corpus/templates/mail/app/pages/Team.tsx +0 -17
- package/dist/server/env-var-writes.d.ts +0 -10
- package/dist/server/env-var-writes.d.ts.map +0 -1
- package/dist/server/env-var-writes.js +0 -18
- package/dist/server/env-var-writes.js.map +0 -1
|
@@ -18,16 +18,9 @@ export interface CreateServerOptions {
|
|
|
18
18
|
pingMessage?: string;
|
|
19
19
|
/** Disable the /_agent-native/ping health check. Default: false */
|
|
20
20
|
disablePing?: boolean;
|
|
21
|
-
/**
|
|
21
|
+
/** Key configuration for the settings UI. Enables status plus the scoped-secret compatibility save route. */
|
|
22
22
|
envKeys?: EnvKeyConfig[];
|
|
23
23
|
}
|
|
24
|
-
/**
|
|
25
|
-
* Upsert vars into a .env file, preserving existing structure.
|
|
26
|
-
*/
|
|
27
|
-
export declare function upsertEnvFile(envPath: string, vars: Array<{
|
|
28
|
-
key: string;
|
|
29
|
-
value: string;
|
|
30
|
-
}>): Promise<void>;
|
|
31
24
|
export interface CreateServerResult {
|
|
32
25
|
app: ReturnType<typeof createApp>;
|
|
33
26
|
router: ReturnType<typeof createRouter>;
|
|
@@ -36,7 +29,8 @@ export interface CreateServerResult {
|
|
|
36
29
|
* Create a pre-configured H3 app with standard agent-native setup:
|
|
37
30
|
* - CORS headers via middleware
|
|
38
31
|
* - /_agent-native/ping health check
|
|
39
|
-
* - /_agent-native/env-status and
|
|
32
|
+
* - /_agent-native/env-status and the scoped-secret compatibility save route
|
|
33
|
+
* at /_agent-native/env-vars (when envKeys is provided)
|
|
40
34
|
*
|
|
41
35
|
* Returns { app, router } — mount routes on `router`.
|
|
42
36
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-server.d.ts","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create-server.d.ts","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,YAAY,EAOb,MAAM,IAAI,CAAC;AAyBZ,MAAM,WAAW,YAAY;IAC3B,8DAA8D;IAC9D,GAAG,EAAE,MAAM,CAAC;IACZ,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,oFAAoF;IACpF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC;IACvC,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qFAAqF;IACrF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,6GAA6G;IAC7G,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;CAC1B;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;IAClC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;CACzC;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,OAAO,GAAE,mBAAwB,GAChC,kBAAkB,CAmMpB"}
|
|
@@ -1,69 +1,19 @@
|
|
|
1
|
-
import path from "path";
|
|
2
1
|
import { createApp, createRouter, defineEventHandler, getMethod, getRequestHeader, setResponseHeader, setResponseStatus, } from "h3";
|
|
2
|
+
import { getOrgContext } from "../org/context.js";
|
|
3
3
|
import { readBody } from "../server/h3-helpers.js";
|
|
4
|
-
import { agentEnv } from "../shared/agent-env.js";
|
|
5
4
|
import { EMBED_TARGET_HEADER } from "../shared/embed-auth.js";
|
|
6
5
|
import { EMBED_TRANSPLANT_HEADER, isMcpEmbedCorsOrigin, MCP_EMBED_CORS_ALLOW_HEADERS, shouldAllowMcpEmbedCredentials, } from "../shared/mcp-embed-headers.js";
|
|
7
|
-
import {
|
|
6
|
+
import { getSession } from "./auth.js";
|
|
8
7
|
import { getAllowedCorsOrigin, readCorsAllowedOrigins, } from "./cors-origins.js";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
*/
|
|
13
|
-
export async function upsertEnvFile(envPath, vars) {
|
|
14
|
-
// Sanitize: reject values that could inject additional env vars
|
|
15
|
-
for (const { key, value } of vars) {
|
|
16
|
-
if (/[\n\r\0]/.test(value)) {
|
|
17
|
-
throw new Error(`Invalid env var value for ${key}: must not contain newlines or control characters`);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const fs = await import("fs");
|
|
21
|
-
let content = "";
|
|
22
|
-
try {
|
|
23
|
-
content = fs.readFileSync(envPath, "utf-8");
|
|
24
|
-
}
|
|
25
|
-
catch {
|
|
26
|
-
// File doesn't exist yet
|
|
27
|
-
}
|
|
28
|
-
const lines = content.split("\n");
|
|
29
|
-
const remaining = new Map(vars.map((v) => [v.key, v.value]));
|
|
30
|
-
// Update existing lines in place
|
|
31
|
-
const updated = lines.map((line) => {
|
|
32
|
-
const trimmed = line.trim();
|
|
33
|
-
if (!trimmed || trimmed.startsWith("#"))
|
|
34
|
-
return line;
|
|
35
|
-
const eqIndex = trimmed.indexOf("=");
|
|
36
|
-
if (eqIndex === -1)
|
|
37
|
-
return line;
|
|
38
|
-
const key = trimmed.slice(0, eqIndex).trim();
|
|
39
|
-
if (remaining.has(key)) {
|
|
40
|
-
const value = remaining.get(key);
|
|
41
|
-
remaining.delete(key);
|
|
42
|
-
return `${key}=${value}`;
|
|
43
|
-
}
|
|
44
|
-
return line;
|
|
45
|
-
});
|
|
46
|
-
// Append new vars
|
|
47
|
-
for (const [key, value] of remaining) {
|
|
48
|
-
updated.push(`${key}=${value}`);
|
|
49
|
-
}
|
|
50
|
-
// Ensure trailing newline
|
|
51
|
-
let result = updated.join("\n");
|
|
52
|
-
if (!result.endsWith("\n"))
|
|
53
|
-
result += "\n";
|
|
54
|
-
try {
|
|
55
|
-
fs.mkdirSync(path.dirname(envPath), { recursive: true });
|
|
56
|
-
fs.writeFileSync(envPath, result);
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
// Edge runtimes don't have writable filesystem — skip silently
|
|
60
|
-
}
|
|
61
|
-
}
|
|
8
|
+
import { resolveSecret } from "./credential-provider.js";
|
|
9
|
+
import { runWithRequestContext } from "./request-context.js";
|
|
10
|
+
import { findUnsupportedScopedKeyNames, saveKeyValuesToScopedSecrets, ScopedKeyStorageError, } from "./scoped-key-storage.js";
|
|
62
11
|
/**
|
|
63
12
|
* Create a pre-configured H3 app with standard agent-native setup:
|
|
64
13
|
* - CORS headers via middleware
|
|
65
14
|
* - /_agent-native/ping health check
|
|
66
|
-
* - /_agent-native/env-status and
|
|
15
|
+
* - /_agent-native/env-status and the scoped-secret compatibility save route
|
|
16
|
+
* at /_agent-native/env-vars (when envKeys is provided)
|
|
67
17
|
*
|
|
68
18
|
* Returns { app, router } — mount routes on `router`.
|
|
69
19
|
*/
|
|
@@ -155,7 +105,6 @@ export function createServer(options = {}) {
|
|
|
155
105
|
}));
|
|
156
106
|
}
|
|
157
107
|
const router = createRouter();
|
|
158
|
-
app.use(router);
|
|
159
108
|
// Health check
|
|
160
109
|
if (!options.disablePing) {
|
|
161
110
|
router.get("/_agent-native/ping", defineEventHandler(() => {
|
|
@@ -166,52 +115,49 @@ export function createServer(options = {}) {
|
|
|
166
115
|
// Env key management routes
|
|
167
116
|
if (options.envKeys) {
|
|
168
117
|
const envKeys = options.envKeys;
|
|
169
|
-
|
|
170
|
-
|
|
118
|
+
const allowedEnvKeyNames = envKeys.map(({ key }) => key);
|
|
119
|
+
router.get("/_agent-native/env-status", defineEventHandler(async (event) => {
|
|
120
|
+
const session = await getSession(event).catch(() => null);
|
|
121
|
+
const userEmail = session?.email;
|
|
122
|
+
let orgId;
|
|
123
|
+
if (userEmail) {
|
|
124
|
+
const orgCtx = await getOrgContext(event).catch(() => null);
|
|
125
|
+
orgId = orgCtx?.orgId ?? undefined;
|
|
126
|
+
}
|
|
127
|
+
return Promise.all(envKeys.map(async (cfg) => ({
|
|
171
128
|
key: cfg.key,
|
|
172
129
|
label: cfg.label,
|
|
173
130
|
required: cfg.required ?? false,
|
|
174
|
-
configured:
|
|
131
|
+
configured: Boolean(process.env[cfg.key]) ||
|
|
132
|
+
(await runWithRequestContext({ userEmail, orgId }, () => resolveSecret(cfg.key).then(Boolean))),
|
|
175
133
|
...(cfg.helpText ? { helpText: cfg.helpText } : {}),
|
|
176
|
-
}));
|
|
134
|
+
})));
|
|
177
135
|
}));
|
|
178
136
|
router.post("/_agent-native/env-vars", defineEventHandler(async (event) => {
|
|
179
|
-
// Env vars are deployment-wide globals — see isEnvVarWriteAllowed
|
|
180
|
-
// above. Disable the endpoint on any multi-tenant deploy.
|
|
181
|
-
if (!isEnvVarWriteAllowed()) {
|
|
182
|
-
setResponseStatus(event, 403);
|
|
183
|
-
return {
|
|
184
|
-
error: "env-vars endpoint disabled on multi-tenant deployments. Use scoped secrets or credentials for user/org API keys.",
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
137
|
const body = await readBody(event);
|
|
188
|
-
const { vars } = body;
|
|
189
|
-
|
|
138
|
+
const { vars, scope } = body;
|
|
139
|
+
const unsupportedKeys = findUnsupportedScopedKeyNames(vars, allowedEnvKeyNames);
|
|
140
|
+
if (unsupportedKeys.length > 0) {
|
|
190
141
|
setResponseStatus(event, 400);
|
|
191
|
-
return {
|
|
142
|
+
return {
|
|
143
|
+
error: `Unsupported env key${unsupportedKeys.length === 1 ? "" : "s"}: ${unsupportedKeys.join(", ")}`,
|
|
144
|
+
};
|
|
192
145
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
const filtered = vars.filter((v) => typeof v.key === "string" &&
|
|
197
|
-
allowedKeys.has(v.key) &&
|
|
198
|
-
!blockedEnvVarWriteKeys.has(v.key));
|
|
199
|
-
if (filtered.length === 0) {
|
|
200
|
-
setResponseStatus(event, 400);
|
|
201
|
-
return { error: "No recognized env keys in request" };
|
|
146
|
+
try {
|
|
147
|
+
const result = await saveKeyValuesToScopedSecrets(event, vars, scope);
|
|
148
|
+
return { saved: result.saved, storage: "scoped-secrets" };
|
|
202
149
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
150
|
+
catch (err) {
|
|
151
|
+
if (err instanceof ScopedKeyStorageError) {
|
|
152
|
+
setResponseStatus(event, err.statusCode);
|
|
153
|
+
return { error: err.message };
|
|
154
|
+
}
|
|
155
|
+
setResponseStatus(event, 500);
|
|
156
|
+
return { error: "Failed to save keys" };
|
|
209
157
|
}
|
|
210
|
-
// Notify parent (Builder or frame) via postMessage
|
|
211
|
-
agentEnv.setVars(filtered);
|
|
212
|
-
return { saved: filtered.map((v) => v.key) };
|
|
213
158
|
}));
|
|
214
159
|
}
|
|
160
|
+
app.use(router);
|
|
215
161
|
return { app, router };
|
|
216
162
|
}
|
|
217
163
|
//# sourceMappingURL=create-server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-server.js","sourceRoot":"","sources":["../../src/server/create-server.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EACL,oBAAoB,EACpB,sBAAsB,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AAqB;YACrB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;YACjD,MAAM,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAEvC,oEAAoE;YACpE,KAAK,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,QAAQ,EAAE,CAAC;gBACtC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC3B,CAAC;YAED,mDAAmD;YACnD,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAE3B,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import path from \"path\";\n\nimport {\n createApp,\n createRouter,\n defineEventHandler,\n getMethod,\n getRequestHeader,\n setResponseHeader,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { agentEnv } from \"../shared/agent-env.js\";\nimport { EMBED_TARGET_HEADER } from \"../shared/embed-auth.js\";\nimport {\n EMBED_TRANSPLANT_HEADER,\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n shouldAllowMcpEmbedCredentials,\n} from \"../shared/mcp-embed-headers.js\";\nimport { BUILDER_ENV_KEYS } from \"./builder-browser.js\";\nimport {\n getAllowedCorsOrigin,\n readCorsAllowedOrigins,\n} from \"./cors-origins.js\";\nimport { isEnvVarWriteAllowed } from \"./env-var-writes.js\";\n\nexport interface EnvKeyConfig {\n /** Environment variable name (e.g. \"HUBSPOT_ACCESS_TOKEN\") */\n key: string;\n /** Human-readable label (e.g. \"HubSpot\") */\n label: string;\n /** Whether this key is required for the app to function */\n required?: boolean;\n /** Optional UI hint shown next to the field describing where to find this value. */\n helpText?: string;\n}\n\nexport interface CreateServerOptions {\n /** CORS options. Ignored (H3 handles CORS via middleware). Default: enabled. */\n cors?: Record<string, unknown> | false;\n /** JSON body parser limit. Kept for API compatibility (H3 uses readBody). */\n jsonLimit?: string;\n /** Custom ping message. Default: reads PING_MESSAGE env var, falls back to \"pong\" */\n pingMessage?: string;\n /** Disable the /_agent-native/ping health check. Default: false */\n disablePing?: boolean;\n /** Env key configuration for the settings UI. Enables /_agent-native/env-status and /_agent-native/env-vars routes. */\n envKeys?: EnvKeyConfig[];\n}\n\n/**\n * Upsert vars into a .env file, preserving existing structure.\n */\nexport async function upsertEnvFile(\n envPath: string,\n vars: Array<{ key: string; value: string }>,\n): Promise<void> {\n // Sanitize: reject values that could inject additional env vars\n for (const { key, value } of vars) {\n if (/[\\n\\r\\0]/.test(value)) {\n throw new Error(\n `Invalid env var value for ${key}: must not contain newlines or control characters`,\n );\n }\n }\n\n const fs = await import(\"fs\");\n\n let content = \"\";\n try {\n content = fs.readFileSync(envPath, \"utf-8\");\n } catch {\n // File doesn't exist yet\n }\n\n const lines = content.split(\"\\n\");\n const remaining = new Map(vars.map((v) => [v.key, v.value]));\n\n // Update existing lines in place\n const updated = lines.map((line) => {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) return line;\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) return line;\n const key = trimmed.slice(0, eqIndex).trim();\n if (remaining.has(key)) {\n const value = remaining.get(key)!;\n remaining.delete(key);\n return `${key}=${value}`;\n }\n return line;\n });\n\n // Append new vars\n for (const [key, value] of remaining) {\n updated.push(`${key}=${value}`);\n }\n\n // Ensure trailing newline\n let result = updated.join(\"\\n\");\n if (!result.endsWith(\"\\n\")) result += \"\\n\";\n\n try {\n fs.mkdirSync(path.dirname(envPath), { recursive: true });\n fs.writeFileSync(envPath, result);\n } catch {\n // Edge runtimes don't have writable filesystem — skip silently\n }\n}\n\nexport interface CreateServerResult {\n app: ReturnType<typeof createApp>;\n router: ReturnType<typeof createRouter>;\n}\n\n/**\n * Create a pre-configured H3 app with standard agent-native setup:\n * - CORS headers via middleware\n * - /_agent-native/ping health check\n * - /_agent-native/env-status and /_agent-native/env-vars (when envKeys is provided)\n *\n * Returns { app, router } — mount routes on `router`.\n */\nexport function createServer(\n options: CreateServerOptions = {},\n): CreateServerResult {\n const app = createApp({\n onError(error, event) {\n // Suppress connection-reset errors — client disconnected mid-request (tab close, reload)\n const err = error as NodeJS.ErrnoException;\n const code = err?.code || (err?.cause as NodeJS.ErrnoException)?.code;\n if (code === \"ECONNRESET\" || code === \"ECONNABORTED\") return;\n if (err?.message === \"aborted\") return;\n console.error(\n `[agent-native] Server error: ${event.method} ${event.path}`,\n error,\n );\n },\n });\n\n // CORS middleware\n if (options.cors !== false) {\n const allowedOrigins = readCorsAllowedOrigins();\n const isProduction = process.env.NODE_ENV === \"production\";\n\n /**\n * When CORS_ALLOWED_ORIGINS is unset, production only allows trusted\n * localhost/native desktop origins. Development keeps the legacy \"echo\n * any origin\" behavior so local tools and docs previews keep working.\n */\n app.use(\n defineEventHandler((event) => {\n const requestOrigin = getRequestHeader(event, \"origin\");\n const method = getMethod(event);\n const requestedHeaders = String(\n getRequestHeader(event, \"access-control-request-headers\") ?? \"\",\n )\n .toLowerCase()\n .split(\",\")\n .map((header) => header.trim());\n const embedCorsRequest =\n isMcpEmbedCorsOrigin(requestOrigin) &&\n (requestedHeaders.includes(EMBED_TARGET_HEADER.toLowerCase()) ||\n requestedHeaders.includes(EMBED_TRANSPLANT_HEADER) ||\n Boolean(getRequestHeader(event, EMBED_TARGET_HEADER)) ||\n Boolean(getRequestHeader(event, EMBED_TRANSPLANT_HEADER)) ||\n Boolean(getRequestHeader(event, \"authorization\")));\n\n /**\n * Decide whether the requesting origin is allowed. We never fall back\n * to \"the first allowlist entry\" when the origin isn't in the list —\n * that previously sent `Access-Control-Allow-Origin: <other-origin>`\n * with credentials enabled to attacker-controlled origins, which was\n * permissive enough that some clients followed through with the\n * credentialed request.\n */\n const allowedOrigin = embedCorsRequest\n ? requestOrigin\n : getAllowedCorsOrigin(requestOrigin, {\n allowedOrigins,\n allowAnyOriginWhenNoAllowlist: !isProduction,\n // Let the cors-origins default apply (dev-only). Passing `true`\n // here unconditionally would re-open the production localhost gap.\n });\n // No origin header at all (same-origin fetch, server-to-server) and\n // no allowlist → fall through with `*`-equivalent behaviour: omit\n // ACAO entirely and let the browser apply its same-origin default.\n\n if (allowedOrigin) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Origin\",\n allowedOrigin,\n );\n setResponseHeader(event, \"Vary\", \"Origin\");\n // A specific origin means we can honor credentialed requests\n // (fetch with `credentials: \"include\"` — used by desktop tray\n // apps that share a same-site cookie with the web app). The\n // wildcard `*` is spec-incompatible with credentials, so only\n // set this when we're echoing a concrete origin.\n if (shouldAllowMcpEmbedCredentials(allowedOrigin)) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Credentials\",\n \"true\",\n );\n }\n } else if (!requestOrigin) {\n // No origin header — preserve the legacy permissive behaviour for\n // tools/scripts that hit the API directly (no credentialed CORS\n // semantics apply when there's no Origin).\n setResponseHeader(event, \"Access-Control-Allow-Origin\", \"*\");\n }\n\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n MCP_EMBED_CORS_ALLOW_HEADERS,\n );\n\n if (method === \"OPTIONS\") {\n // Reject preflights from disallowed cross-origin callers. We only\n // 204 if either (a) there was no Origin header (same-origin or\n // direct script invocation) or (b) the origin was in the allowlist\n // / dev fallback above. Otherwise we 403 so the browser surfaces\n // a hard CORS failure rather than blindly retrying with credentials.\n if (requestOrigin && !allowedOrigin) {\n return new Response(null, { status: 403 });\n }\n return new Response(null, { status: 204 });\n }\n }),\n );\n }\n\n const router = createRouter();\n app.use(router);\n\n // Health check\n if (!options.disablePing) {\n router.get(\n \"/_agent-native/ping\",\n defineEventHandler(() => {\n const message =\n options.pingMessage ?? process.env.PING_MESSAGE ?? \"pong\";\n return { message };\n }),\n );\n }\n\n // Env key management routes\n if (options.envKeys) {\n const envKeys = options.envKeys;\n\n router.get(\n \"/_agent-native/env-status\",\n defineEventHandler(() => {\n return envKeys.map((cfg) => ({\n key: cfg.key,\n label: cfg.label,\n required: cfg.required ?? false,\n configured: !!process.env[cfg.key],\n ...(cfg.helpText ? { helpText: cfg.helpText } : {}),\n }));\n }),\n );\n\n router.post(\n \"/_agent-native/env-vars\",\n defineEventHandler(async (event: H3Event) => {\n // Env vars are deployment-wide globals — see isEnvVarWriteAllowed\n // above. Disable the endpoint on any multi-tenant deploy.\n if (!isEnvVarWriteAllowed()) {\n setResponseStatus(event, 403);\n return {\n error:\n \"env-vars endpoint disabled on multi-tenant deployments. Use scoped secrets or credentials for user/org API keys.\",\n };\n }\n\n const body = await readBody(event);\n const { vars } = body as {\n vars?: Array<{ key: string; value: string }>;\n };\n\n if (!Array.isArray(vars) || vars.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"vars array required\" };\n }\n\n // Only allow keys that are in the env config\n const allowedKeys = new Set(envKeys.map((k) => k.key));\n const blockedEnvVarWriteKeys = new Set<string>(BUILDER_ENV_KEYS);\n const filtered = vars.filter(\n (v) =>\n typeof v.key === \"string\" &&\n allowedKeys.has(v.key) &&\n !blockedEnvVarWriteKeys.has(v.key),\n );\n if (filtered.length === 0) {\n setResponseStatus(event, 400);\n return { error: \"No recognized env keys in request\" };\n }\n\n // Write to .env file\n const envPath = path.join(process.cwd(), \".env\");\n await upsertEnvFile(envPath, filtered);\n\n // Update process.env so the app picks up the new values immediately\n for (const { key, value } of filtered) {\n process.env[key] = value;\n }\n\n // Notify parent (Builder or frame) via postMessage\n agentEnv.setVars(filtered);\n\n return { saved: filtered.map((v) => v.key) };\n }),\n );\n }\n\n return { app, router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CAAC;YAC5D,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAI,GAAG,YAAY,qBAAqB,EAAE,CAAC;oBACzC,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;oBACzC,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;gBAChC,CAAC;gBACD,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;gBAC9B,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC;YAC1C,CAAC;QACH,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAED,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAChB,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n createApp,\n createRouter,\n defineEventHandler,\n getMethod,\n getRequestHeader,\n setResponseHeader,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { getOrgContext } from \"../org/context.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { EMBED_TARGET_HEADER } from \"../shared/embed-auth.js\";\nimport {\n EMBED_TRANSPLANT_HEADER,\n isMcpEmbedCorsOrigin,\n MCP_EMBED_CORS_ALLOW_HEADERS,\n shouldAllowMcpEmbedCredentials,\n} from \"../shared/mcp-embed-headers.js\";\nimport { getSession } from \"./auth.js\";\nimport {\n getAllowedCorsOrigin,\n readCorsAllowedOrigins,\n} from \"./cors-origins.js\";\nimport { resolveSecret } from \"./credential-provider.js\";\nimport { runWithRequestContext } from \"./request-context.js\";\nimport {\n findUnsupportedScopedKeyNames,\n saveKeyValuesToScopedSecrets,\n ScopedKeyStorageError,\n type ScopedKeySaveRequestScope,\n} from \"./scoped-key-storage.js\";\n\nexport interface EnvKeyConfig {\n /** Environment variable name (e.g. \"HUBSPOT_ACCESS_TOKEN\") */\n key: string;\n /** Human-readable label (e.g. \"HubSpot\") */\n label: string;\n /** Whether this key is required for the app to function */\n required?: boolean;\n /** Optional UI hint shown next to the field describing where to find this value. */\n helpText?: string;\n}\n\nexport interface CreateServerOptions {\n /** CORS options. Ignored (H3 handles CORS via middleware). Default: enabled. */\n cors?: Record<string, unknown> | false;\n /** JSON body parser limit. Kept for API compatibility (H3 uses readBody). */\n jsonLimit?: string;\n /** Custom ping message. Default: reads PING_MESSAGE env var, falls back to \"pong\" */\n pingMessage?: string;\n /** Disable the /_agent-native/ping health check. Default: false */\n disablePing?: boolean;\n /** Key configuration for the settings UI. Enables status plus the scoped-secret compatibility save route. */\n envKeys?: EnvKeyConfig[];\n}\n\nexport interface CreateServerResult {\n app: ReturnType<typeof createApp>;\n router: ReturnType<typeof createRouter>;\n}\n\n/**\n * Create a pre-configured H3 app with standard agent-native setup:\n * - CORS headers via middleware\n * - /_agent-native/ping health check\n * - /_agent-native/env-status and the scoped-secret compatibility save route\n * at /_agent-native/env-vars (when envKeys is provided)\n *\n * Returns { app, router } — mount routes on `router`.\n */\nexport function createServer(\n options: CreateServerOptions = {},\n): CreateServerResult {\n const app = createApp({\n onError(error, event) {\n // Suppress connection-reset errors — client disconnected mid-request (tab close, reload)\n const err = error as NodeJS.ErrnoException;\n const code = err?.code || (err?.cause as NodeJS.ErrnoException)?.code;\n if (code === \"ECONNRESET\" || code === \"ECONNABORTED\") return;\n if (err?.message === \"aborted\") return;\n console.error(\n `[agent-native] Server error: ${event.method} ${event.path}`,\n error,\n );\n },\n });\n\n // CORS middleware\n if (options.cors !== false) {\n const allowedOrigins = readCorsAllowedOrigins();\n const isProduction = process.env.NODE_ENV === \"production\";\n\n /**\n * When CORS_ALLOWED_ORIGINS is unset, production only allows trusted\n * localhost/native desktop origins. Development keeps the legacy \"echo\n * any origin\" behavior so local tools and docs previews keep working.\n */\n app.use(\n defineEventHandler((event) => {\n const requestOrigin = getRequestHeader(event, \"origin\");\n const method = getMethod(event);\n const requestedHeaders = String(\n getRequestHeader(event, \"access-control-request-headers\") ?? \"\",\n )\n .toLowerCase()\n .split(\",\")\n .map((header) => header.trim());\n const embedCorsRequest =\n isMcpEmbedCorsOrigin(requestOrigin) &&\n (requestedHeaders.includes(EMBED_TARGET_HEADER.toLowerCase()) ||\n requestedHeaders.includes(EMBED_TRANSPLANT_HEADER) ||\n Boolean(getRequestHeader(event, EMBED_TARGET_HEADER)) ||\n Boolean(getRequestHeader(event, EMBED_TRANSPLANT_HEADER)) ||\n Boolean(getRequestHeader(event, \"authorization\")));\n\n /**\n * Decide whether the requesting origin is allowed. We never fall back\n * to \"the first allowlist entry\" when the origin isn't in the list —\n * that previously sent `Access-Control-Allow-Origin: <other-origin>`\n * with credentials enabled to attacker-controlled origins, which was\n * permissive enough that some clients followed through with the\n * credentialed request.\n */\n const allowedOrigin = embedCorsRequest\n ? requestOrigin\n : getAllowedCorsOrigin(requestOrigin, {\n allowedOrigins,\n allowAnyOriginWhenNoAllowlist: !isProduction,\n // Let the cors-origins default apply (dev-only). Passing `true`\n // here unconditionally would re-open the production localhost gap.\n });\n // No origin header at all (same-origin fetch, server-to-server) and\n // no allowlist → fall through with `*`-equivalent behaviour: omit\n // ACAO entirely and let the browser apply its same-origin default.\n\n if (allowedOrigin) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Origin\",\n allowedOrigin,\n );\n setResponseHeader(event, \"Vary\", \"Origin\");\n // A specific origin means we can honor credentialed requests\n // (fetch with `credentials: \"include\"` — used by desktop tray\n // apps that share a same-site cookie with the web app). The\n // wildcard `*` is spec-incompatible with credentials, so only\n // set this when we're echoing a concrete origin.\n if (shouldAllowMcpEmbedCredentials(allowedOrigin)) {\n setResponseHeader(\n event,\n \"Access-Control-Allow-Credentials\",\n \"true\",\n );\n }\n } else if (!requestOrigin) {\n // No origin header — preserve the legacy permissive behaviour for\n // tools/scripts that hit the API directly (no credentialed CORS\n // semantics apply when there's no Origin).\n setResponseHeader(event, \"Access-Control-Allow-Origin\", \"*\");\n }\n\n setResponseHeader(\n event,\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n );\n setResponseHeader(\n event,\n \"Access-Control-Allow-Headers\",\n MCP_EMBED_CORS_ALLOW_HEADERS,\n );\n\n if (method === \"OPTIONS\") {\n // Reject preflights from disallowed cross-origin callers. We only\n // 204 if either (a) there was no Origin header (same-origin or\n // direct script invocation) or (b) the origin was in the allowlist\n // / dev fallback above. Otherwise we 403 so the browser surfaces\n // a hard CORS failure rather than blindly retrying with credentials.\n if (requestOrigin && !allowedOrigin) {\n return new Response(null, { status: 403 });\n }\n return new Response(null, { status: 204 });\n }\n }),\n );\n }\n\n const router = createRouter();\n\n // Health check\n if (!options.disablePing) {\n router.get(\n \"/_agent-native/ping\",\n defineEventHandler(() => {\n const message =\n options.pingMessage ?? process.env.PING_MESSAGE ?? \"pong\";\n return { message };\n }),\n );\n }\n\n // Env key management routes\n if (options.envKeys) {\n const envKeys = options.envKeys;\n const allowedEnvKeyNames = envKeys.map(({ key }) => key);\n\n router.get(\n \"/_agent-native/env-status\",\n defineEventHandler(async (event) => {\n const session = await getSession(event).catch(() => null);\n const userEmail = session?.email;\n let orgId: string | undefined;\n if (userEmail) {\n const orgCtx = await getOrgContext(event).catch(() => null);\n orgId = orgCtx?.orgId ?? undefined;\n }\n return Promise.all(\n envKeys.map(async (cfg) => ({\n key: cfg.key,\n label: cfg.label,\n required: cfg.required ?? false,\n configured:\n Boolean(process.env[cfg.key]) ||\n (await runWithRequestContext({ userEmail, orgId }, () =>\n resolveSecret(cfg.key).then(Boolean),\n )),\n ...(cfg.helpText ? { helpText: cfg.helpText } : {}),\n })),\n );\n }),\n );\n\n router.post(\n \"/_agent-native/env-vars\",\n defineEventHandler(async (event: H3Event) => {\n const body = await readBody(event);\n const { vars, scope } = body as {\n vars?: Array<{ key: string; value: string }>;\n scope?: ScopedKeySaveRequestScope;\n };\n const unsupportedKeys = findUnsupportedScopedKeyNames(\n vars,\n allowedEnvKeyNames,\n );\n if (unsupportedKeys.length > 0) {\n setResponseStatus(event, 400);\n return {\n error: `Unsupported env key${unsupportedKeys.length === 1 ? \"\" : \"s\"}: ${unsupportedKeys.join(\", \")}`,\n };\n }\n try {\n const result = await saveKeyValuesToScopedSecrets(event, vars, scope);\n return { saved: result.saved, storage: \"scoped-secrets\" };\n } catch (err) {\n if (err instanceof ScopedKeyStorageError) {\n setResponseStatus(event, err.statusCode);\n return { error: err.message };\n }\n setResponseStatus(event, 500);\n return { error: \"Failed to save keys\" };\n }\n }),\n );\n }\n\n app.use(router);\n return { app, router };\n}\n"]}
|
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
* Framework-level agent action for sending transactional/notification emails
|
|
3
3
|
* via the configured core email transport (Resend or SendGrid).
|
|
4
4
|
*
|
|
5
|
-
* Registered as a native tool in every template
|
|
6
|
-
*
|
|
7
|
-
* from the agent surface so the agent never sees it.
|
|
5
|
+
* Registered as a native tool in every template. sendEmail() checks the
|
|
6
|
+
* scoped Resend/SendGrid configuration at call time.
|
|
8
7
|
*
|
|
9
8
|
* SAFETY: the action description instructs the agent to draft-first and only
|
|
10
9
|
* send when the user explicitly confirms, matching the mail template convention.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-actions.d.ts","sourceRoot":"","sources":["../../src/server/email-actions.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"email-actions.d.ts","sourceRoot":"","sources":["../../src/server/email-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAmGhE,wBAAgB,4BAA4B,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAsG1E"}
|
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
* Framework-level agent action for sending transactional/notification emails
|
|
3
3
|
* via the configured core email transport (Resend or SendGrid).
|
|
4
4
|
*
|
|
5
|
-
* Registered as a native tool in every template
|
|
6
|
-
*
|
|
7
|
-
* from the agent surface so the agent never sees it.
|
|
5
|
+
* Registered as a native tool in every template. sendEmail() checks the
|
|
6
|
+
* scoped Resend/SendGrid configuration at call time.
|
|
8
7
|
*
|
|
9
8
|
* SAFETY: the action description instructs the agent to draft-first and only
|
|
10
9
|
* send when the user explicitly confirms, matching the mail template convention.
|
|
@@ -14,7 +13,7 @@
|
|
|
14
13
|
* when both would be present under the same key. To avoid any ambiguity this
|
|
15
14
|
* action is keyed "core-send-email" which is distinct from the template name.
|
|
16
15
|
*/
|
|
17
|
-
import {
|
|
16
|
+
import { sendEmail } from "./email.js";
|
|
18
17
|
function markdownToText(md) {
|
|
19
18
|
return md
|
|
20
19
|
.replace(/!\[([^\]]*)\]\([^\s)]+\)/g, "$1")
|
|
@@ -91,8 +90,6 @@ function markdownToHtml(md) {
|
|
|
91
90
|
return html;
|
|
92
91
|
}
|
|
93
92
|
export function createCoreEmailActionEntries() {
|
|
94
|
-
if (!isEmailConfigured())
|
|
95
|
-
return {};
|
|
96
93
|
return {
|
|
97
94
|
"core-send-email": {
|
|
98
95
|
tool: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-actions.js","sourceRoot":"","sources":["../../src/server/email-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE1D,SAAS,cAAc,CAAC,EAAU;IAChC,OAAO,EAAE;SACN,OAAO,CAAC,2BAA2B,EAAE,IAAI,CAAC;SAC1C,OAAO,CAAC,0BAA0B,EAAE,SAAS,CAAC;SAC9C,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC;SAC3B,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC;SACjC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;SAC/B,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;SAC3B,IAAI,EAAE,CAAC;AACZ,CAAC;AAED,SAAS,cAAc,CAAC,EAAU;IAChC,MAAM,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CAAC,EAAE,CAAC;oBAC5C,OAAO,iBAAiB,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG,CAAC;gBACvD,CAAC;gBAAC,OAAO,GAAY,EAAE,CAAC;oBACtB,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC7D,OAAO,wBAAwB,GAAG,EAAE,CAAC;gBACvC,CAAC;YACH,CAAC;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Framework-level agent action for sending transactional/notification emails\n * via the configured core email transport (Resend or SendGrid).\n *\n * Registered as a native tool in every template when RESEND_API_KEY or\n * SENDGRID_API_KEY is set. When neither key is present the tool is omitted\n * from the agent surface so the agent never sees it.\n *\n * SAFETY: the action description instructs the agent to draft-first and only\n * send when the user explicitly confirms, matching the mail template convention.\n *\n * COLLISION: the mail template registers its own richer \"send-email\" action.\n * The template's registration comes after this one in the spread, so it wins\n * when both would be present under the same key. To avoid any ambiguity this\n * action is keyed \"core-send-email\" which is distinct from the template name.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { isEmailConfigured, sendEmail } from \"./email.js\";\n\nfunction markdownToText(md: string): string {\n return md\n .replace(/!\\[([^\\]]*)\\]\\([^\\s)]+\\)/g, \"$1\")\n .replace(/\\[([^\\]]+)\\]\\([^\\s)]+\\)/g, \"$1 ($2)\")\n .replace(/`([^`]+)`/g, \"$1\")\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"$1\")\n .replace(/\\*([^*\\n]+)\\*/g, \"$1\")\n .replace(/^#{1,6}\\s+/gm, \"\")\n .trim();\n}\n\nfunction markdownToHtml(md: string): string {\n const normalized = md.replace(/\\r\\n/g, \"\\n\").trim();\n if (!normalized) return \"<p></p>\";\n\n // Escape HTML entities in a string, preserving already-encoded references.\n const esc = (s: string) =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n\n // Inline markdown: links, bold, italic, code, bare URLs.\n const inline = (s: string): string =>\n s\n .replace(\n /\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g,\n (_m, label: string, url: string) =>\n `<a href=\"${esc(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(label)}</a>`,\n )\n .replace(\n /(^|[^\\w\"'=])(https?:\\/\\/[^\\s<]+)/g,\n (_m, pre: string, url: string) =>\n `${pre}<a href=\"${esc(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(url)}</a>`,\n )\n .replace(/`([^`]+)`/g, (_m, code: string) => `<code>${esc(code)}</code>`)\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[\\s(])\\*([^*\\n]+)\\*(?=$|[\\s).,!?:;])/g, \"$1<em>$2</em>\");\n\n const blocks = normalized.split(/\\n{2,}/);\n const html = blocks\n .map((block) => {\n const trimmed = block.trim();\n\n // Fenced code block\n if (trimmed.startsWith(\"```\") && trimmed.endsWith(\"```\")) {\n const code = trimmed\n .replace(/^```[^\\n]*\\n?/, \"\")\n .replace(/\\n?```$/, \"\");\n return `<pre><code>${esc(code)}</code></pre>`;\n }\n\n // Heading\n const hm = trimmed.match(/^(#{1,6})\\s+(.+)$/);\n if (hm) {\n const level = hm[1].length;\n return `<h${level}>${inline(hm[2])}</h${level}>`;\n }\n\n // Unordered list\n if (/^[-*+]\\s+/m.test(trimmed)) {\n const items = trimmed\n .split(\"\\n\")\n .filter(Boolean)\n .map((l) => `<li>${inline(l.replace(/^[-*+]\\s+/, \"\"))}</li>`)\n .join(\"\");\n return `<ul style=\"margin:0 0 1em;padding-left:1.5em\">${items}</ul>`;\n }\n\n // Ordered list\n if (/^\\d+\\.\\s+/m.test(trimmed)) {\n const items = trimmed\n .split(\"\\n\")\n .filter(Boolean)\n .map((l) => `<li>${inline(l.replace(/^\\d+\\.\\s+/, \"\"))}</li>`)\n .join(\"\");\n return `<ol style=\"margin:0 0 1em;padding-left:1.5em\">${items}</ol>`;\n }\n\n // Blockquote\n if (trimmed.startsWith(\"> \")) {\n const inner = trimmed\n .split(\"\\n\")\n .map((l) => (l.startsWith(\"> \") ? l.slice(2) : l))\n .join(\"\\n\");\n return `<blockquote style=\"margin:0 0 1em 1em;border-left:3px solid #ccc;padding-left:0.75em;color:#555\">${inline(inner)}</blockquote>`;\n }\n\n return `<p style=\"margin:0 0 1em\">${inline(trimmed).replace(/\\n/g, \"<br />\")}</p>`;\n })\n .join(\"\");\n\n return html;\n}\n\nexport function createCoreEmailActionEntries(): Record<string, ActionEntry> {\n if (!isEmailConfigured()) return {};\n\n return {\n \"core-send-email\": {\n tool: {\n description: [\n \"Send a transactional email via the app's configured email provider (Resend or SendGrid).\",\n \"\",\n \"IMPORTANT — DRAFT-FIRST SAFETY RULE: Never call this tool until the user has explicitly\",\n \"confirmed they want to send. Always compose the full email content first, show it to the\",\n \"user, and wait for an explicit 'yes, send it' before invoking this action.\",\n \"\",\n \"The body is written in markdown. Tables, lists, bold, italic, links, and code blocks\",\n \"are all supported and will render correctly in email clients.\",\n \"\",\n \"This sends via the framework transport (Resend/SendGrid). It is NOT the Gmail-based\",\n \"send-email action in the mail template — use this for system/notification emails from\",\n \"any template.\",\n ].join(\"\\n\"),\n parameters: {\n type: \"object\" as const,\n properties: {\n to: {\n type: \"string\",\n description: \"Recipient email address.\",\n },\n subject: {\n type: \"string\",\n description: \"Email subject line.\",\n },\n body: {\n type: \"string\",\n description:\n \"Email body in markdown. Tables, lists, headings, bold, italic, links, and code blocks are supported.\",\n },\n cc: {\n type: \"string\",\n description: \"CC email address (single address only).\",\n },\n bcc: {\n type: \"string\",\n description: \"BCC email address (single address only).\",\n },\n replyTo: {\n type: \"string\",\n description:\n \"Reply-To address. Useful when sending on behalf of someone.\",\n },\n from: {\n type: \"string\",\n description:\n 'Override the sender address. Must be a verified sender for the configured provider. Example: \"Team Name <team@example.com>\". Leave unset to use the default EMAIL_FROM env var.',\n },\n },\n required: [\"to\", \"subject\", \"body\"],\n },\n },\n run: async (input: Record<string, unknown>) => {\n const to = typeof input.to === \"string\" ? input.to.trim() : \"\";\n const subject =\n typeof input.subject === \"string\" ? input.subject.trim() : \"\";\n const bodyMd = typeof input.body === \"string\" ? input.body.trim() : \"\";\n const cc =\n typeof input.cc === \"string\" && input.cc.trim()\n ? input.cc.trim()\n : undefined;\n const bcc =\n typeof input.bcc === \"string\" && input.bcc.trim()\n ? input.bcc.trim()\n : undefined;\n const replyTo =\n typeof input.replyTo === \"string\" && input.replyTo.trim()\n ? input.replyTo.trim()\n : undefined;\n const from =\n typeof input.from === \"string\" && input.from.trim()\n ? input.from.trim()\n : undefined;\n\n if (!to) return \"Error: 'to' is required.\";\n if (!subject) return \"Error: 'subject' is required.\";\n if (!bodyMd) return \"Error: 'body' is required.\";\n\n try {\n await sendEmail({\n to,\n subject,\n html: markdownToHtml(bodyMd),\n text: markdownToText(bodyMd),\n ...(from ? { from } : {}),\n ...(cc ? { cc } : {}),\n ...(replyTo ? { replyTo } : {}),\n });\n\n const bccNote = bcc ? ` (bcc: ${bcc})` : \"\";\n return `Email sent to ${to}${bccNote}: \"${subject}\"`;\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n return `Error sending email: ${msg}`;\n }\n },\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"email-actions.js","sourceRoot":"","sources":["../../src/server/email-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,SAAS,cAAc,CAAC,EAAU;IAChC,OAAO,EAAE;SACN,OAAO,CAAC,2BAA2B,EAAE,IAAI,CAAC;SAC1C,OAAO,CAAC,0BAA0B,EAAE,SAAS,CAAC;SAC9C,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC;SAC3B,OAAO,CAAC,kBAAkB,EAAE,IAAI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AAC,EAAE,CAAC;qBAChC,CAAC,CAAC;oBAEH,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC5C,OAAO,iBAAiB,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG,CAAC;gBACvD,CAAC;gBAAC,OAAO,GAAY,EAAE,CAAC;oBACtB,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC7D,OAAO,wBAAwB,GAAG,EAAE,CAAC;gBACvC,CAAC;YACH,CAAC;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Framework-level agent action for sending transactional/notification emails\n * via the configured core email transport (Resend or SendGrid).\n *\n * Registered as a native tool in every template. sendEmail() checks the\n * scoped Resend/SendGrid configuration at call time.\n *\n * SAFETY: the action description instructs the agent to draft-first and only\n * send when the user explicitly confirms, matching the mail template convention.\n *\n * COLLISION: the mail template registers its own richer \"send-email\" action.\n * The template's registration comes after this one in the spread, so it wins\n * when both would be present under the same key. To avoid any ambiguity this\n * action is keyed \"core-send-email\" which is distinct from the template name.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { sendEmail } from \"./email.js\";\n\nfunction markdownToText(md: string): string {\n return md\n .replace(/!\\[([^\\]]*)\\]\\([^\\s)]+\\)/g, \"$1\")\n .replace(/\\[([^\\]]+)\\]\\([^\\s)]+\\)/g, \"$1 ($2)\")\n .replace(/`([^`]+)`/g, \"$1\")\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"$1\")\n .replace(/\\*([^*\\n]+)\\*/g, \"$1\")\n .replace(/^#{1,6}\\s+/gm, \"\")\n .trim();\n}\n\nfunction markdownToHtml(md: string): string {\n const normalized = md.replace(/\\r\\n/g, \"\\n\").trim();\n if (!normalized) return \"<p></p>\";\n\n // Escape HTML entities in a string, preserving already-encoded references.\n const esc = (s: string) =>\n s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n\n // Inline markdown: links, bold, italic, code, bare URLs.\n const inline = (s: string): string =>\n s\n .replace(\n /\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g,\n (_m, label: string, url: string) =>\n `<a href=\"${esc(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(label)}</a>`,\n )\n .replace(\n /(^|[^\\w\"'=])(https?:\\/\\/[^\\s<]+)/g,\n (_m, pre: string, url: string) =>\n `${pre}<a href=\"${esc(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${esc(url)}</a>`,\n )\n .replace(/`([^`]+)`/g, (_m, code: string) => `<code>${esc(code)}</code>`)\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[\\s(])\\*([^*\\n]+)\\*(?=$|[\\s).,!?:;])/g, \"$1<em>$2</em>\");\n\n const blocks = normalized.split(/\\n{2,}/);\n const html = blocks\n .map((block) => {\n const trimmed = block.trim();\n\n // Fenced code block\n if (trimmed.startsWith(\"```\") && trimmed.endsWith(\"```\")) {\n const code = trimmed\n .replace(/^```[^\\n]*\\n?/, \"\")\n .replace(/\\n?```$/, \"\");\n return `<pre><code>${esc(code)}</code></pre>`;\n }\n\n // Heading\n const hm = trimmed.match(/^(#{1,6})\\s+(.+)$/);\n if (hm) {\n const level = hm[1].length;\n return `<h${level}>${inline(hm[2])}</h${level}>`;\n }\n\n // Unordered list\n if (/^[-*+]\\s+/m.test(trimmed)) {\n const items = trimmed\n .split(\"\\n\")\n .filter(Boolean)\n .map((l) => `<li>${inline(l.replace(/^[-*+]\\s+/, \"\"))}</li>`)\n .join(\"\");\n return `<ul style=\"margin:0 0 1em;padding-left:1.5em\">${items}</ul>`;\n }\n\n // Ordered list\n if (/^\\d+\\.\\s+/m.test(trimmed)) {\n const items = trimmed\n .split(\"\\n\")\n .filter(Boolean)\n .map((l) => `<li>${inline(l.replace(/^\\d+\\.\\s+/, \"\"))}</li>`)\n .join(\"\");\n return `<ol style=\"margin:0 0 1em;padding-left:1.5em\">${items}</ol>`;\n }\n\n // Blockquote\n if (trimmed.startsWith(\"> \")) {\n const inner = trimmed\n .split(\"\\n\")\n .map((l) => (l.startsWith(\"> \") ? l.slice(2) : l))\n .join(\"\\n\");\n return `<blockquote style=\"margin:0 0 1em 1em;border-left:3px solid #ccc;padding-left:0.75em;color:#555\">${inline(inner)}</blockquote>`;\n }\n\n return `<p style=\"margin:0 0 1em\">${inline(trimmed).replace(/\\n/g, \"<br />\")}</p>`;\n })\n .join(\"\");\n\n return html;\n}\n\nexport function createCoreEmailActionEntries(): Record<string, ActionEntry> {\n return {\n \"core-send-email\": {\n tool: {\n description: [\n \"Send a transactional email via the app's configured email provider (Resend or SendGrid).\",\n \"\",\n \"IMPORTANT — DRAFT-FIRST SAFETY RULE: Never call this tool until the user has explicitly\",\n \"confirmed they want to send. Always compose the full email content first, show it to the\",\n \"user, and wait for an explicit 'yes, send it' before invoking this action.\",\n \"\",\n \"The body is written in markdown. Tables, lists, bold, italic, links, and code blocks\",\n \"are all supported and will render correctly in email clients.\",\n \"\",\n \"This sends via the framework transport (Resend/SendGrid). It is NOT the Gmail-based\",\n \"send-email action in the mail template — use this for system/notification emails from\",\n \"any template.\",\n ].join(\"\\n\"),\n parameters: {\n type: \"object\" as const,\n properties: {\n to: {\n type: \"string\",\n description: \"Recipient email address.\",\n },\n subject: {\n type: \"string\",\n description: \"Email subject line.\",\n },\n body: {\n type: \"string\",\n description:\n \"Email body in markdown. Tables, lists, headings, bold, italic, links, and code blocks are supported.\",\n },\n cc: {\n type: \"string\",\n description: \"CC email address (single address only).\",\n },\n bcc: {\n type: \"string\",\n description: \"BCC email address (single address only).\",\n },\n replyTo: {\n type: \"string\",\n description:\n \"Reply-To address. Useful when sending on behalf of someone.\",\n },\n from: {\n type: \"string\",\n description:\n 'Override the sender address. Must be a verified sender for the configured provider. Example: \"Team Name <team@example.com>\". Leave unset to use the default EMAIL_FROM env var.',\n },\n },\n required: [\"to\", \"subject\", \"body\"],\n },\n },\n run: async (input: Record<string, unknown>) => {\n const to = typeof input.to === \"string\" ? input.to.trim() : \"\";\n const subject =\n typeof input.subject === \"string\" ? input.subject.trim() : \"\";\n const bodyMd = typeof input.body === \"string\" ? input.body.trim() : \"\";\n const cc =\n typeof input.cc === \"string\" && input.cc.trim()\n ? input.cc.trim()\n : undefined;\n const bcc =\n typeof input.bcc === \"string\" && input.bcc.trim()\n ? input.bcc.trim()\n : undefined;\n const replyTo =\n typeof input.replyTo === \"string\" && input.replyTo.trim()\n ? input.replyTo.trim()\n : undefined;\n const from =\n typeof input.from === \"string\" && input.from.trim()\n ? input.from.trim()\n : undefined;\n\n if (!to) return \"Error: 'to' is required.\";\n if (!subject) return \"Error: 'subject' is required.\";\n if (!bodyMd) return \"Error: 'body' is required.\";\n\n try {\n await sendEmail({\n to,\n subject,\n html: markdownToHtml(bodyMd),\n text: markdownToText(bodyMd),\n ...(from ? { from } : {}),\n ...(cc ? { cc } : {}),\n ...(replyTo ? { replyTo } : {}),\n });\n\n const bccNote = bcc ? ` (bcc: ${bcc})` : \"\";\n return `Email sent to ${to}${bccNote}: \"${subject}\"`;\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n return `Error sending email: ${msg}`;\n }\n },\n },\n };\n}\n"]}
|
package/dist/server/email.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Email transport for system emails (password resets, invitations, notifications).
|
|
3
3
|
*
|
|
4
|
-
* Providers are selected by
|
|
4
|
+
* Providers are selected by scoped secrets:
|
|
5
5
|
* RESEND_API_KEY — https://resend.com
|
|
6
6
|
* SENDGRID_API_KEY — https://sendgrid.com
|
|
7
7
|
* EMAIL_FROM — "Name <addr@domain>" (optional; defaults to Resend's sandbox)
|
|
@@ -29,7 +29,7 @@ export interface SendEmailArgs {
|
|
|
29
29
|
references?: string;
|
|
30
30
|
attachments?: EmailAttachment[];
|
|
31
31
|
}
|
|
32
|
-
export declare function isEmailConfigured(): boolean
|
|
33
|
-
export declare function getEmailProvider(): EmailProvider
|
|
32
|
+
export declare function isEmailConfigured(): Promise<boolean>;
|
|
33
|
+
export declare function getEmailProvider(): Promise<EmailProvider>;
|
|
34
34
|
export declare function sendEmail(args: SendEmailArgs): Promise<void>;
|
|
35
35
|
//# sourceMappingURL=email.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/server/email.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;
|
|
1
|
+
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/server/email.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,UAAU,GAAG,KAAK,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAC;CACvC;AAED,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,eAAe,EAAE,CAAC;CACjC;AAiCD,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC,CAE1D;AAED,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,aAAa,CAAC,CAE/D;AAkBD,wBAAsB,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CA+GlE"}
|
package/dist/server/email.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Email transport for system emails (password resets, invitations, notifications).
|
|
3
3
|
*
|
|
4
|
-
* Providers are selected by
|
|
4
|
+
* Providers are selected by scoped secrets:
|
|
5
5
|
* RESEND_API_KEY — https://resend.com
|
|
6
6
|
* SENDGRID_API_KEY — https://sendgrid.com
|
|
7
7
|
* EMAIL_FROM — "Name <addr@domain>" (optional; defaults to Resend's sandbox)
|
|
@@ -9,30 +9,51 @@
|
|
|
9
9
|
* With neither provider configured, `sendEmail` logs the message to the console
|
|
10
10
|
* so the reset-password flow still works end-to-end for local development.
|
|
11
11
|
*/
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
import { resolveSecret } from "./credential-provider.js";
|
|
13
|
+
async function resolveEmailTransport() {
|
|
14
|
+
const [resendApiKey, sendgridApiKey, from] = await Promise.all([
|
|
15
|
+
resolveSecret("RESEND_API_KEY"),
|
|
16
|
+
resolveSecret("SENDGRID_API_KEY"),
|
|
17
|
+
resolveSecret("EMAIL_FROM"),
|
|
18
|
+
]);
|
|
19
|
+
const resolvedFrom = from ?? undefined;
|
|
20
|
+
if (resendApiKey) {
|
|
21
|
+
return {
|
|
22
|
+
provider: "resend",
|
|
23
|
+
resendApiKey,
|
|
24
|
+
from: resolvedFrom,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
if (sendgridApiKey) {
|
|
28
|
+
return {
|
|
29
|
+
provider: "sendgrid",
|
|
30
|
+
sendgridApiKey,
|
|
31
|
+
from: resolvedFrom,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
return { provider: "dev", from: resolvedFrom };
|
|
35
|
+
}
|
|
36
|
+
export async function isEmailConfigured() {
|
|
37
|
+
return (await resolveEmailTransport()).provider !== "dev";
|
|
14
38
|
}
|
|
15
|
-
export function getEmailProvider() {
|
|
16
|
-
|
|
17
|
-
return "resend";
|
|
18
|
-
if (process.env.SENDGRID_API_KEY)
|
|
19
|
-
return "sendgrid";
|
|
20
|
-
return "dev";
|
|
39
|
+
export async function getEmailProvider() {
|
|
40
|
+
return (await resolveEmailTransport()).provider;
|
|
21
41
|
}
|
|
22
|
-
function getFromAddress(
|
|
23
|
-
const explicit = override ||
|
|
42
|
+
function getFromAddress(config, override) {
|
|
43
|
+
const explicit = override || config.from;
|
|
24
44
|
if (explicit)
|
|
25
45
|
return explicit;
|
|
26
46
|
// Resend lets unverified accounts send from its sandbox domain; SendGrid
|
|
27
47
|
// does not, so falling back there would cause silent 403s at runtime.
|
|
28
|
-
if (provider === "sendgrid") {
|
|
29
|
-
throw new Error("EMAIL_FROM is required when using SendGrid —
|
|
48
|
+
if (config.provider === "sendgrid") {
|
|
49
|
+
throw new Error("EMAIL_FROM is required when using SendGrid — save it as a verified sender address.");
|
|
30
50
|
}
|
|
31
51
|
return "Agent Native <onboarding@resend.dev>";
|
|
32
52
|
}
|
|
33
53
|
export async function sendEmail(args) {
|
|
34
|
-
const
|
|
35
|
-
const
|
|
54
|
+
const config = await resolveEmailTransport();
|
|
55
|
+
const provider = config.provider;
|
|
56
|
+
const from = getFromAddress(config, args.from);
|
|
36
57
|
if (provider === "resend") {
|
|
37
58
|
const payload = {
|
|
38
59
|
from,
|
|
@@ -65,7 +86,7 @@ export async function sendEmail(args) {
|
|
|
65
86
|
const res = await fetch("https://api.resend.com/emails", {
|
|
66
87
|
method: "POST",
|
|
67
88
|
headers: {
|
|
68
|
-
Authorization: `Bearer ${
|
|
89
|
+
Authorization: `Bearer ${config.resendApiKey}`,
|
|
69
90
|
"Content-Type": "application/json",
|
|
70
91
|
},
|
|
71
92
|
body: JSON.stringify(payload),
|
|
@@ -116,7 +137,7 @@ export async function sendEmail(args) {
|
|
|
116
137
|
const res = await fetch("https://api.sendgrid.com/v3/mail/send", {
|
|
117
138
|
method: "POST",
|
|
118
139
|
headers: {
|
|
119
|
-
Authorization: `Bearer ${
|
|
140
|
+
Authorization: `Bearer ${config.sendgridApiKey}`,
|
|
120
141
|
"Content-Type": "application/json",
|
|
121
142
|
},
|
|
122
143
|
body: JSON.stringify(sgPayload),
|
|
@@ -131,10 +152,10 @@ export async function sendEmail(args) {
|
|
|
131
152
|
// reset tokens, so only do it outside production. In production, refuse
|
|
132
153
|
// to send rather than silently leaking secrets to logs.
|
|
133
154
|
if (process.env.NODE_ENV === "production") {
|
|
134
|
-
throw new Error("No email provider configured.
|
|
155
|
+
throw new Error("No email provider configured. Save RESEND_API_KEY or SENDGRID_API_KEY in settings.");
|
|
135
156
|
}
|
|
136
157
|
console.log(`\n[agent-native:email] No email provider configured. ` +
|
|
137
|
-
`
|
|
158
|
+
`Save RESEND_API_KEY or SENDGRID_API_KEY in settings to send real emails.\n` +
|
|
138
159
|
`---\nTo: ${args.to}\nFrom: ${from}\nSubject: ${args.subject}\n\n` +
|
|
139
160
|
`${args.text || stripHtml(args.html)}\n---\n`);
|
|
140
161
|
}
|
package/dist/server/email.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.js","sourceRoot":"","sources":["../../src/server/email.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAyBH,MAAM,UAAU,iBAAiB;IAC/B,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc;QAAE,OAAO,QAAQ,CAAC;IAChD,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB;QAAE,OAAO,UAAU,CAA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AO;IACT,CAAC;IAED,uEAAuE;IACvE,wEAAwE;IACxE,wDAAwD;IACxD,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,GAAG,CACT,uDAAuD;QACrD,+DAA+D;QAC/D,YAAY,IAAI,CAAC,EAAE,WAAW,IAAI,cAAc,IAAI,CAAC,OAAO,MAAM;QAClE,GAAG,IAAI,CAAC,IAAI,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAChD,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;IAC/C,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/D,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;AAChC,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,IAAI;SACR,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC;SAC1B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,IAAI,EAAE,CAAC;AACZ,CAAC","sourcesContent":["/**\n * Email transport for system emails (password resets, invitations, notifications).\n *\n * Providers are selected by env var:\n * RESEND_API_KEY — https://resend.com\n * SENDGRID_API_KEY — https://sendgrid.com\n * EMAIL_FROM — \"Name <addr@domain>\" (optional; defaults to Resend's sandbox)\n *\n * With neither provider configured, `sendEmail` logs the message to the console\n * so the reset-password flow still works end-to-end for local development.\n */\n\nexport type EmailProvider = \"resend\" | \"sendgrid\" | \"dev\";\n\nexport interface EmailAttachment {\n filename: string;\n content: string | Buffer;\n contentType?: string;\n contentId?: string;\n disposition?: \"attachment\" | \"inline\";\n}\n\nexport interface SendEmailArgs {\n to: string;\n subject: string;\n html: string;\n text?: string;\n from?: string;\n cc?: string | string[];\n replyTo?: string;\n inReplyTo?: string;\n references?: string;\n attachments?: EmailAttachment[];\n}\n\nexport function isEmailConfigured(): boolean {\n return !!(process.env.RESEND_API_KEY || process.env.SENDGRID_API_KEY);\n}\n\nexport function getEmailProvider(): EmailProvider {\n if (process.env.RESEND_API_KEY) return \"resend\";\n if (process.env.SENDGRID_API_KEY) return \"sendgrid\";\n return \"dev\";\n}\n\nfunction getFromAddress(override?: string, provider?: EmailProvider): string {\n const explicit = override || process.env.EMAIL_FROM;\n if (explicit) return explicit;\n // Resend lets unverified accounts send from its sandbox domain; SendGrid\n // does not, so falling back there would cause silent 403s at runtime.\n if (provider === \"sendgrid\") {\n throw new Error(\n \"EMAIL_FROM is required when using SendGrid — set it to a verified sender address.\",\n );\n }\n return \"Agent Native <onboarding@resend.dev>\";\n}\n\nexport async function sendEmail(args: SendEmailArgs): Promise<void> {\n const provider = getEmailProvider();\n const from = getFromAddress(args.from, provider);\n\n if (provider === \"resend\") {\n const payload: Record<string, unknown> = {\n from,\n to: args.to,\n subject: args.subject,\n html: args.html,\n text: args.text,\n };\n if (args.cc) payload.cc = Array.isArray(args.cc) ? args.cc : [args.cc];\n if (args.replyTo) payload.reply_to = args.replyTo;\n if (args.attachments?.length) {\n payload.attachments = args.attachments.map((a) => ({\n filename: a.filename,\n content:\n typeof a.content === \"string\"\n ? a.content\n : a.content.toString(\"base64\"),\n content_type: a.contentType,\n content_id: a.contentId,\n }));\n }\n const headers: Record<string, string> = {};\n if (args.inReplyTo) headers[\"In-Reply-To\"] = args.inReplyTo;\n if (args.references) headers[\"References\"] = args.references;\n if (Object.keys(headers).length) payload.headers = headers;\n\n const res = await fetch(\"https://api.resend.com/emails\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${process.env.RESEND_API_KEY}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Resend error ${res.status}: ${body}`);\n }\n return;\n }\n\n if (provider === \"sendgrid\") {\n const personalization: Record<string, unknown> = {\n to: [{ email: args.to }],\n };\n if (args.cc) {\n const ccList = Array.isArray(args.cc) ? args.cc : [args.cc];\n personalization.cc = ccList.map((email) => ({ email }));\n }\n\n const sgPayload: Record<string, unknown> = {\n personalizations: [personalization],\n from: parseSendGridFrom(from),\n subject: args.subject,\n content: [\n ...(args.text ? [{ type: \"text/plain\", value: args.text }] : []),\n { type: \"text/html\", value: args.html },\n ],\n };\n if (args.replyTo) sgPayload.reply_to = parseSendGridFrom(args.replyTo);\n const sgHeaders: Record<string, string> = {};\n if (args.inReplyTo) sgHeaders[\"In-Reply-To\"] = args.inReplyTo;\n if (args.references) sgHeaders[\"References\"] = args.references;\n if (Object.keys(sgHeaders).length) sgPayload.headers = sgHeaders;\n if (args.attachments?.length) {\n sgPayload.attachments = args.attachments.map((a) => ({\n filename: a.filename,\n content:\n typeof a.content === \"string\"\n ? Buffer.from(a.content).toString(\"base64\")\n : a.content.toString(\"base64\"),\n type: a.contentType,\n disposition: a.disposition ?? (a.contentId ? \"inline\" : undefined),\n content_id: a.contentId,\n }));\n }\n\n const res = await fetch(\"https://api.sendgrid.com/v3/mail/send\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(sgPayload),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`SendGrid error ${res.status}: ${body}`);\n }\n return;\n }\n\n // Dev fallback — no provider configured. Logging the full body exposes\n // reset tokens, so only do it outside production. In production, refuse\n // to send rather than silently leaking secrets to logs.\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(\n \"No email provider configured. Set RESEND_API_KEY or SENDGRID_API_KEY.\",\n );\n }\n console.log(\n `\\n[agent-native:email] No email provider configured. ` +\n `Set RESEND_API_KEY or SENDGRID_API_KEY to send real emails.\\n` +\n `---\\nTo: ${args.to}\\nFrom: ${from}\\nSubject: ${args.subject}\\n\\n` +\n `${args.text || stripHtml(args.html)}\\n---\\n`,\n );\n}\n\nfunction parseSendGridFrom(from: string): { email: string; name?: string } {\n const m = from.match(/^\\s*(.*?)\\s*<(.+)>\\s*$/);\n if (m && m[2]) return { name: m[1] || undefined, email: m[2] };\n return { email: from.trim() };\n}\n\nfunction stripHtml(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/ /g, \" \")\n .trim();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"email.js","sourceRoot":"","sources":["../../src/server/email.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAgCzD,KAAK,UAAU,qBAAqB;IAClC,MAAM,CAAC,YAAY,EAAE,cAAc,EAAE,IAAI,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAC7D,aAAa,CAAC,gBAAgB,CAAC;QAC/B,aAAa,CAAC,kBAAkB,CAAC;QACjC,aAAa,CAAC,YAAY,CAAC;KAC5B,CAAC,CAAC;IACH,MAAM,YAAY,GAAG,IAAI,IAAI,SAAS,CAAC;IACvC,IAAI,YAAY,EAAE,CAAC;QACjB,OAAO;YACL,QAAQ,EAAE,QAAQ;YAClB,YAAY;YACZ,IAAI,EAAE,YAAY;SACnB,CAAC;IACJ,CAAC;IACD,IAAI,cAAc,EAAE,CAAC;QACnB,OAAO;YACL,QAAQ,EAAE,UAAU;YACpB,cAAc;YACd,IAAI,EAAE,YAAY;SACnB,CA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B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,IAAI,EAAE,CAAC;AACZ,CAAC","sourcesContent":["/**\n * Email transport for system emails (password resets, invitations, notifications).\n *\n * Providers are selected by scoped secrets:\n * RESEND_API_KEY — https://resend.com\n * SENDGRID_API_KEY — https://sendgrid.com\n * EMAIL_FROM — \"Name <addr@domain>\" (optional; defaults to Resend's sandbox)\n *\n * With neither provider configured, `sendEmail` logs the message to the console\n * so the reset-password flow still works end-to-end for local development.\n */\n\nimport { resolveSecret } from \"./credential-provider.js\";\n\nexport type EmailProvider = \"resend\" | \"sendgrid\" | \"dev\";\n\nexport interface EmailAttachment {\n filename: string;\n content: string | Buffer;\n contentType?: string;\n contentId?: string;\n disposition?: \"attachment\" | \"inline\";\n}\n\nexport interface SendEmailArgs {\n to: string;\n subject: string;\n html: string;\n text?: string;\n from?: string;\n cc?: string | string[];\n replyTo?: string;\n inReplyTo?: string;\n references?: string;\n attachments?: EmailAttachment[];\n}\n\ninterface EmailTransportConfig {\n provider: EmailProvider;\n resendApiKey?: string;\n sendgridApiKey?: string;\n from?: string;\n}\n\nasync function resolveEmailTransport(): Promise<EmailTransportConfig> {\n const [resendApiKey, sendgridApiKey, from] = await Promise.all([\n resolveSecret(\"RESEND_API_KEY\"),\n resolveSecret(\"SENDGRID_API_KEY\"),\n resolveSecret(\"EMAIL_FROM\"),\n ]);\n const resolvedFrom = from ?? undefined;\n if (resendApiKey) {\n return {\n provider: \"resend\",\n resendApiKey,\n from: resolvedFrom,\n };\n }\n if (sendgridApiKey) {\n return {\n provider: \"sendgrid\",\n sendgridApiKey,\n from: resolvedFrom,\n };\n }\n return { provider: \"dev\", from: resolvedFrom };\n}\n\nexport async function isEmailConfigured(): Promise<boolean> {\n return (await resolveEmailTransport()).provider !== \"dev\";\n}\n\nexport async function getEmailProvider(): Promise<EmailProvider> {\n return (await resolveEmailTransport()).provider;\n}\n\nfunction getFromAddress(\n config: EmailTransportConfig,\n override?: string,\n): string {\n const explicit = override || config.from;\n if (explicit) return explicit;\n // Resend lets unverified accounts send from its sandbox domain; SendGrid\n // does not, so falling back there would cause silent 403s at runtime.\n if (config.provider === \"sendgrid\") {\n throw new Error(\n \"EMAIL_FROM is required when using SendGrid — save it as a verified sender address.\",\n );\n }\n return \"Agent Native <onboarding@resend.dev>\";\n}\n\nexport async function sendEmail(args: SendEmailArgs): Promise<void> {\n const config = await resolveEmailTransport();\n const provider = config.provider;\n const from = getFromAddress(config, args.from);\n\n if (provider === \"resend\") {\n const payload: Record<string, unknown> = {\n from,\n to: args.to,\n subject: args.subject,\n html: args.html,\n text: args.text,\n };\n if (args.cc) payload.cc = Array.isArray(args.cc) ? args.cc : [args.cc];\n if (args.replyTo) payload.reply_to = args.replyTo;\n if (args.attachments?.length) {\n payload.attachments = args.attachments.map((a) => ({\n filename: a.filename,\n content:\n typeof a.content === \"string\"\n ? a.content\n : a.content.toString(\"base64\"),\n content_type: a.contentType,\n content_id: a.contentId,\n }));\n }\n const headers: Record<string, string> = {};\n if (args.inReplyTo) headers[\"In-Reply-To\"] = args.inReplyTo;\n if (args.references) headers[\"References\"] = args.references;\n if (Object.keys(headers).length) payload.headers = headers;\n\n const res = await fetch(\"https://api.resend.com/emails\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${config.resendApiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Resend error ${res.status}: ${body}`);\n }\n return;\n }\n\n if (provider === \"sendgrid\") {\n const personalization: Record<string, unknown> = {\n to: [{ email: args.to }],\n };\n if (args.cc) {\n const ccList = Array.isArray(args.cc) ? args.cc : [args.cc];\n personalization.cc = ccList.map((email) => ({ email }));\n }\n\n const sgPayload: Record<string, unknown> = {\n personalizations: [personalization],\n from: parseSendGridFrom(from),\n subject: args.subject,\n content: [\n ...(args.text ? [{ type: \"text/plain\", value: args.text }] : []),\n { type: \"text/html\", value: args.html },\n ],\n };\n if (args.replyTo) sgPayload.reply_to = parseSendGridFrom(args.replyTo);\n const sgHeaders: Record<string, string> = {};\n if (args.inReplyTo) sgHeaders[\"In-Reply-To\"] = args.inReplyTo;\n if (args.references) sgHeaders[\"References\"] = args.references;\n if (Object.keys(sgHeaders).length) sgPayload.headers = sgHeaders;\n if (args.attachments?.length) {\n sgPayload.attachments = args.attachments.map((a) => ({\n filename: a.filename,\n content:\n typeof a.content === \"string\"\n ? Buffer.from(a.content).toString(\"base64\")\n : a.content.toString(\"base64\"),\n type: a.contentType,\n disposition: a.disposition ?? (a.contentId ? \"inline\" : undefined),\n content_id: a.contentId,\n }));\n }\n\n const res = await fetch(\"https://api.sendgrid.com/v3/mail/send\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${config.sendgridApiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(sgPayload),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`SendGrid error ${res.status}: ${body}`);\n }\n return;\n }\n\n // Dev fallback — no provider configured. Logging the full body exposes\n // reset tokens, so only do it outside production. In production, refuse\n // to send rather than silently leaking secrets to logs.\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(\n \"No email provider configured. Save RESEND_API_KEY or SENDGRID_API_KEY in settings.\",\n );\n }\n console.log(\n `\\n[agent-native:email] No email provider configured. ` +\n `Save RESEND_API_KEY or SENDGRID_API_KEY in settings to send real emails.\\n` +\n `---\\nTo: ${args.to}\\nFrom: ${from}\\nSubject: ${args.subject}\\n\\n` +\n `${args.text || stripHtml(args.html)}\\n---\\n`,\n );\n}\n\nfunction parseSendGridFrom(from: string): { email: string; name?: string } {\n const m = from.match(/^\\s*(.*?)\\s*<(.+)>\\s*$/);\n if (m && m[2]) return { name: m[1] || undefined, email: m[2] };\n return { email: from.trim() };\n}\n\nfunction stripHtml(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/ /g, \" \")\n .trim();\n}\n"]}
|