@agent-native/core 0.117.1 → 0.118.0

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 (815) hide show
  1. package/corpus/README.md +3 -3
  2. package/corpus/core/CHANGELOG.md +40 -0
  3. package/corpus/core/docs/content/custom-design-system.mdx +445 -0
  4. package/corpus/core/docs/content/toolkit-ui.mdx +16 -0
  5. package/corpus/core/package.json +2 -1
  6. package/corpus/core/src/a2a/types.ts +1 -0
  7. package/corpus/core/src/agent/types.ts +1 -1
  8. package/corpus/core/src/cli/context-xray-local.ts +1 -1
  9. package/corpus/core/src/client/AgentPanel.tsx +90 -107
  10. package/corpus/core/src/client/AssistantChat.tsx +30 -13
  11. package/corpus/core/src/client/CommandMenu.tsx +68 -178
  12. package/corpus/core/src/client/agent-chat-adapter.ts +3 -1
  13. package/corpus/core/src/client/app-providers.tsx +1 -1
  14. package/corpus/core/src/client/chat/message-components.tsx +116 -10
  15. package/corpus/core/src/client/chat/tool-call-display.tsx +26 -5
  16. package/corpus/core/src/client/chat/widgets/InlineExtensionWidget.tsx +14 -40
  17. package/corpus/core/src/client/components/ui/message-scroller.tsx +15 -1
  18. package/corpus/core/src/client/extensions/ExtensionViewer.tsx +4 -4
  19. package/corpus/core/src/client/extensions/ExtensionsSidebarSection.tsx +11 -11
  20. package/corpus/core/src/client/extensions/agent-native-extension-runtime.ts +1 -1
  21. package/corpus/core/src/client/extensions/delete-extension.ts +2 -2
  22. package/corpus/core/src/client/i18n.tsx +22 -0
  23. package/corpus/core/src/client/index.ts +17 -0
  24. package/corpus/core/src/client/org/OrgSwitcher.tsx +25 -1
  25. package/corpus/core/src/client/org/TeamPage.tsx +257 -153
  26. package/corpus/core/src/client/progress/RunsTray.tsx +89 -88
  27. package/corpus/core/src/client/resources/McpConnectionSuggestion.tsx +5 -2
  28. package/corpus/core/src/client/resources/McpIntegrationDialog.tsx +34 -13
  29. package/corpus/core/src/client/resources/mcp-integration-catalog.ts +13 -0
  30. package/corpus/core/src/client/settings/DemoModeSection.tsx +6 -18
  31. package/corpus/core/src/client/settings/SecretsSection.tsx +97 -52
  32. package/corpus/core/src/client/settings/SettingsPanel.tsx +302 -254
  33. package/corpus/core/src/client/settings/SettingsTabsPage.tsx +23 -2
  34. package/corpus/core/src/client/settings/VoiceTranscriptionSection.tsx +7 -18
  35. package/corpus/core/src/client/settings/index.ts +7 -0
  36. package/corpus/core/src/client/settings/useSettingsPanelController.ts +155 -0
  37. package/corpus/core/src/client/setup-connections/BuilderConnectCard.tsx +116 -51
  38. package/corpus/core/src/client/setup-connections/index.ts +10 -0
  39. package/corpus/core/src/client/setup-connections/useBuilderConnectCardController.ts +82 -0
  40. package/corpus/core/src/client/sharing/ShareButton.tsx +71 -592
  41. package/corpus/core/src/client/sharing/ShareDialog.tsx +299 -633
  42. package/corpus/core/src/client/sharing/index.ts +42 -0
  43. package/corpus/core/src/client/sharing/share-controller-helpers.ts +318 -0
  44. package/corpus/core/src/client/sharing/useShareButtonController.ts +600 -0
  45. package/corpus/core/src/client/sharing/useShareDialogController.ts +559 -0
  46. package/corpus/core/src/client/sse-event-processor.ts +23 -0
  47. package/corpus/core/src/client/tool-display.ts +71 -0
  48. package/corpus/core/src/client/use-agent-engine-configured.ts +12 -19
  49. package/corpus/core/src/client/use-chat-threads.ts +33 -12
  50. package/corpus/core/src/db/client.ts +13 -10
  51. package/corpus/core/src/extensions/actions.ts +13 -5
  52. package/corpus/core/src/extensions/local.ts +1 -0
  53. package/corpus/core/src/extensions/routes.ts +10 -5
  54. package/corpus/core/src/extensions/schema.ts +5 -0
  55. package/corpus/core/src/extensions/slots/store.ts +14 -4
  56. package/corpus/core/src/extensions/store.ts +55 -19
  57. package/corpus/core/src/extensions/theme.ts +1 -1
  58. package/corpus/core/src/file-upload/registry.ts +9 -0
  59. package/corpus/core/src/index.browser.ts +5 -0
  60. package/corpus/core/src/index.ts +1 -0
  61. package/corpus/core/src/localization/default-messages.ts +28 -6
  62. package/corpus/core/src/mcp-client/oauth-routes.ts +16 -2
  63. package/corpus/core/src/scripts/call-agent.ts +5 -1
  64. package/corpus/core/src/server/action-discovery.ts +8 -0
  65. package/corpus/core/src/server/better-auth-instance.ts +7 -2
  66. package/corpus/core/src/server/email-template.ts +18 -0
  67. package/corpus/core/src/server/email-templates.ts +3 -0
  68. package/corpus/core/src/server/email.ts +40 -4
  69. package/corpus/core/src/server/realtime-voice.ts +1 -1
  70. package/corpus/core/src/sharing/actions/share-resource.ts +1 -0
  71. package/corpus/core/src/styles/agent-native.css +0 -24
  72. package/corpus/core/src/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  73. package/corpus/core/src/templates/default/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  74. package/corpus/core/src/templates/default/.agents/skills/frontend-design/SKILL.md +22 -2
  75. package/corpus/core/src/templates/default/.agents/skills/shadcn-ui/SKILL.md +28 -4
  76. package/corpus/core/src/templates/default/app/components/ui/toolkit-provider.tsx +10 -0
  77. package/corpus/core/src/templates/default/app/design-system.ts +3 -0
  78. package/corpus/core/src/templates/default/app/global.css +1 -1
  79. package/corpus/core/src/templates/default/app/i18n/ar-SA.ts +6 -6
  80. package/corpus/core/src/templates/default/app/i18n/de-DE.ts +6 -6
  81. package/corpus/core/src/templates/default/app/i18n/en-US.ts +6 -6
  82. package/corpus/core/src/templates/default/app/i18n/es-ES.ts +6 -6
  83. package/corpus/core/src/templates/default/app/i18n/fr-FR.ts +6 -6
  84. package/corpus/core/src/templates/default/app/i18n/hi-IN.ts +6 -6
  85. package/corpus/core/src/templates/default/app/i18n/ja-JP.ts +6 -6
  86. package/corpus/core/src/templates/default/app/i18n/ko-KR.ts +6 -6
  87. package/corpus/core/src/templates/default/app/i18n/pt-BR.ts +6 -6
  88. package/corpus/core/src/templates/default/app/i18n/zh-CN.ts +7 -7
  89. package/corpus/core/src/templates/default/app/i18n/zh-TW.ts +7 -7
  90. package/corpus/core/src/templates/default/app/root.tsx +5 -2
  91. package/corpus/core/src/templates/default/package.json +1 -0
  92. package/corpus/core/src/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  93. package/corpus/core/src/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  94. package/corpus/core/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  95. package/corpus/core/src/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  96. package/corpus/core/src/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +22 -2
  97. package/corpus/core/src/templates/workspace-core/.agents/skills/shadcn-ui/SKILL.md +28 -4
  98. package/corpus/core/src/user-profile/actions/get-user-profile.ts +16 -0
  99. package/corpus/core/src/user-profile/actions/update-user-profile.ts +24 -0
  100. package/corpus/core/src/user-profile/index.ts +5 -0
  101. package/corpus/core/src/user-profile/shared.ts +14 -0
  102. package/corpus/core/src/user-profile/store.ts +50 -0
  103. package/corpus/core/src/vite/client.ts +39 -0
  104. package/corpus/templates/analytics/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  105. package/corpus/templates/analytics/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  106. package/corpus/templates/analytics/.agents/skills/frontend-design/SKILL.md +22 -2
  107. package/corpus/templates/analytics/.agents/skills/shadcn-ui/SKILL.md +28 -4
  108. package/corpus/templates/analytics/app/components/ui/toolkit-provider.tsx +6 -1
  109. package/corpus/templates/analytics/app/design-system.ts +3 -0
  110. package/corpus/templates/assets/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  111. package/corpus/templates/assets/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  112. package/corpus/templates/assets/.agents/skills/frontend-design/SKILL.md +22 -2
  113. package/corpus/templates/assets/.agents/skills/shadcn-ui/SKILL.md +28 -4
  114. package/corpus/templates/assets/app/components/layout/Sidebar.tsx +2 -2
  115. package/corpus/templates/assets/app/components/ui/alert.tsx +1 -0
  116. package/corpus/templates/assets/app/components/ui/toolkit-provider.tsx +6 -1
  117. package/corpus/templates/assets/app/design-system.ts +3 -0
  118. package/corpus/templates/assets/app/global.css +1 -1
  119. package/corpus/templates/assets/app/routes/brand-kits.$id_.presets.$presetId.tsx +26 -30
  120. package/corpus/templates/assets/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  121. package/corpus/templates/brain/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  122. package/corpus/templates/brain/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  123. package/corpus/templates/brain/.agents/skills/frontend-design/SKILL.md +22 -2
  124. package/corpus/templates/brain/.agents/skills/shadcn-ui/SKILL.md +28 -4
  125. package/corpus/templates/brain/app/components/ui/dialog.tsx +1 -0
  126. package/corpus/templates/brain/app/components/ui/toolkit-provider.tsx +6 -1
  127. package/corpus/templates/brain/app/design-system.ts +3 -0
  128. package/corpus/templates/brain/app/global.css +2 -2
  129. package/corpus/templates/brain/app/lib/brain.ts +2 -2
  130. package/corpus/templates/brain/app/root.tsx +2 -2
  131. package/corpus/templates/brain/app/routes/sources.tsx +8 -8
  132. package/corpus/templates/brain/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  133. package/corpus/templates/calendar/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  134. package/corpus/templates/calendar/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  135. package/corpus/templates/calendar/.agents/skills/frontend-design/SKILL.md +22 -2
  136. package/corpus/templates/calendar/.agents/skills/shadcn-ui/SKILL.md +28 -4
  137. package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +6 -2
  138. package/corpus/templates/calendar/app/components/ui/toolkit-provider.tsx +6 -1
  139. package/corpus/templates/calendar/app/design-system.ts +3 -0
  140. package/corpus/templates/calendar/app/global.css +1 -1
  141. package/corpus/templates/calendar/app/root.tsx +2 -2
  142. package/corpus/templates/calendar/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  143. package/corpus/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  144. package/corpus/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  145. package/corpus/templates/chat/.agents/skills/frontend-design/SKILL.md +22 -2
  146. package/corpus/templates/chat/.agents/skills/shadcn-ui/SKILL.md +28 -4
  147. package/corpus/templates/chat/app/components/layout/Sidebar.tsx +2 -2
  148. package/corpus/templates/chat/app/components/ui/toolkit-provider.tsx +6 -1
  149. package/corpus/templates/chat/app/design-system.ts +3 -0
  150. package/corpus/templates/chat/app/global.css +1 -1
  151. package/corpus/templates/chat/app/root.tsx +2 -2
  152. package/corpus/templates/chat/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  153. package/corpus/templates/clips/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  154. package/corpus/templates/clips/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  155. package/corpus/templates/clips/.agents/skills/frontend-design/SKILL.md +22 -2
  156. package/corpus/templates/clips/.agents/skills/shadcn-ui/SKILL.md +28 -4
  157. package/corpus/templates/clips/actions/export-to-brain.ts +1 -1
  158. package/corpus/templates/clips/actions/invite-member.ts +1 -0
  159. package/corpus/templates/clips/app/components/library/library-layout.tsx +2 -2
  160. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +20 -11
  161. package/corpus/templates/clips/app/components/ui/toolkit-provider.tsx +6 -1
  162. package/corpus/templates/clips/app/design-system.ts +3 -0
  163. package/corpus/templates/clips/app/global.css +1 -1
  164. package/corpus/templates/clips/app/root.tsx +7 -2
  165. package/corpus/templates/clips/app/routes/_app.library._index.tsx +1 -1
  166. package/corpus/templates/clips/app/routes/record.tsx +2 -88
  167. package/corpus/templates/clips/changelog/2026-07-22-builder-connected-recordings-start-resumable-upload-sessions.md +6 -0
  168. package/corpus/templates/clips/changelog/2026-07-22-clip-thumbnails-now-come-from-the-recording-instead-of-the-p.md +6 -0
  169. package/corpus/templates/clips/changelog/2026-07-22-clips-emails-now-render-the-agent-native-logo-in-gmail-and-o.md +6 -0
  170. package/corpus/templates/clips/changelog/2026-07-22-dismissed-zoom-and-teams-meeting-note-prompts-now-stay-dismi.md +6 -0
  171. package/corpus/templates/clips/changelog/2026-07-22-fixed-windows-recordings-aborting-during-the-countdown.md +6 -0
  172. package/corpus/templates/clips/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  173. package/corpus/templates/clips/changelog/2026-07-22-permissions-and-rewind-controls-are-now-grouped-with-clearer.md +6 -0
  174. package/corpus/templates/clips/changelog/2026-07-22-quieter-permissions-and-rewind-controls.md +6 -0
  175. package/corpus/templates/clips/changelog/2026-07-22-the-desktop-popover-opens-centered-under-the-menu-bar-icon-o.md +6 -0
  176. package/corpus/templates/clips/desktop/src/app.tsx +100 -62
  177. package/corpus/templates/clips/desktop/src/lib/meeting-notification-dismissal.ts +31 -0
  178. package/corpus/templates/clips/desktop/src/lib/recorder.ts +4 -167
  179. package/corpus/templates/clips/desktop/src/overlays/meeting-notification.tsx +10 -1
  180. package/corpus/templates/clips/desktop/src/styles.css +111 -36
  181. package/corpus/templates/clips/desktop/src-tauri/src/adhoc_meetings_watcher.rs +67 -4
  182. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +11 -2
  183. package/corpus/templates/clips/desktop/src-tauri/src/meetings_watcher.rs +51 -0
  184. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/custom_capture.rs +5 -1
  185. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +0 -189
  186. package/corpus/templates/clips/desktop/src-tauri/src/notifications.rs +62 -0
  187. package/corpus/templates/clips/desktop/src-tauri/src/shortcuts.rs +37 -2
  188. package/corpus/templates/clips/desktop/src-tauri/src/tray.rs +18 -0
  189. package/corpus/templates/clips/server/plugins/db.ts +6 -2
  190. package/corpus/templates/content/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  191. package/corpus/templates/content/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  192. package/corpus/templates/content/.agents/skills/frontend-design/SKILL.md +22 -2
  193. package/corpus/templates/content/.agents/skills/shadcn-ui/SKILL.md +28 -4
  194. package/corpus/templates/content/app/components/editor/DocumentToolbar.tsx +41 -59
  195. package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +41 -41
  196. package/corpus/templates/content/app/components/editor/database/GalleryView.tsx +2 -1
  197. package/corpus/templates/content/app/components/editor/database/ListView.tsx +2 -1
  198. package/corpus/templates/content/app/components/editor/database/TimelineView.tsx +9 -9
  199. package/corpus/templates/content/app/components/editor/database/sidebar.tsx +7 -7
  200. package/corpus/templates/content/app/components/editor/database-sources/BuilderSourceReviewDialog.tsx +11 -11
  201. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +3 -3
  202. package/corpus/templates/content/app/components/ui/checkbox.tsx +1 -0
  203. package/corpus/templates/content/app/components/ui/collapsible.tsx +1 -0
  204. package/corpus/templates/content/app/components/ui/toolkit-provider.tsx +6 -1
  205. package/corpus/templates/content/app/design-system.ts +3 -0
  206. package/corpus/templates/content/app/global.css +30 -4
  207. package/corpus/templates/content/app/root.tsx +2 -2
  208. package/corpus/templates/content/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  209. package/corpus/templates/content/changelog/2026-07-22-page-actions-are-grouped-into-the-three-dots-menu-for-a-clea.md +6 -0
  210. package/corpus/templates/crm/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  211. package/corpus/templates/crm/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  212. package/corpus/templates/crm/app/components/crm/CreateCrmRecordDialog.tsx +10 -10
  213. package/corpus/templates/crm/app/components/crm/CrmDashboardPanel.tsx +1 -6
  214. package/corpus/templates/crm/app/components/crm/CrmSignalsPanel.tsx +3 -2
  215. package/corpus/templates/crm/app/components/crm/IntelligenceSettings.tsx +13 -12
  216. package/corpus/templates/crm/app/components/crm/RecordActions.tsx +17 -17
  217. package/corpus/templates/crm/app/components/crm/RecordGrid.tsx +8 -8
  218. package/corpus/templates/crm/app/components/crm/RecordWorkspace.tsx +3 -8
  219. package/corpus/templates/crm/app/components/crm/SavedViewDataProgram.tsx +2 -1
  220. package/corpus/templates/crm/app/components/crm/Surface.tsx +3 -2
  221. package/corpus/templates/crm/app/components/crm/WorkOverview.tsx +2 -2
  222. package/corpus/templates/crm/app/components/layout/CrmLayout.tsx +7 -7
  223. package/corpus/templates/crm/app/components/layout/CrmSidebar.tsx +1 -1
  224. package/corpus/templates/crm/app/components/ui/alert-dialog.tsx +1 -0
  225. package/corpus/templates/crm/app/components/ui/badge.tsx +1 -0
  226. package/corpus/templates/crm/app/components/ui/button.tsx +1 -0
  227. package/corpus/templates/crm/app/components/ui/card.tsx +1 -0
  228. package/corpus/templates/crm/app/components/ui/dialog.tsx +1 -0
  229. package/corpus/templates/crm/app/components/ui/input.tsx +1 -0
  230. package/corpus/templates/crm/app/components/ui/label.tsx +1 -0
  231. package/corpus/templates/crm/app/components/ui/select.tsx +1 -0
  232. package/corpus/templates/crm/app/components/ui/sheet.tsx +1 -0
  233. package/corpus/templates/crm/app/components/ui/skeleton.tsx +1 -0
  234. package/corpus/templates/crm/app/components/ui/switch.tsx +1 -0
  235. package/corpus/templates/crm/app/components/ui/table.tsx +1 -0
  236. package/corpus/templates/crm/app/components/ui/tabs.tsx +1 -0
  237. package/corpus/templates/crm/app/components/ui/textarea.tsx +1 -0
  238. package/corpus/templates/crm/app/components/ui/toolkit-provider.tsx +17 -0
  239. package/corpus/templates/crm/app/design-system.ts +3 -0
  240. package/corpus/templates/crm/app/global.css +1 -1
  241. package/corpus/templates/crm/app/root.tsx +9 -6
  242. package/corpus/templates/crm/app/routes/dashboard.tsx +1 -1
  243. package/corpus/templates/crm/app/routes/proposals.tsx +13 -13
  244. package/corpus/templates/crm/app/routes/setup.tsx +9 -9
  245. package/corpus/templates/crm/app/routes/tasks.tsx +14 -14
  246. package/corpus/templates/crm/app/routes/views.tsx +16 -16
  247. package/corpus/templates/design/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  248. package/corpus/templates/design/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  249. package/corpus/templates/design/.agents/skills/frontend-design/SKILL.md +22 -2
  250. package/corpus/templates/design/.agents/skills/shadcn-ui/SKILL.md +28 -4
  251. package/corpus/templates/design/app/components/design/CanvasContextMenu.tsx +19 -1
  252. package/corpus/templates/design/app/components/design/DesignCanvas.tsx +12 -1
  253. package/corpus/templates/design/app/components/design/EditPanel.tsx +177 -52
  254. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +179 -59
  255. package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +74 -27
  256. package/corpus/templates/design/app/components/design/multi-screen/types.ts +2 -0
  257. package/corpus/templates/design/app/components/editor/PromptDialog.tsx +8 -8
  258. package/corpus/templates/design/app/components/layout/Sidebar.tsx +2 -2
  259. package/corpus/templates/design/app/components/ui/command.tsx +1 -0
  260. package/corpus/templates/design/app/components/ui/toolkit-provider.tsx +6 -1
  261. package/corpus/templates/design/app/design-system.ts +3 -0
  262. package/corpus/templates/design/app/global.css +1 -1
  263. package/corpus/templates/design/app/hooks/use-navigation-state.ts +6 -5
  264. package/corpus/templates/design/app/root.tsx +2 -2
  265. package/corpus/templates/design/changelog/2026-07-22-design-owners-can-keep-editing-their-designs-after-switching.md +6 -0
  266. package/corpus/templates/design/changelog/2026-07-22-inspector-tabs-keep-their-text-labels-at-narrow-widths.md +6 -0
  267. package/corpus/templates/design/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  268. package/corpus/templates/design/changelog/2026-07-22-narrow-breakpoint-previews-keep-their-device-labels-readable.md +6 -0
  269. package/corpus/templates/design/changelog/2026-07-22-removed-the-draft-status-chip-from-the-design-editor.md +6 -0
  270. package/corpus/templates/design/changelog/2026-07-22-responsive-breakpoint-controls-stay-within-narrow-sidebars.md +6 -0
  271. package/corpus/templates/design/changelog/2026-07-22-responsive-peers-now-use-a-softer-selection-highlight-withou.md +6 -0
  272. package/corpus/templates/design/changelog/2026-07-22-rotate-from-context-menu.md +6 -0
  273. package/corpus/templates/design/changelog/2026-07-22-the-selection-outline-now-stays-attached-while-moving-screen.md +6 -0
  274. package/corpus/templates/design/changelog/2026-07-22-view-only-designs-now-support-figma-style-layer-inspection-w.md +6 -0
  275. package/corpus/templates/design/server/db/index.ts +4 -0
  276. package/corpus/templates/dispatch/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  277. package/corpus/templates/dispatch/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  278. package/corpus/templates/dispatch/.agents/skills/frontend-design/SKILL.md +22 -2
  279. package/corpus/templates/dispatch/.agents/skills/shadcn-ui/SKILL.md +28 -4
  280. package/corpus/templates/dispatch/app/components/ui/button.tsx +1 -0
  281. package/corpus/templates/dispatch/app/components/ui/toolkit-provider.tsx +17 -0
  282. package/corpus/templates/dispatch/app/design-system.ts +3 -0
  283. package/corpus/templates/dispatch/app/dispatch-extensions.tsx +2 -2
  284. package/corpus/templates/dispatch/app/global.css +1 -1
  285. package/corpus/templates/dispatch/app/root.tsx +12 -9
  286. package/corpus/templates/dispatch/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  287. package/corpus/templates/dispatch/package.json +1 -0
  288. package/corpus/templates/forms/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  289. package/corpus/templates/forms/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  290. package/corpus/templates/forms/.agents/skills/frontend-design/SKILL.md +22 -2
  291. package/corpus/templates/forms/.agents/skills/shadcn-ui/SKILL.md +28 -4
  292. package/corpus/templates/forms/app/components/layout/Layout.tsx +1 -1
  293. package/corpus/templates/forms/app/components/layout/Sidebar.tsx +3 -3
  294. package/corpus/templates/forms/app/components/ui/toolkit-provider.tsx +6 -1
  295. package/corpus/templates/forms/app/design-system.ts +3 -0
  296. package/corpus/templates/forms/app/global.css +1 -1
  297. package/corpus/templates/forms/app/hooks/use-forms.ts +55 -2
  298. package/corpus/templates/forms/app/i18n/en-US.ts +2 -0
  299. package/corpus/templates/forms/app/pages/FormBuilderPage.tsx +3 -3
  300. package/corpus/templates/forms/app/pages/FormsListPage.tsx +23 -6
  301. package/corpus/templates/forms/app/root.tsx +2 -2
  302. package/corpus/templates/forms/changelog/2026-07-22-forms-now-archive-with-optimistic-feedback.md +6 -0
  303. package/corpus/templates/forms/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  304. package/corpus/templates/forms/server/plugins/agent-chat.ts +1 -1
  305. package/corpus/templates/macros/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  306. package/corpus/templates/macros/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  307. package/corpus/templates/macros/.agents/skills/frontend-design/SKILL.md +22 -2
  308. package/corpus/templates/macros/.agents/skills/shadcn-ui/SKILL.md +28 -4
  309. package/corpus/templates/macros/app/components/layout/AppLayout.tsx +2 -2
  310. package/corpus/templates/macros/app/components/ui/toolkit-provider.tsx +6 -1
  311. package/corpus/templates/macros/app/design-system.ts +3 -0
  312. package/corpus/templates/macros/app/root.tsx +2 -2
  313. package/corpus/templates/macros/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  314. package/corpus/templates/mail/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  315. package/corpus/templates/mail/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  316. package/corpus/templates/mail/.agents/skills/frontend-design/SKILL.md +22 -2
  317. package/corpus/templates/mail/.agents/skills/shadcn-ui/SKILL.md +28 -4
  318. package/corpus/templates/mail/app/components/email/EmailThread.tsx +134 -93
  319. package/corpus/templates/mail/app/components/email/email-iframe-document.ts +8 -2
  320. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +3 -3
  321. package/corpus/templates/mail/app/components/layout/CommandPalette.tsx +2 -2
  322. package/corpus/templates/mail/app/components/ui/textarea.tsx +1 -21
  323. package/corpus/templates/mail/app/components/ui/toolkit-provider.tsx +6 -1
  324. package/corpus/templates/mail/app/design-system.ts +3 -0
  325. package/corpus/templates/mail/app/global.css +1 -1
  326. package/corpus/templates/mail/changelog/2026-07-22-email-messages-no-longer-flash-with-an-unstyled-page-while-l.md +6 -0
  327. package/corpus/templates/mail/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  328. package/corpus/templates/plan/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  329. package/corpus/templates/plan/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  330. package/corpus/templates/plan/.agents/skills/frontend-design/SKILL.md +22 -2
  331. package/corpus/templates/plan/.agents/skills/shadcn-ui/SKILL.md +28 -4
  332. package/corpus/templates/plan/app/components/layout/Sidebar.tsx +2 -2
  333. package/corpus/templates/plan/app/components/plan/PlanContentRenderer.tsx +1 -1
  334. package/corpus/templates/plan/app/components/ui/toolkit-provider.tsx +6 -1
  335. package/corpus/templates/plan/app/design-system.ts +3 -0
  336. package/corpus/templates/plan/app/global.css +1 -1
  337. package/corpus/templates/plan/app/root.tsx +2 -2
  338. package/corpus/templates/plan/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  339. package/corpus/templates/slides/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  340. package/corpus/templates/slides/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  341. package/corpus/templates/slides/.agents/skills/frontend-design/SKILL.md +22 -2
  342. package/corpus/templates/slides/.agents/skills/shadcn-ui/SKILL.md +28 -4
  343. package/corpus/templates/slides/app/components/layout/Sidebar.tsx +2 -2
  344. package/corpus/templates/slides/app/components/ui/toolkit-provider.tsx +6 -1
  345. package/corpus/templates/slides/app/design-system.ts +3 -0
  346. package/corpus/templates/slides/app/root.tsx +2 -2
  347. package/corpus/templates/slides/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  348. package/corpus/templates/slides/changelog/2026-07-22-slides-no-longer-fail-intermittently-on-fresh-server-instances.md +6 -0
  349. package/corpus/templates/slides/changelog/2026-07-22-uploaded-screenshots-can-now-be-analyzed-and-recreated-as-ed.md +6 -0
  350. package/corpus/templates/slides/server/lib/chat-attachments.ts +7 -3
  351. package/corpus/templates/slides/server/plugins/db.ts +44 -17
  352. package/corpus/templates/tasks/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  353. package/corpus/templates/tasks/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  354. package/corpus/templates/tasks/.agents/skills/frontend-design/SKILL.md +22 -2
  355. package/corpus/templates/tasks/.agents/skills/shadcn-ui/SKILL.md +28 -4
  356. package/corpus/templates/tasks/app/components/ui/toolkit-provider.tsx +17 -0
  357. package/corpus/templates/tasks/app/design-system.ts +3 -0
  358. package/corpus/templates/tasks/app/global.css +1 -1
  359. package/corpus/templates/tasks/app/root.tsx +5 -2
  360. package/corpus/toolkit/CHANGELOG.md +14 -0
  361. package/corpus/toolkit/agent-native.eject.json +71 -0
  362. package/corpus/toolkit/package.json +31 -1
  363. package/corpus/toolkit/src/chat-history/ChatHistoryRail.tsx +100 -39
  364. package/corpus/toolkit/src/chat-history/index.ts +9 -0
  365. package/corpus/toolkit/src/chat-history/useChatHistoryRailController.ts +76 -0
  366. package/corpus/toolkit/src/chat-history.css +2 -0
  367. package/corpus/toolkit/src/composer/ComposerPlusMenu.tsx +11 -8
  368. package/corpus/toolkit/src/composer/PromptComposer.tsx +27 -6
  369. package/corpus/toolkit/src/composer/useRealtimeVoiceMode.tsx +107 -22
  370. package/corpus/toolkit/src/conformance/__fixtures__/css-in-js-adapter.tsx +401 -0
  371. package/corpus/toolkit/src/conformance/index.ts +3 -0
  372. package/corpus/toolkit/src/conformance/runner.tsx +710 -0
  373. package/corpus/toolkit/src/conformance/types.ts +45 -0
  374. package/corpus/toolkit/src/conformance/version.ts +22 -0
  375. package/corpus/toolkit/src/design-system/components.tsx +146 -0
  376. package/corpus/toolkit/src/design-system/context.tsx +31 -0
  377. package/corpus/toolkit/src/design-system/default-adapter.tsx +915 -0
  378. package/corpus/toolkit/src/design-system/definition.ts +14 -0
  379. package/corpus/toolkit/src/design-system/error-boundary.tsx +37 -0
  380. package/corpus/toolkit/src/design-system/index.ts +7 -0
  381. package/corpus/toolkit/src/design-system/theme.ts +145 -0
  382. package/corpus/toolkit/src/design-system/types.ts +363 -0
  383. package/corpus/toolkit/src/provider.tsx +98 -5
  384. package/corpus/toolkit/src/ui/button.tsx +95 -6
  385. package/corpus/toolkit/src/ui/dialog.tsx +48 -23
  386. package/corpus/toolkit/src/ui/popover.tsx +16 -2
  387. package/corpus/toolkit/src/ui/select.tsx +7 -3
  388. package/corpus/toolkit/src/ui/sidebar.tsx +47 -48
  389. package/corpus/toolkit/src/ui/tooltip.tsx +7 -3
  390. package/dist/a2a/types.d.ts +1 -1
  391. package/dist/a2a/types.d.ts.map +1 -1
  392. package/dist/a2a/types.js.map +1 -1
  393. package/dist/agent/types.d.ts +1 -1
  394. package/dist/agent/types.d.ts.map +1 -1
  395. package/dist/agent/types.js.map +1 -1
  396. package/dist/cli/context-xray-local.js +1 -1
  397. package/dist/cli/context-xray-local.js.map +1 -1
  398. package/dist/client/AgentPanel.d.ts.map +1 -1
  399. package/dist/client/AgentPanel.js +14 -14
  400. package/dist/client/AgentPanel.js.map +1 -1
  401. package/dist/client/AssistantChat.d.ts.map +1 -1
  402. package/dist/client/AssistantChat.js +26 -15
  403. package/dist/client/AssistantChat.js.map +1 -1
  404. package/dist/client/CommandMenu.d.ts.map +1 -1
  405. package/dist/client/CommandMenu.js +18 -106
  406. package/dist/client/CommandMenu.js.map +1 -1
  407. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  408. package/dist/client/agent-chat-adapter.js +2 -1
  409. package/dist/client/agent-chat-adapter.js.map +1 -1
  410. package/dist/client/app-providers.d.ts.map +1 -1
  411. package/dist/client/app-providers.js +1 -1
  412. package/dist/client/app-providers.js.map +1 -1
  413. package/dist/client/chat/message-components.d.ts +9 -1
  414. package/dist/client/chat/message-components.d.ts.map +1 -1
  415. package/dist/client/chat/message-components.js +62 -7
  416. package/dist/client/chat/message-components.js.map +1 -1
  417. package/dist/client/chat/tool-call-display.d.ts.map +1 -1
  418. package/dist/client/chat/tool-call-display.js +20 -5
  419. package/dist/client/chat/tool-call-display.js.map +1 -1
  420. package/dist/client/chat/widgets/InlineExtensionWidget.d.ts.map +1 -1
  421. package/dist/client/chat/widgets/InlineExtensionWidget.js +9 -12
  422. package/dist/client/chat/widgets/InlineExtensionWidget.js.map +1 -1
  423. package/dist/client/components/ui/message-scroller.d.ts +1 -1
  424. package/dist/client/components/ui/message-scroller.d.ts.map +1 -1
  425. package/dist/client/components/ui/message-scroller.js +4 -3
  426. package/dist/client/components/ui/message-scroller.js.map +1 -1
  427. package/dist/client/extensions/ExtensionViewer.js +2 -2
  428. package/dist/client/extensions/ExtensionViewer.js.map +1 -1
  429. package/dist/client/extensions/ExtensionsSidebarSection.js +11 -11
  430. package/dist/client/extensions/ExtensionsSidebarSection.js.map +1 -1
  431. package/dist/client/extensions/agent-native-extension-runtime.js +1 -1
  432. package/dist/client/extensions/agent-native-extension-runtime.js.map +1 -1
  433. package/dist/client/extensions/delete-extension.d.ts +1 -1
  434. package/dist/client/extensions/delete-extension.d.ts.map +1 -1
  435. package/dist/client/extensions/delete-extension.js +1 -1
  436. package/dist/client/extensions/delete-extension.js.map +1 -1
  437. package/dist/client/i18n.d.ts.map +1 -1
  438. package/dist/client/i18n.js +9 -0
  439. package/dist/client/i18n.js.map +1 -1
  440. package/dist/client/index.d.ts +2 -2
  441. package/dist/client/index.d.ts.map +1 -1
  442. package/dist/client/index.js +2 -2
  443. package/dist/client/index.js.map +1 -1
  444. package/dist/client/org/OrgSwitcher.d.ts +3 -1
  445. package/dist/client/org/OrgSwitcher.d.ts.map +1 -1
  446. package/dist/client/org/OrgSwitcher.js +12 -4
  447. package/dist/client/org/OrgSwitcher.js.map +1 -1
  448. package/dist/client/org/TeamPage.d.ts.map +1 -1
  449. package/dist/client/org/TeamPage.js +41 -33
  450. package/dist/client/org/TeamPage.js.map +1 -1
  451. package/dist/client/progress/RunsTray.d.ts.map +1 -1
  452. package/dist/client/progress/RunsTray.js +9 -10
  453. package/dist/client/progress/RunsTray.js.map +1 -1
  454. package/dist/client/resources/McpConnectionSuggestion.d.ts.map +1 -1
  455. package/dist/client/resources/McpConnectionSuggestion.js +5 -4
  456. package/dist/client/resources/McpConnectionSuggestion.js.map +1 -1
  457. package/dist/client/resources/McpIntegrationDialog.d.ts.map +1 -1
  458. package/dist/client/resources/McpIntegrationDialog.js +10 -8
  459. package/dist/client/resources/McpIntegrationDialog.js.map +1 -1
  460. package/dist/client/resources/mcp-integration-catalog.d.ts +1 -0
  461. package/dist/client/resources/mcp-integration-catalog.d.ts.map +1 -1
  462. package/dist/client/resources/mcp-integration-catalog.js +13 -0
  463. package/dist/client/resources/mcp-integration-catalog.js.map +1 -1
  464. package/dist/client/settings/DemoModeSection.d.ts.map +1 -1
  465. package/dist/client/settings/DemoModeSection.js +2 -5
  466. package/dist/client/settings/DemoModeSection.js.map +1 -1
  467. package/dist/client/settings/SecretsSection.d.ts.map +1 -1
  468. package/dist/client/settings/SecretsSection.js +18 -6
  469. package/dist/client/settings/SecretsSection.js.map +1 -1
  470. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  471. package/dist/client/settings/SettingsPanel.js +87 -119
  472. package/dist/client/settings/SettingsPanel.js.map +1 -1
  473. package/dist/client/settings/SettingsTabsPage.d.ts.map +1 -1
  474. package/dist/client/settings/SettingsTabsPage.js +16 -1
  475. package/dist/client/settings/SettingsTabsPage.js.map +1 -1
  476. package/dist/client/settings/VoiceTranscriptionSection.d.ts.map +1 -1
  477. package/dist/client/settings/VoiceTranscriptionSection.js +2 -5
  478. package/dist/client/settings/VoiceTranscriptionSection.js.map +1 -1
  479. package/dist/client/settings/index.d.ts +1 -0
  480. package/dist/client/settings/index.d.ts.map +1 -1
  481. package/dist/client/settings/index.js +1 -0
  482. package/dist/client/settings/index.js.map +1 -1
  483. package/dist/client/settings/useSettingsPanelController.d.ts +22 -0
  484. package/dist/client/settings/useSettingsPanelController.d.ts.map +1 -0
  485. package/dist/client/settings/useSettingsPanelController.js +103 -0
  486. package/dist/client/settings/useSettingsPanelController.js.map +1 -0
  487. package/dist/client/setup-connections/BuilderConnectCard.d.ts +14 -6
  488. package/dist/client/setup-connections/BuilderConnectCard.d.ts.map +1 -1
  489. package/dist/client/setup-connections/BuilderConnectCard.js +24 -16
  490. package/dist/client/setup-connections/BuilderConnectCard.js.map +1 -1
  491. package/dist/client/setup-connections/index.d.ts +2 -1
  492. package/dist/client/setup-connections/index.d.ts.map +1 -1
  493. package/dist/client/setup-connections/index.js +2 -1
  494. package/dist/client/setup-connections/index.js.map +1 -1
  495. package/dist/client/setup-connections/useBuilderConnectCardController.d.ts +34 -0
  496. package/dist/client/setup-connections/useBuilderConnectCardController.d.ts.map +1 -0
  497. package/dist/client/setup-connections/useBuilderConnectCardController.js +39 -0
  498. package/dist/client/setup-connections/useBuilderConnectCardController.js.map +1 -0
  499. package/dist/client/sharing/ShareButton.d.ts +5 -5
  500. package/dist/client/sharing/ShareButton.d.ts.map +1 -1
  501. package/dist/client/sharing/ShareButton.js +19 -464
  502. package/dist/client/sharing/ShareButton.js.map +1 -1
  503. package/dist/client/sharing/ShareDialog.d.ts +6 -6
  504. package/dist/client/sharing/ShareDialog.d.ts.map +1 -1
  505. package/dist/client/sharing/ShareDialog.js +69 -283
  506. package/dist/client/sharing/ShareDialog.js.map +1 -1
  507. package/dist/client/sharing/index.d.ts +3 -0
  508. package/dist/client/sharing/index.d.ts.map +1 -1
  509. package/dist/client/sharing/index.js +3 -0
  510. package/dist/client/sharing/index.js.map +1 -1
  511. package/dist/client/sharing/share-controller-helpers.d.ts +70 -0
  512. package/dist/client/sharing/share-controller-helpers.d.ts.map +1 -0
  513. package/dist/client/sharing/share-controller-helpers.js +224 -0
  514. package/dist/client/sharing/share-controller-helpers.js.map +1 -0
  515. package/dist/client/sharing/useShareButtonController.d.ts +91 -0
  516. package/dist/client/sharing/useShareButtonController.d.ts.map +1 -0
  517. package/dist/client/sharing/useShareButtonController.js +397 -0
  518. package/dist/client/sharing/useShareButtonController.js.map +1 -0
  519. package/dist/client/sharing/useShareDialogController.d.ts +109 -0
  520. package/dist/client/sharing/useShareDialogController.d.ts.map +1 -0
  521. package/dist/client/sharing/useShareDialogController.js +348 -0
  522. package/dist/client/sharing/useShareDialogController.js.map +1 -0
  523. package/dist/client/sse-event-processor.d.ts.map +1 -1
  524. package/dist/client/sse-event-processor.js +21 -0
  525. package/dist/client/sse-event-processor.js.map +1 -1
  526. package/dist/client/tool-display.d.ts +16 -0
  527. package/dist/client/tool-display.d.ts.map +1 -1
  528. package/dist/client/tool-display.js +52 -0
  529. package/dist/client/tool-display.js.map +1 -1
  530. package/dist/client/use-agent-engine-configured.d.ts +3 -2
  531. package/dist/client/use-agent-engine-configured.d.ts.map +1 -1
  532. package/dist/client/use-agent-engine-configured.js +7 -19
  533. package/dist/client/use-agent-engine-configured.js.map +1 -1
  534. package/dist/client/use-chat-threads.d.ts.map +1 -1
  535. package/dist/client/use-chat-threads.js +21 -8
  536. package/dist/client/use-chat-threads.js.map +1 -1
  537. package/dist/collab/awareness.d.ts +2 -2
  538. package/dist/collab/awareness.d.ts.map +1 -1
  539. package/dist/db/client.d.ts +7 -7
  540. package/dist/db/client.d.ts.map +1 -1
  541. package/dist/db/client.js +13 -10
  542. package/dist/db/client.js.map +1 -1
  543. package/dist/extensions/actions.d.ts.map +1 -1
  544. package/dist/extensions/actions.js +8 -5
  545. package/dist/extensions/actions.js.map +1 -1
  546. package/dist/extensions/local.d.ts.map +1 -1
  547. package/dist/extensions/local.js +1 -0
  548. package/dist/extensions/local.js.map +1 -1
  549. package/dist/extensions/routes.d.ts.map +1 -1
  550. package/dist/extensions/routes.js +9 -4
  551. package/dist/extensions/routes.js.map +1 -1
  552. package/dist/extensions/schema.d.ts +23 -2
  553. package/dist/extensions/schema.d.ts.map +1 -1
  554. package/dist/extensions/schema.js +5 -0
  555. package/dist/extensions/schema.js.map +1 -1
  556. package/dist/extensions/slots/store.d.ts +1 -1
  557. package/dist/extensions/slots/store.d.ts.map +1 -1
  558. package/dist/extensions/slots/store.js +4 -4
  559. package/dist/extensions/slots/store.js.map +1 -1
  560. package/dist/extensions/store.d.ts +1 -0
  561. package/dist/extensions/store.d.ts.map +1 -1
  562. package/dist/extensions/store.js +38 -21
  563. package/dist/extensions/store.js.map +1 -1
  564. package/dist/extensions/theme.js +1 -1
  565. package/dist/extensions/theme.js.map +1 -1
  566. package/dist/file-upload/registry.d.ts.map +1 -1
  567. package/dist/file-upload/registry.js +9 -0
  568. package/dist/file-upload/registry.js.map +1 -1
  569. package/dist/index.browser.d.ts +1 -0
  570. package/dist/index.browser.d.ts.map +1 -1
  571. package/dist/index.browser.js +1 -0
  572. package/dist/index.browser.js.map +1 -1
  573. package/dist/index.d.ts +1 -0
  574. package/dist/index.d.ts.map +1 -1
  575. package/dist/index.js +1 -0
  576. package/dist/index.js.map +1 -1
  577. package/dist/localization/default-messages.d.ts +20 -0
  578. package/dist/localization/default-messages.d.ts.map +1 -1
  579. package/dist/localization/default-messages.js +26 -6
  580. package/dist/localization/default-messages.js.map +1 -1
  581. package/dist/mcp-client/oauth-routes.d.ts +2 -0
  582. package/dist/mcp-client/oauth-routes.d.ts.map +1 -1
  583. package/dist/mcp-client/oauth-routes.js +12 -2
  584. package/dist/mcp-client/oauth-routes.js.map +1 -1
  585. package/dist/observability/routes.d.ts +3 -3
  586. package/dist/provider-api/actions/custom-provider-registration.d.ts +3 -3
  587. package/dist/provider-api/actions/provider-api.d.ts +11 -11
  588. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  589. package/dist/scripts/call-agent.d.ts.map +1 -1
  590. package/dist/scripts/call-agent.js +5 -1
  591. package/dist/scripts/call-agent.js.map +1 -1
  592. package/dist/secrets/routes.d.ts +6 -6
  593. package/dist/server/action-discovery.d.ts.map +1 -1
  594. package/dist/server/action-discovery.js +8 -0
  595. package/dist/server/action-discovery.js.map +1 -1
  596. package/dist/server/better-auth-instance.d.ts +7 -2
  597. package/dist/server/better-auth-instance.d.ts.map +1 -1
  598. package/dist/server/better-auth-instance.js.map +1 -1
  599. package/dist/server/email-template.d.ts +3 -0
  600. package/dist/server/email-template.d.ts.map +1 -1
  601. package/dist/server/email-template.js +13 -0
  602. package/dist/server/email-template.js.map +1 -1
  603. package/dist/server/email-templates.d.ts.map +1 -1
  604. package/dist/server/email-templates.js +3 -0
  605. package/dist/server/email-templates.js.map +1 -1
  606. package/dist/server/email.d.ts.map +1 -1
  607. package/dist/server/email.js +27 -4
  608. package/dist/server/email.js.map +1 -1
  609. package/dist/server/realtime-voice.js +1 -1
  610. package/dist/server/realtime-voice.js.map +1 -1
  611. package/dist/server/transcribe-voice.d.ts +1 -1
  612. package/dist/sharing/actions/share-resource.js +1 -0
  613. package/dist/sharing/actions/share-resource.js.map +1 -1
  614. package/dist/styles/agent-native.css +0 -24
  615. package/dist/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  616. package/dist/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  617. package/dist/templates/chat/.agents/skills/frontend-design/SKILL.md +22 -2
  618. package/dist/templates/chat/.agents/skills/shadcn-ui/SKILL.md +28 -4
  619. package/dist/templates/chat/app/components/layout/Sidebar.tsx +2 -2
  620. package/dist/templates/chat/app/components/ui/toolkit-provider.tsx +6 -1
  621. package/dist/templates/chat/app/design-system.ts +3 -0
  622. package/dist/templates/chat/app/global.css +1 -1
  623. package/dist/templates/chat/app/root.tsx +2 -2
  624. package/dist/templates/chat/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  625. package/dist/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  626. package/dist/templates/default/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  627. package/dist/templates/default/.agents/skills/frontend-design/SKILL.md +22 -2
  628. package/dist/templates/default/.agents/skills/shadcn-ui/SKILL.md +28 -4
  629. package/dist/templates/default/app/components/ui/toolkit-provider.tsx +10 -0
  630. package/dist/templates/default/app/design-system.ts +3 -0
  631. package/dist/templates/default/app/global.css +1 -1
  632. package/dist/templates/default/app/i18n/ar-SA.ts +6 -6
  633. package/dist/templates/default/app/i18n/de-DE.ts +6 -6
  634. package/dist/templates/default/app/i18n/en-US.ts +6 -6
  635. package/dist/templates/default/app/i18n/es-ES.ts +6 -6
  636. package/dist/templates/default/app/i18n/fr-FR.ts +6 -6
  637. package/dist/templates/default/app/i18n/hi-IN.ts +6 -6
  638. package/dist/templates/default/app/i18n/ja-JP.ts +6 -6
  639. package/dist/templates/default/app/i18n/ko-KR.ts +6 -6
  640. package/dist/templates/default/app/i18n/pt-BR.ts +6 -6
  641. package/dist/templates/default/app/i18n/zh-CN.ts +7 -7
  642. package/dist/templates/default/app/i18n/zh-TW.ts +7 -7
  643. package/dist/templates/default/app/root.tsx +5 -2
  644. package/dist/templates/default/package.json +1 -0
  645. package/dist/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  646. package/dist/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  647. package/dist/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  648. package/dist/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  649. package/dist/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +22 -2
  650. package/dist/templates/workspace-core/.agents/skills/shadcn-ui/SKILL.md +28 -4
  651. package/dist/user-profile/actions/get-user-profile.d.ts +4 -0
  652. package/dist/user-profile/actions/get-user-profile.d.ts.map +1 -0
  653. package/dist/user-profile/actions/get-user-profile.js +14 -0
  654. package/dist/user-profile/actions/get-user-profile.js.map +1 -0
  655. package/dist/user-profile/actions/update-user-profile.d.ts +6 -0
  656. package/dist/user-profile/actions/update-user-profile.d.ts.map +1 -0
  657. package/dist/user-profile/actions/update-user-profile.js +20 -0
  658. package/dist/user-profile/actions/update-user-profile.js.map +1 -0
  659. package/dist/user-profile/index.d.ts +2 -0
  660. package/dist/user-profile/index.d.ts.map +1 -0
  661. package/dist/user-profile/index.js +2 -0
  662. package/dist/user-profile/index.js.map +1 -0
  663. package/dist/user-profile/shared.d.ts +7 -0
  664. package/dist/user-profile/shared.d.ts.map +1 -0
  665. package/dist/user-profile/shared.js +6 -0
  666. package/dist/user-profile/shared.js.map +1 -0
  667. package/dist/user-profile/store.d.ts +4 -0
  668. package/dist/user-profile/store.d.ts.map +1 -0
  669. package/dist/user-profile/store.js +38 -0
  670. package/dist/user-profile/store.js.map +1 -0
  671. package/dist/vite/client.d.ts +3 -0
  672. package/dist/vite/client.d.ts.map +1 -1
  673. package/dist/vite/client.js +31 -0
  674. package/dist/vite/client.js.map +1 -1
  675. package/docs/content/custom-design-system.mdx +445 -0
  676. package/docs/content/toolkit-ui.mdx +16 -0
  677. package/package.json +3 -2
  678. package/src/a2a/types.ts +1 -0
  679. package/src/agent/types.ts +1 -1
  680. package/src/cli/context-xray-local.ts +1 -1
  681. package/src/client/AgentPanel.tsx +90 -107
  682. package/src/client/AssistantChat.tsx +30 -13
  683. package/src/client/CommandMenu.tsx +68 -178
  684. package/src/client/agent-chat-adapter.ts +3 -1
  685. package/src/client/app-providers.tsx +1 -1
  686. package/src/client/chat/message-components.tsx +116 -10
  687. package/src/client/chat/tool-call-display.tsx +26 -5
  688. package/src/client/chat/widgets/InlineExtensionWidget.tsx +14 -40
  689. package/src/client/components/ui/message-scroller.tsx +15 -1
  690. package/src/client/extensions/ExtensionViewer.tsx +4 -4
  691. package/src/client/extensions/ExtensionsSidebarSection.tsx +11 -11
  692. package/src/client/extensions/agent-native-extension-runtime.ts +1 -1
  693. package/src/client/extensions/delete-extension.ts +2 -2
  694. package/src/client/i18n.tsx +22 -0
  695. package/src/client/index.ts +17 -0
  696. package/src/client/org/OrgSwitcher.tsx +25 -1
  697. package/src/client/org/TeamPage.tsx +257 -153
  698. package/src/client/progress/RunsTray.tsx +89 -88
  699. package/src/client/resources/McpConnectionSuggestion.tsx +5 -2
  700. package/src/client/resources/McpIntegrationDialog.tsx +34 -13
  701. package/src/client/resources/mcp-integration-catalog.ts +13 -0
  702. package/src/client/settings/DemoModeSection.tsx +6 -18
  703. package/src/client/settings/SecretsSection.tsx +97 -52
  704. package/src/client/settings/SettingsPanel.tsx +302 -254
  705. package/src/client/settings/SettingsTabsPage.tsx +23 -2
  706. package/src/client/settings/VoiceTranscriptionSection.tsx +7 -18
  707. package/src/client/settings/index.ts +7 -0
  708. package/src/client/settings/useSettingsPanelController.ts +155 -0
  709. package/src/client/setup-connections/BuilderConnectCard.tsx +116 -51
  710. package/src/client/setup-connections/index.ts +10 -0
  711. package/src/client/setup-connections/useBuilderConnectCardController.ts +82 -0
  712. package/src/client/sharing/ShareButton.tsx +71 -592
  713. package/src/client/sharing/ShareDialog.tsx +299 -633
  714. package/src/client/sharing/index.ts +42 -0
  715. package/src/client/sharing/share-controller-helpers.ts +318 -0
  716. package/src/client/sharing/useShareButtonController.ts +600 -0
  717. package/src/client/sharing/useShareDialogController.ts +559 -0
  718. package/src/client/sse-event-processor.ts +23 -0
  719. package/src/client/tool-display.ts +71 -0
  720. package/src/client/use-agent-engine-configured.ts +12 -19
  721. package/src/client/use-chat-threads.ts +33 -12
  722. package/src/db/client.ts +13 -10
  723. package/src/extensions/actions.ts +13 -5
  724. package/src/extensions/local.ts +1 -0
  725. package/src/extensions/routes.ts +10 -5
  726. package/src/extensions/schema.ts +5 -0
  727. package/src/extensions/slots/store.ts +14 -4
  728. package/src/extensions/store.ts +55 -19
  729. package/src/extensions/theme.ts +1 -1
  730. package/src/file-upload/registry.ts +9 -0
  731. package/src/index.browser.ts +5 -0
  732. package/src/index.ts +1 -0
  733. package/src/localization/default-messages.ts +28 -6
  734. package/src/mcp-client/oauth-routes.ts +16 -2
  735. package/src/scripts/call-agent.ts +5 -1
  736. package/src/server/action-discovery.ts +8 -0
  737. package/src/server/better-auth-instance.ts +7 -2
  738. package/src/server/email-template.ts +18 -0
  739. package/src/server/email-templates.ts +3 -0
  740. package/src/server/email.ts +40 -4
  741. package/src/server/realtime-voice.ts +1 -1
  742. package/src/sharing/actions/share-resource.ts +1 -0
  743. package/src/styles/agent-native.css +0 -24
  744. package/src/templates/chat/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  745. package/src/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  746. package/src/templates/chat/.agents/skills/frontend-design/SKILL.md +22 -2
  747. package/src/templates/chat/.agents/skills/shadcn-ui/SKILL.md +28 -4
  748. package/src/templates/chat/app/components/layout/Sidebar.tsx +2 -2
  749. package/src/templates/chat/app/components/ui/toolkit-provider.tsx +6 -1
  750. package/src/templates/chat/app/design-system.ts +3 -0
  751. package/src/templates/chat/app/global.css +1 -1
  752. package/src/templates/chat/app/root.tsx +2 -2
  753. package/src/templates/chat/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  754. package/src/templates/default/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  755. package/src/templates/default/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  756. package/src/templates/default/.agents/skills/frontend-design/SKILL.md +22 -2
  757. package/src/templates/default/.agents/skills/shadcn-ui/SKILL.md +28 -4
  758. package/src/templates/default/app/components/ui/toolkit-provider.tsx +10 -0
  759. package/src/templates/default/app/design-system.ts +3 -0
  760. package/src/templates/default/app/global.css +1 -1
  761. package/src/templates/default/app/i18n/ar-SA.ts +6 -6
  762. package/src/templates/default/app/i18n/de-DE.ts +6 -6
  763. package/src/templates/default/app/i18n/en-US.ts +6 -6
  764. package/src/templates/default/app/i18n/es-ES.ts +6 -6
  765. package/src/templates/default/app/i18n/fr-FR.ts +6 -6
  766. package/src/templates/default/app/i18n/hi-IN.ts +6 -6
  767. package/src/templates/default/app/i18n/ja-JP.ts +6 -6
  768. package/src/templates/default/app/i18n/ko-KR.ts +6 -6
  769. package/src/templates/default/app/i18n/pt-BR.ts +6 -6
  770. package/src/templates/default/app/i18n/zh-CN.ts +7 -7
  771. package/src/templates/default/app/i18n/zh-TW.ts +7 -7
  772. package/src/templates/default/app/root.tsx +5 -2
  773. package/src/templates/default/package.json +1 -0
  774. package/src/templates/headless/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  775. package/src/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  776. package/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +43 -2
  777. package/src/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +86 -11
  778. package/src/templates/workspace-core/.agents/skills/frontend-design/SKILL.md +22 -2
  779. package/src/templates/workspace-core/.agents/skills/shadcn-ui/SKILL.md +28 -4
  780. package/src/user-profile/actions/get-user-profile.ts +16 -0
  781. package/src/user-profile/actions/update-user-profile.ts +24 -0
  782. package/src/user-profile/index.ts +5 -0
  783. package/src/user-profile/shared.ts +14 -0
  784. package/src/user-profile/store.ts +50 -0
  785. package/src/vite/client.ts +39 -0
  786. package/corpus/templates/analytics/app/components/ui/calendar.tsx +0 -70
  787. package/corpus/templates/analytics/app/components/ui/chart.tsx +0 -386
  788. package/corpus/templates/calendar/app/components/ui/sonner.tsx +0 -58
  789. package/corpus/templates/forms/app/components/ui/calendar.tsx +0 -214
  790. package/corpus/templates/forms/app/components/ui/chart.tsx +0 -379
  791. package/corpus/templates/forms/app/components/ui/command.tsx +0 -153
  792. package/corpus/templates/forms/app/components/ui/context-menu.tsx +0 -198
  793. package/corpus/templates/forms/app/components/ui/menubar.tsx +0 -254
  794. package/corpus/templates/macros/app/components/ui/menubar.tsx +0 -238
  795. package/corpus/templates/macros/app/components/ui/progress.tsx +0 -26
  796. package/corpus/templates/mail/app/components/ui/calendar.tsx +0 -211
  797. package/corpus/templates/mail/app/components/ui/chart.tsx +0 -379
  798. package/corpus/templates/mail/app/components/ui/command.tsx +0 -153
  799. package/corpus/templates/mail/app/components/ui/context-menu.tsx +0 -198
  800. package/corpus/templates/mail/app/components/ui/menubar.tsx +0 -254
  801. package/corpus/templates/tasks/app/components/ui/accordion.tsx +0 -56
  802. package/corpus/templates/tasks/app/components/ui/aspect-ratio.tsx +0 -5
  803. package/corpus/templates/tasks/app/components/ui/breadcrumb.tsx +0 -115
  804. package/corpus/templates/tasks/app/components/ui/calendar.tsx +0 -70
  805. package/corpus/templates/tasks/app/components/ui/carousel.tsx +0 -260
  806. package/corpus/templates/tasks/app/components/ui/chart.tsx +0 -379
  807. package/corpus/templates/tasks/app/components/ui/form.tsx +0 -177
  808. package/corpus/templates/tasks/app/components/ui/hover-card.tsx +0 -27
  809. package/corpus/templates/tasks/app/components/ui/input-otp.tsx +0 -69
  810. package/corpus/templates/tasks/app/components/ui/menubar.tsx +0 -254
  811. package/corpus/templates/tasks/app/components/ui/navigation-menu.tsx +0 -128
  812. package/corpus/templates/tasks/app/components/ui/pagination.tsx +0 -121
  813. package/corpus/templates/tasks/app/components/ui/resizable.tsx +0 -43
  814. package/corpus/templates/tasks/app/components/ui/sidebar.tsx +0 -782
  815. package/corpus/templates/tasks/app/components/ui/toggle.tsx +0 -43
@@ -10,6 +10,16 @@ import { finishMcpOAuthAuthorization, startMcpOAuthAuthorization, } from "./oaut
10
10
  import { addOAuthRemoteServer, normalizeServerName, validateRemoteUrl, } from "./remote-store.js";
11
11
  const FLOW_COOKIE = "an_mcp_oauth_flow";
12
12
  const FLOW_TTL_SECONDS = 10 * 60;
13
+ export function redirectWithStagedCookies(event, location) {
14
+ const headers = new Headers({
15
+ Location: location,
16
+ "Cache-Control": "no-store",
17
+ });
18
+ for (const cookie of event.res?.headers?.getSetCookie?.() ?? []) {
19
+ headers.append("set-cookie", cookie);
20
+ }
21
+ return new Response(null, { status: 302, headers });
22
+ }
13
23
  export function mountMcpOAuthRoutes(nitroApp, options) {
14
24
  const mountedApps = (globalThis.__agentNativeMcpOAuthMountedApps ??= new WeakSet());
15
25
  if (mountedApps.has(nitroApp))
@@ -116,7 +126,7 @@ async function handleMcpOAuthStart(event) {
116
126
  path: "/",
117
127
  maxAge: FLOW_TTL_SECONDS,
118
128
  });
119
- return Response.redirect(started.authorizationUrl.href, 302);
129
+ return redirectWithStagedCookies(event, started.authorizationUrl.href);
120
130
  }
121
131
  catch {
122
132
  setResponseStatus(event, 400);
@@ -174,7 +184,7 @@ async function handleMcpOAuthCallback(event, options) {
174
184
  await options.reconfigure();
175
185
  const returnPath = flow.returnUrl ??
176
186
  `/settings/connections?connected=mcp-${encodeURIComponent(flow.name)}`;
177
- return Response.redirect(getAppUrl(event, returnPath), 302);
187
+ return redirectWithStagedCookies(event, getAppUrl(event, returnPath));
178
188
  }
179
189
  catch {
180
190
  setResponseStatus(event, 400);
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-routes.js","sourceRoot":"","sources":["../../src/mcp-client/oauth-routes.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAGjC,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,EACT,iBAAiB,GAElB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,GAE3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,GAAG,mBAAmB,CAAC;A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MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,IAAkB,EAClB,KAAa,EACb,KAAyB,EACzB,KAAa;IAEb,MAAM,YAAY,GAChB,IAAI,CAAC,KAAK,KAAK,MAAM;QACnB,CAAC,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC,KAAK;QACvC,CAAC,CAAC,IAAI,CAAC,KAAK,KAAK,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC;IAC7E,OAAO,CACL,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,GAAG,EAAE;QAC5B,IAAI,CAAC,KAAK,KAAK,KAAK;QACpB,IAAI,CAAC,KAAK,KAAK,KAAK;QACpB,YAAY;QACZ,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ;QAChC,OAAO,IAAI,CAAC,WAAW,KAAK,QAAQ;QACpC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,2CAA2C,CAAC,CACvE,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,IAAa;IAC/B,OAAO,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC;AAC9C,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9E,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAC9B,OAAO,EAAE,KAAK,EAAE,yBAAyB,EAAE,CAAC;AAC9C,CAAC","sourcesContent":["import crypto from \"node:crypto\";\n\nimport type { OAuthClientInformationMixed } from \"@modelcontextprotocol/sdk/shared/auth.js\";\nimport {\n deleteCookie,\n defineEventHandler,\n getCookie,\n getMethod,\n getQuery,\n setCookie,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { getOrgContext } from \"../org/context.js\";\nimport { decryptSecretValue, encryptSecretValue } from \"../secrets/crypto.js\";\nimport { getSession, safeReturnPath } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { getAppUrl, resolveOAuthRedirectUri } from \"../server/google-oauth.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport {\n finishMcpOAuthAuthorization,\n startMcpOAuthAuthorization,\n type McpOAuthDiscoveryState,\n} from \"./oauth-client.js\";\nimport {\n addOAuthRemoteServer,\n normalizeServerName,\n validateRemoteUrl,\n type RemoteMcpScope,\n} from \"./remote-store.js\";\n\nconst FLOW_COOKIE = \"an_mcp_oauth_flow\";\nconst FLOW_TTL_SECONDS = 10 * 60;\n\nexport interface McpOAuthFlow {\n name: string;\n url: string;\n description?: string;\n scope: RemoteMcpScope;\n scopeId: string;\n owner: string;\n orgId?: string;\n redirectUri: string;\n state: string;\n codeVerifier: string;\n clientInformation: OAuthClientInformationMixed;\n discoveryState?: McpOAuthDiscoveryState;\n returnUrl?: string;\n expiresAt: number;\n}\n\nexport interface McpOAuthRoutesOptions {\n reconfigure: () => Promise<void>;\n}\n\nexport function mountMcpOAuthRoutes(\n nitroApp: any,\n options: McpOAuthRoutesOptions,\n): void {\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpOAuthMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/servers/oauth\",\n defineEventHandler(async (event: H3Event) => {\n const method = getMethod(event);\n const pathname = (event.url?.pathname || \"\")\n .replace(/^\\/+/, \"\")\n .replace(/\\/+$/, \"\");\n const parts = pathname ? pathname.split(\"/\") : [];\n if (method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (parts.length === 1 && parts[0] === \"start\") {\n return handleMcpOAuthStart(event);\n }\n if (parts.length === 1 && parts[0] === \"callback\") {\n return handleMcpOAuthCallback(event, options);\n }\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }),\n );\n}\n\nasync function handleMcpOAuthStart(\n event: H3Event,\n): Promise<Response | Record<string, unknown>> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) return unauthorized(event);\n\n const query = getQuery(event);\n const rawUrl = text(query.url);\n const rawName = text(query.name);\n const returnUrl = text(query.return);\n if (!rawUrl || !rawName) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth requires a server name and URL.\" };\n }\n const urlCheck = validateRemoteUrl(rawUrl);\n if (!urlCheck.ok) {\n setResponseStatus(event, 400);\n return { error: urlCheck.error ?? \"MCP server URL is not allowed.\" };\n }\n const name = normalizeServerName(rawName);\n if (!name) {\n setResponseStatus(event, 400);\n return { error: \"MCP server name is invalid.\" };\n }\n\n const requestedScope = query.scope === \"org\" ? \"org\" : \"user\";\n const requestedOrgId = text(query.orgId);\n const org =\n requestedScope === \"org\"\n ? await getOrgContext(event).catch(() => null)\n : null;\n const scope: RemoteMcpScope = requestedScope;\n const scopeId = scope === \"user\" ? session.email : (org?.orgId ?? \"\");\n if (scope === \"org\" && requestedOrgId && requestedOrgId !== scopeId) {\n setResponseStatus(event, 403);\n return {\n error: \"The selected organization is not the active organization.\",\n };\n }\n if (scope === \"org\" && (!scopeId || !isOrgAdmin(org?.role))) {\n setResponseStatus(event, scopeId ? 403 : 400);\n return {\n error: scopeId\n ? \"Only organization owners and admins can connect an org MCP server.\"\n : \"Join an organization before connecting an org MCP server.\",\n };\n }\n\n const redirectUri = resolveOAuthRedirectUri(\n event,\n \"/_agent-native/mcp/servers/oauth/callback\",\n );\n if (!redirectUri) {\n setResponseStatus(event, 400);\n return { error: \"Invalid MCP OAuth redirect URI.\" };\n }\n\n const state = crypto.randomUUID();\n const safeReturnUrl = returnUrl ? safeReturnPath(returnUrl) : undefined;\n try {\n const started = await runWithRequestContext(\n { userEmail: session.email, orgId: org?.orgId ?? undefined },\n () =>\n startMcpOAuthAuthorization({\n serverUrl: urlCheck.url!.toString(),\n redirectUrl: redirectUri,\n state,\n }),\n );\n const flow: McpOAuthFlow = {\n name,\n url: urlCheck.url!.toString(),\n description: text(query.description),\n scope,\n scopeId,\n owner: session.email,\n ...(org?.orgId ? { orgId: org.orgId } : {}),\n redirectUri,\n state: started.state,\n codeVerifier: started.codeVerifier,\n clientInformation: started.clientInformation,\n ...(started.discoveryState\n ? { discoveryState: started.discoveryState }\n : {}),\n ...(safeReturnUrl ? { returnUrl: safeReturnUrl } : {}),\n expiresAt: Date.now() + FLOW_TTL_SECONDS * 1_000,\n };\n setCookie(event, FLOW_COOKIE, encryptSecretValue(JSON.stringify(flow)), {\n httpOnly: true,\n secure: redirectUri.startsWith(\"https://\"),\n sameSite: \"lax\",\n path: \"/\",\n maxAge: FLOW_TTL_SECONDS,\n });\n return Response.redirect(started.authorizationUrl.href, 302);\n } catch {\n setResponseStatus(event, 400);\n return {\n error:\n \"This MCP server could not start OAuth. It may not support standard MCP OAuth discovery or dynamic client registration.\",\n };\n }\n}\n\nasync function handleMcpOAuthCallback(\n event: H3Event,\n options: McpOAuthRoutesOptions,\n): Promise<Response | Record<string, unknown>> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) return unauthorized(event);\n\n const query = getQuery(event);\n const code = text(query.code);\n const state = text(query.state);\n const providerError = text(query.error);\n const flow = readFlow(event);\n deleteCookie(event, FLOW_COOKIE, { path: \"/\" });\n if (providerError || !code || !state) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth authorization was not completed.\" };\n }\n const org =\n flow?.scope === \"org\" ? await getOrgContext(event).catch(() => null) : null;\n if (\n !flow ||\n !isValidMcpOAuthFlow(flow, session.email, org?.orgId ?? undefined, state)\n ) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth state is invalid or expired.\" };\n }\n if (flow.scope === \"org\" && !isOrgAdmin(org?.role)) {\n setResponseStatus(event, 403);\n return {\n error:\n \"Only organization owners and admins can connect an org MCP server.\",\n };\n }\n\n try {\n const finished = await runWithRequestContext(\n { userEmail: session.email, orgId: org?.orgId ?? undefined },\n () =>\n finishMcpOAuthAuthorization({\n serverUrl: flow.url,\n redirectUrl: flow.redirectUri,\n state: flow.state,\n clientInformation: flow.clientInformation,\n codeVerifier: flow.codeVerifier,\n discoveryState: flow.discoveryState,\n authorizationCode: code,\n }),\n );\n const result = await addOAuthRemoteServer(flow.scope, flow.scopeId, {\n name: flow.name,\n url: flow.url,\n description: flow.description,\n credentials: finished.credentials,\n });\n if (!result.ok) {\n setResponseStatus(event, 400);\n return { error: result.error };\n }\n await options.reconfigure();\n const returnPath =\n flow.returnUrl ??\n `/settings/connections?connected=mcp-${encodeURIComponent(flow.name)}`;\n return Response.redirect(getAppUrl(event, returnPath), 302);\n } catch {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth authorization could not be completed.\" };\n }\n}\n\nfunction readFlow(event: H3Event): McpOAuthFlow | null {\n const encrypted = getCookie(event, FLOW_COOKIE);\n if (!encrypted) return null;\n try {\n const parsed = JSON.parse(decryptSecretValue(encrypted)) as McpOAuthFlow;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function isValidMcpOAuthFlow(\n flow: McpOAuthFlow,\n email: string,\n orgId: string | undefined,\n state: string,\n): boolean {\n const scopeMatches =\n flow.scope === \"user\"\n ? flow.scopeId === email && !flow.orgId\n : flow.scope === \"org\" && flow.scopeId === orgId && flow.orgId === orgId;\n return (\n flow.expiresAt >= Date.now() &&\n flow.owner === email &&\n flow.state === state &&\n scopeMatches &&\n typeof flow.scopeId === \"string\" &&\n typeof flow.redirectUri === \"string\" &&\n flow.redirectUri.includes(\"/_agent-native/mcp/servers/oauth/callback\")\n );\n}\n\nfunction isOrgAdmin(role: unknown): boolean {\n return role === \"owner\" || role === \"admin\";\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction unauthorized(event: H3Event) {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n}\n"]}
1
+ {"version":3,"file":"oauth-routes.js","sourceRoot":"","sources":["../../src/mcp-client/oauth-routes.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAGjC,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,EACT,iBAAiB,GAElB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,GAE3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,GAAG,mBAAmB,CAAC;AACxC,MAAM,gBAAgB,GAAG,EAAE,GAAG,EAAE,CAAC;AAuBjC,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,QAAgB;IAEhB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC;QAC1B,QAAQ,EAAE,QAAQ;QAClB,eAAe,EAAE,UAAU;KAC5B,CAAC,CAAC;IACH,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,E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,CAAC;AAC9C,CAAC","sourcesContent":["import crypto from \"node:crypto\";\n\nimport type { OAuthClientInformationMixed } from \"@modelcontextprotocol/sdk/shared/auth.js\";\nimport {\n deleteCookie,\n defineEventHandler,\n getCookie,\n getMethod,\n getQuery,\n setCookie,\n setResponseStatus,\n type H3Event,\n} from \"h3\";\n\nimport { getOrgContext } from \"../org/context.js\";\nimport { decryptSecretValue, encryptSecretValue } from \"../secrets/crypto.js\";\nimport { getSession, safeReturnPath } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { getAppUrl, resolveOAuthRedirectUri } from \"../server/google-oauth.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport {\n finishMcpOAuthAuthorization,\n startMcpOAuthAuthorization,\n type McpOAuthDiscoveryState,\n} from \"./oauth-client.js\";\nimport {\n addOAuthRemoteServer,\n normalizeServerName,\n validateRemoteUrl,\n type RemoteMcpScope,\n} from \"./remote-store.js\";\n\nconst FLOW_COOKIE = \"an_mcp_oauth_flow\";\nconst FLOW_TTL_SECONDS = 10 * 60;\n\nexport interface McpOAuthFlow {\n name: string;\n url: string;\n description?: string;\n scope: RemoteMcpScope;\n scopeId: string;\n owner: string;\n orgId?: string;\n redirectUri: string;\n state: string;\n codeVerifier: string;\n clientInformation: OAuthClientInformationMixed;\n discoveryState?: McpOAuthDiscoveryState;\n returnUrl?: string;\n expiresAt: number;\n}\n\nexport interface McpOAuthRoutesOptions {\n reconfigure: () => Promise<void>;\n}\n\nexport function redirectWithStagedCookies(\n event: H3Event,\n location: string,\n): Response {\n const headers = new Headers({\n Location: location,\n \"Cache-Control\": \"no-store\",\n });\n for (const cookie of event.res?.headers?.getSetCookie?.() ?? []) {\n headers.append(\"set-cookie\", cookie);\n }\n return new Response(null, { status: 302, headers });\n}\n\nexport function mountMcpOAuthRoutes(\n nitroApp: any,\n options: McpOAuthRoutesOptions,\n): void {\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpOAuthMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/servers/oauth\",\n defineEventHandler(async (event: H3Event) => {\n const method = getMethod(event);\n const pathname = (event.url?.pathname || \"\")\n .replace(/^\\/+/, \"\")\n .replace(/\\/+$/, \"\");\n const parts = pathname ? pathname.split(\"/\") : [];\n if (method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (parts.length === 1 && parts[0] === \"start\") {\n return handleMcpOAuthStart(event);\n }\n if (parts.length === 1 && parts[0] === \"callback\") {\n return handleMcpOAuthCallback(event, options);\n }\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }),\n );\n}\n\nasync function handleMcpOAuthStart(\n event: H3Event,\n): Promise<Response | Record<string, unknown>> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) return unauthorized(event);\n\n const query = getQuery(event);\n const rawUrl = text(query.url);\n const rawName = text(query.name);\n const returnUrl = text(query.return);\n if (!rawUrl || !rawName) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth requires a server name and URL.\" };\n }\n const urlCheck = validateRemoteUrl(rawUrl);\n if (!urlCheck.ok) {\n setResponseStatus(event, 400);\n return { error: urlCheck.error ?? \"MCP server URL is not allowed.\" };\n }\n const name = normalizeServerName(rawName);\n if (!name) {\n setResponseStatus(event, 400);\n return { error: \"MCP server name is invalid.\" };\n }\n\n const requestedScope = query.scope === \"org\" ? \"org\" : \"user\";\n const requestedOrgId = text(query.orgId);\n const org =\n requestedScope === \"org\"\n ? await getOrgContext(event).catch(() => null)\n : null;\n const scope: RemoteMcpScope = requestedScope;\n const scopeId = scope === \"user\" ? session.email : (org?.orgId ?? \"\");\n if (scope === \"org\" && requestedOrgId && requestedOrgId !== scopeId) {\n setResponseStatus(event, 403);\n return {\n error: \"The selected organization is not the active organization.\",\n };\n }\n if (scope === \"org\" && (!scopeId || !isOrgAdmin(org?.role))) {\n setResponseStatus(event, scopeId ? 403 : 400);\n return {\n error: scopeId\n ? \"Only organization owners and admins can connect an org MCP server.\"\n : \"Join an organization before connecting an org MCP server.\",\n };\n }\n\n const redirectUri = resolveOAuthRedirectUri(\n event,\n \"/_agent-native/mcp/servers/oauth/callback\",\n );\n if (!redirectUri) {\n setResponseStatus(event, 400);\n return { error: \"Invalid MCP OAuth redirect URI.\" };\n }\n\n const state = crypto.randomUUID();\n const safeReturnUrl = returnUrl ? safeReturnPath(returnUrl) : undefined;\n try {\n const started = await runWithRequestContext(\n { userEmail: session.email, orgId: org?.orgId ?? undefined },\n () =>\n startMcpOAuthAuthorization({\n serverUrl: urlCheck.url!.toString(),\n redirectUrl: redirectUri,\n state,\n }),\n );\n const flow: McpOAuthFlow = {\n name,\n url: urlCheck.url!.toString(),\n description: text(query.description),\n scope,\n scopeId,\n owner: session.email,\n ...(org?.orgId ? { orgId: org.orgId } : {}),\n redirectUri,\n state: started.state,\n codeVerifier: started.codeVerifier,\n clientInformation: started.clientInformation,\n ...(started.discoveryState\n ? { discoveryState: started.discoveryState }\n : {}),\n ...(safeReturnUrl ? { returnUrl: safeReturnUrl } : {}),\n expiresAt: Date.now() + FLOW_TTL_SECONDS * 1_000,\n };\n setCookie(event, FLOW_COOKIE, encryptSecretValue(JSON.stringify(flow)), {\n httpOnly: true,\n secure: redirectUri.startsWith(\"https://\"),\n sameSite: \"lax\",\n path: \"/\",\n maxAge: FLOW_TTL_SECONDS,\n });\n return redirectWithStagedCookies(event, started.authorizationUrl.href);\n } catch {\n setResponseStatus(event, 400);\n return {\n error:\n \"This MCP server could not start OAuth. It may not support standard MCP OAuth discovery or dynamic client registration.\",\n };\n }\n}\n\nasync function handleMcpOAuthCallback(\n event: H3Event,\n options: McpOAuthRoutesOptions,\n): Promise<Response | Record<string, unknown>> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) return unauthorized(event);\n\n const query = getQuery(event);\n const code = text(query.code);\n const state = text(query.state);\n const providerError = text(query.error);\n const flow = readFlow(event);\n deleteCookie(event, FLOW_COOKIE, { path: \"/\" });\n if (providerError || !code || !state) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth authorization was not completed.\" };\n }\n const org =\n flow?.scope === \"org\" ? await getOrgContext(event).catch(() => null) : null;\n if (\n !flow ||\n !isValidMcpOAuthFlow(flow, session.email, org?.orgId ?? undefined, state)\n ) {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth state is invalid or expired.\" };\n }\n if (flow.scope === \"org\" && !isOrgAdmin(org?.role)) {\n setResponseStatus(event, 403);\n return {\n error:\n \"Only organization owners and admins can connect an org MCP server.\",\n };\n }\n\n try {\n const finished = await runWithRequestContext(\n { userEmail: session.email, orgId: org?.orgId ?? undefined },\n () =>\n finishMcpOAuthAuthorization({\n serverUrl: flow.url,\n redirectUrl: flow.redirectUri,\n state: flow.state,\n clientInformation: flow.clientInformation,\n codeVerifier: flow.codeVerifier,\n discoveryState: flow.discoveryState,\n authorizationCode: code,\n }),\n );\n const result = await addOAuthRemoteServer(flow.scope, flow.scopeId, {\n name: flow.name,\n url: flow.url,\n description: flow.description,\n credentials: finished.credentials,\n });\n if (!result.ok) {\n setResponseStatus(event, 400);\n return { error: result.error };\n }\n await options.reconfigure();\n const returnPath =\n flow.returnUrl ??\n `/settings/connections?connected=mcp-${encodeURIComponent(flow.name)}`;\n return redirectWithStagedCookies(event, getAppUrl(event, returnPath));\n } catch {\n setResponseStatus(event, 400);\n return { error: \"MCP OAuth authorization could not be completed.\" };\n }\n}\n\nfunction readFlow(event: H3Event): McpOAuthFlow | null {\n const encrypted = getCookie(event, FLOW_COOKIE);\n if (!encrypted) return null;\n try {\n const parsed = JSON.parse(decryptSecretValue(encrypted)) as McpOAuthFlow;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function isValidMcpOAuthFlow(\n flow: McpOAuthFlow,\n email: string,\n orgId: string | undefined,\n state: string,\n): boolean {\n const scopeMatches =\n flow.scope === \"user\"\n ? flow.scopeId === email && !flow.orgId\n : flow.scope === \"org\" && flow.scopeId === orgId && flow.orgId === orgId;\n return (\n flow.expiresAt >= Date.now() &&\n flow.owner === email &&\n flow.state === state &&\n scopeMatches &&\n typeof flow.scopeId === \"string\" &&\n typeof flow.redirectUri === \"string\" &&\n flow.redirectUri.includes(\"/_agent-native/mcp/servers/oauth/callback\")\n );\n}\n\nfunction isOrgAdmin(role: unknown): boolean {\n return role === \"owner\" || role === \"admin\";\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction unauthorized(event: H3Event) {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n}\n"]}
@@ -41,16 +41,16 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
41
41
  thumbsUpRate: number;
42
42
  avgEvalScore: number;
43
43
  } | {
44
+ error?: undefined;
44
45
  summary: import("./types.js").TraceSummary;
45
46
  spans: import("./types.js").TraceSpan[];
46
47
  id?: undefined;
47
- error?: undefined;
48
48
  ok?: undefined;
49
49
  } | {
50
+ error?: undefined;
50
51
  summary?: undefined;
51
52
  spans?: undefined;
52
53
  id: string;
53
- error?: undefined;
54
54
  ok?: undefined;
55
55
  } | {
56
56
  summary?: undefined;
@@ -59,10 +59,10 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
59
59
  error: any;
60
60
  ok?: undefined;
61
61
  } | {
62
+ error?: undefined;
62
63
  summary?: undefined;
63
64
  spans?: undefined;
64
65
  id?: undefined;
65
66
  ok: boolean;
66
- error?: undefined;
67
67
  }>>;
68
68
  //# sourceMappingURL=routes.d.ts.map
@@ -76,7 +76,6 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
76
76
  }>>;
77
77
  }, z.core.$strip>>, {
78
78
  id?: undefined;
79
- found?: undefined;
80
79
  deleted?: undefined;
81
80
  providers: {
82
81
  id: string;
@@ -89,6 +88,7 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
89
88
  }[];
90
89
  count: number;
91
90
  provider?: undefined;
91
+ found?: undefined;
92
92
  registered?: undefined;
93
93
  label?: undefined;
94
94
  message?: undefined;
@@ -113,21 +113,21 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
113
113
  label?: undefined;
114
114
  message?: undefined;
115
115
  } | {
116
- found?: undefined;
117
116
  providers?: undefined;
118
117
  count?: undefined;
119
118
  provider?: undefined;
119
+ found?: undefined;
120
120
  deleted: boolean;
121
121
  id: string;
122
122
  registered?: undefined;
123
123
  label?: undefined;
124
124
  message?: undefined;
125
125
  } | {
126
- found?: undefined;
127
126
  deleted?: undefined;
128
127
  providers?: undefined;
129
128
  count?: undefined;
130
129
  provider?: undefined;
130
+ found?: undefined;
131
131
  registered: boolean;
132
132
  id: string;
133
133
  label: string;
@@ -309,10 +309,9 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
309
309
  notes?: string | undefined;
310
310
  scope?: "org" | "user" | undefined;
311
311
  }, {
312
- deleted?: undefined;
312
+ message?: undefined;
313
313
  id?: undefined;
314
- provider?: undefined;
315
- found?: undefined;
314
+ deleted?: undefined;
316
315
  providers: {
317
316
  id: string;
318
317
  label: string;
@@ -323,45 +322,46 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
323
322
  updatedAt: number;
324
323
  }[];
325
324
  count: number;
325
+ provider?: undefined;
326
+ found?: undefined;
326
327
  registered?: undefined;
327
328
  label?: undefined;
328
- message?: undefined;
329
329
  } | {
330
+ message?: undefined;
331
+ id?: undefined;
330
332
  deleted?: undefined;
331
333
  count?: undefined;
332
- id?: undefined;
333
334
  providers?: undefined;
334
335
  found: boolean;
335
336
  provider: import("../custom-registry.js").CustomProviderConfig;
336
337
  registered?: undefined;
337
338
  label?: undefined;
338
- message?: undefined;
339
339
  } | {
340
+ message?: undefined;
340
341
  deleted?: undefined;
341
342
  count?: undefined;
342
- provider?: undefined;
343
343
  providers?: undefined;
344
+ provider?: undefined;
344
345
  found: boolean;
345
346
  id: string;
346
347
  registered?: undefined;
347
348
  label?: undefined;
348
- message?: undefined;
349
349
  } | {
350
+ message?: undefined;
350
351
  count?: undefined;
352
+ providers?: undefined;
351
353
  provider?: undefined;
352
354
  found?: undefined;
353
- providers?: undefined;
354
355
  deleted: boolean;
355
356
  id: string;
356
357
  registered?: undefined;
357
358
  label?: undefined;
358
- message?: undefined;
359
359
  } | {
360
360
  deleted?: undefined;
361
361
  count?: undefined;
362
+ providers?: undefined;
362
363
  provider?: undefined;
363
364
  found?: undefined;
364
- providers?: undefined;
365
365
  registered: boolean;
366
366
  id: string;
367
367
  label: string;
@@ -73,6 +73,7 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
73
73
  offset?: unknown;
74
74
  limit?: unknown;
75
75
  }, {
76
+ deleted?: undefined;
76
77
  jobs: {
77
78
  id: string;
78
79
  name: string;
@@ -83,7 +84,6 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
83
84
  updatedAt: string;
84
85
  }[];
85
86
  total: number;
86
- deleted?: undefined;
87
87
  jobId?: undefined;
88
88
  } | {
89
89
  jobs?: undefined;
@@ -91,9 +91,9 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
91
91
  deleted: boolean;
92
92
  jobId: string;
93
93
  } | {
94
+ deleted?: undefined;
94
95
  jobs?: undefined;
95
96
  total?: undefined;
96
- deleted?: undefined;
97
97
  jobId?: undefined;
98
98
  hits: Record<string, unknown>[];
99
99
  offset: number;
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAuJpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAmXjB;AA+ND,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAuJpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAuXjB;AA+ND,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
@@ -350,7 +350,11 @@ export async function run(args, context, selfAppId) {
350
350
  // Terminal states resolve the poll; "input-required" means the remote is
351
351
  // blocked waiting on us, not making progress. Only actively-working
352
352
  // states count as liveness worth surfacing.
353
- const ACTIVELY_WORKING_STATES = new Set(["working", "submitted"]);
353
+ const ACTIVELY_WORKING_STATES = new Set([
354
+ "working",
355
+ "submitted",
356
+ "processing",
357
+ ]);
354
358
  const callStartedAt = Date.now();
355
359
  let lastProgressEmitAt = callStartedAt;
356
360
  const onRemotePollUpdate = (task) => {
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EACL,mBAAmB,EACnB,SAAS,EAC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AO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACvD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n A2ATaskTimeoutError,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed app over A2A. When you know the exact exposed read-only action, pass action + input and omit message; this invokes it directly without starting the other app's model and is the fastest path for bounded data reads. Use message only for natural-language investigation, synthesis, mutations, or multi-step work that needs the other agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Exact read-only action exposed by the target app. Use with input and omit message/taskId to skip the downstream agent loop.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n\n if (action) {\n if (context?.send) {\n context.send({ type: \"agent_call\", agent: agent.name, status: \"start\" });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n return output;\n } finally {\n if (context?.send) {\n context.send({ type: \"agent_call\", agent: agent.name, status: \"done\" });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\"working\", \"submitted\"]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!parts) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQrD,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL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AAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n A2ATaskTimeoutError,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed app over A2A. When you know the exact exposed read-only action, pass action + input and omit message; this invokes it directly without starting the other app's model and is the fastest path for bounded data reads. Use message only for natural-language investigation, synthesis, mutations, or multi-step work that needs the other agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Exact read-only action exposed by the target app. Use with input and omit message/taskId to skip the downstream agent loop.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n\n if (action) {\n if (context?.send) {\n context.send({ type: \"agent_call\", agent: agent.name, status: \"start\" });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n return output;\n } finally {\n if (context?.send) {\n context.send({ type: \"agent_call\", agent: agent.name, status: \"done\" });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\n \"working\",\n \"submitted\",\n \"processing\",\n ]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!parts) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}